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
e4b95460ed54946e233a63f09027dd1dbfa2b0a7
2023-07-07 13:13:41
Sanchith Hegde
ci: add workflow to create tags on schedule (#1642)
false
diff --git a/.github/cocogitto-changelog-template b/.github/cocogitto-changelog-template new file mode 100644 index 00000000000..37591139a7e --- /dev/null +++ b/.github/cocogitto-changelog-template @@ -0,0 +1,56 @@ +{# Using a literal newline to set the newline variable -#} +{% set newline = " +" -%} + +{% set commit_base_url = repository_url ~ "/commit/" -%} +{% set compare_base_url = repository_url ~ "/compare/" -%} +{% set pr_base_url = repository_url ~ "/pull/" -%} + +{% if version.tag -%} + ## {{ version.tag | trim_start_matches(pat="v") }} ({{ date | date(format="%Y-%m-%d") }}) +{% else -%} + {% set from = from.id -%} + {% set to = version.id -%} + + {% set from_shorthand = from.id | truncate(length=7, end="") -%} + {% set to_shorthand = version.id | truncate(length=7, end="") -%} + + ## Unreleased ([`{{ from_shorthand ~ ".." ~ to_shorthand }}`]({{ compare_base_url ~ from_shorthand ~ ".." ~ to_shorthand }})) +{% endif -%} + +{% for type, typed_commits in commits | sort(attribute="type") | group_by(attribute="type") %} +{# The `striptags` removes the HTML comments added while grouping -#} +### {{ type | striptags | trim | upper_first }} +{% for scope, scoped_commits in typed_commits | group_by(attribute="scope") %} +- {{ "**" ~ scope ~ ":" ~ "**" -}} + {% for commit in scoped_commits | sort(attribute="date") -%} + {% set shorthand = commit.id | truncate(length=7, end="") -%} + {% set commit_link = commit_base_url ~ commit.id -%} + {# Replace PR numbers in commit message with PR link -#} + {% set pr_number = commit.summary | split(pat="(#") | last | trim_end_matches(pat=")") -%} + {% set pr_link = "[#" ~ pr_number ~ "](" ~ pr_base_url ~ pr_number ~ ")" -%} + {% if scoped_commits | length != 1 %}{{ newline ~ " - " }}{% else %}{{ " " }}{% endif -%} + {{ commit.summary | upper_first | trim | replace(from="#" ~ pr_number, to=pr_link) }} ([`{{ shorthand }}`]({{ commit_link }})) + {%- endfor -%} +{% endfor -%} + +{% for commit in typed_commits | unscoped | sort(attribute="date") -%} + {% set shorthand = commit.id | truncate(length=7, end="") -%} + {% set commit_link = commit_base_url ~ commit.id -%} + {# Replace PR numbers in commit message with PR link -#} + {% set pr_number = commit.summary | split(pat="(#") | last | trim_end_matches(pat=")") -%} + {% set pr_link = "[#" ~ pr_number ~ "](" ~ pr_base_url ~ pr_number ~ ")" -%} + {{ newline ~ "- "}}{{ commit.summary | upper_first | trim | replace(from="#" ~ pr_number, to=pr_link) }} ([`{{ shorthand }}`]({{ commit_link }})) +{%- endfor %} +{% endfor %} +{% if version.tag and from.tag -%} + **Full Changelog:** [`{{ from.tag ~ "..." ~ version.tag }}`]({{ compare_base_url ~ from.tag ~ "..." ~ version.tag }}) +{%- elif version.tag and from.id -%} + **Full Changelog:** [`{{ from.id ~ "..." ~ version.tag }}`]({{ compare_base_url ~ from.id ~ "..." ~ version.tag }}) +{%- else -%} + {% set from = from.id -%} + {% set to = version.id -%} + {% set from_shorthand = from.id | truncate(length=7, end="") -%} + {% set to_shorthand = version.id | truncate(length=7, end="") -%} + **Full Changelog:** [`{{ from_shorthand ~ "..." ~ to_shorthand }}`]({{ compare_base_url ~ from_shorthand ~ "..." ~ to_shorthand }}) +{%- endif %} diff --git a/.github/workflows/release-new-version.yml b/.github/workflows/release-new-version.yml new file mode 100644 index 00000000000..3b54c586df2 --- /dev/null +++ b/.github/workflows/release-new-version.yml @@ -0,0 +1,52 @@ +name: Release a new version + +on: + schedule: + - cron: "30 12 * * *" # Run workflow at 6 PM IST + + workflow_dispatch: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +env: + # 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 + +jobs: + create-release: + name: Release a new version + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + with: + fetch-depth: 0 + token: ${{ secrets.AUTO_RELEASE_PAT }} + + - name: Install Rust + uses: dtolnay/rust-toolchain@master + with: + toolchain: stable + + - name: Install cocogitto + uses: baptiste0928/[email protected] + with: + crate: cocogitto + version: 5.4.0 + + - name: Update changelog and create tag + shell: bash + run: | + git config --local user.name 'github-actions[bot]' + git config --local user.email '41898282+github-actions[bot]@users.noreply.github.com' + cog bump --auto + + - name: Push created tag + shell: bash + run: git push --atomic --tags diff --git a/.typos.toml b/.typos.toml index 8b98c0fc126..4fb387dd33e 100644 --- a/.typos.toml +++ b/.typos.toml @@ -23,6 +23,8 @@ encrypter = "encrypter" # Used by the `ring` crate nin = "nin" # National identification number, a field used by PayU connector substituters = "substituters" # Present in `flake.nix` unsuccess = "unsuccess" # Used in cryptopay request +ba = "ba" # ignore minor commit conversions +ede = "ede" # ignore minor commit conversions [files] extend-exclude = [ diff --git a/CHANGELOG.md b/CHANGELOG.md index c38ac5371aa..9a58d75a22f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,398 @@ All notable changes to HyperSwitch will be documented here. +- - - +## 1.0.5 (2023-07-06) + +### Features + +- **connector:** [Stripe] Add support for WeChat Pay and Qr code support in next action ([#1555](https://github.com/juspay/hyperswitch/pull/1555)) ([`a15a77d`](https://github.com/juspay/hyperswitch/commit/a15a77dea36fd13e92bd64014fc25014d51a3548)) +- **test:** Add support to run UI tests in CI pipeline ([#1539](https://github.com/juspay/hyperswitch/pull/1539)) ([`21f5e20`](https://github.com/juspay/hyperswitch/commit/21f5e20929dfef9ffdd2f20fb0fd190c59e35316)) + +### Bug Fixes + +- **connector:** [Rapyd] Add router_return_url in 3DS request ([#1621](https://github.com/juspay/hyperswitch/pull/1621)) ([`e913bfc`](https://github.com/juspay/hyperswitch/commit/e913bfc4958da613cd352eca9bc38b23ab7ac38e)) + +### Refactors + +- **payments:** Error message of manual retry ([#1617](https://github.com/juspay/hyperswitch/pull/1617)) ([`fad4895`](https://github.com/juspay/hyperswitch/commit/fad4895f756811bb0af9ccbc69b9f6dfff3ab32f)) + +**Full Changelog:** [`v1.0.4...v1.0.5`](https://github.com/juspay/hyperswitch/compare/v1.0.4...v1.0.5) + +- - - + +## 1.0.4 (2023-07-05) + +### Features + +- **connector:** [DummyConnector] add new dummy connectors ([#1609](https://github.com/juspay/hyperswitch/pull/1609)) ([`cf7b672`](https://github.com/juspay/hyperswitch/commit/cf7b67286c5102f457595e287f4f9315046fe267)) +- **payments:** Add connector_metadata, metadata and feature_metadata fields in payments, remove udf field ([#1595](https://github.com/juspay/hyperswitch/pull/1595)) ([`e713b62`](https://github.com/juspay/hyperswitch/commit/e713b62ae3444ef9a9a8984f9fd593936734dc41)) +- **router:** + - Modify attempt_id generation logic to accommodate payment_id as prefix ([#1596](https://github.com/juspay/hyperswitch/pull/1596)) ([`82e1bf0`](https://github.com/juspay/hyperswitch/commit/82e1bf0d168c60733775f933c838b6f9a6301cad)) + - Add card_info in payment_attempt table if not provided in request ([#1538](https://github.com/juspay/hyperswitch/pull/1538)) ([`5628985`](https://github.com/juspay/hyperswitch/commit/5628985c400500d031b0da2c7cef1b04118a096d)) +- List payment_methods with the required fields in each method ([#1310](https://github.com/juspay/hyperswitch/pull/1310)) ([`6447b04`](https://github.com/juspay/hyperswitch/commit/6447b04574e941b9214239bf5b65b7c1a229dfd6)) + +### Bug Fixes + +- **payment_methods:** Return an empty array when the merchant does not have any payment methods ([#1601](https://github.com/juspay/hyperswitch/pull/1601)) ([`04c60d7`](https://github.com/juspay/hyperswitch/commit/04c60d73cb34a3432fcb9fa24af95022b16048b2)) + +### Refactors + +- **fix:** [Nuvei] fix currency conversion issue in nuvei cards ([#1605](https://github.com/juspay/hyperswitch/pull/1605)) ([`1b22638`](https://github.com/juspay/hyperswitch/commit/1b226389bd5c8c5dba211dc058c981d8d543f45a)) +- **redis_interface:** Changed the in the get_options value from true to false ([#1606](https://github.com/juspay/hyperswitch/pull/1606)) ([`737aeb6`](https://github.com/juspay/hyperswitch/commit/737aeb6b0a083bdbcde169d4cfeb40ebc6f4378e)) +- **router:** Add psync task to process tracker after building connector request in payments flow ([#1603](https://github.com/juspay/hyperswitch/pull/1603)) ([`e978e9d`](https://github.com/juspay/hyperswitch/commit/e978e9d66bcb8ea20837fa0e87aa0b0ffffac622)) + +### Miscellaneous Tasks + +- **connector-template:** Update connector template code ([#1612](https://github.com/juspay/hyperswitch/pull/1612)) ([`8c90d0a`](https://github.com/juspay/hyperswitch/commit/8c90d0a78c99c6934a505324e07985eb31ac2f32)) + +**Full Changelog:** [`v1.0.3...v1.0.4`](https://github.com/juspay/hyperswitch/compare/v1.0.3...v1.0.4) + +- - - + +## 1.0.3 (2023-07-04) + +### Features + +- **compatibility:** Add straight through routing and udf mapping in setup intent ([#1536](https://github.com/juspay/hyperswitch/pull/1536)) ([`1e87f3d`](https://github.com/juspay/hyperswitch/commit/1e87f3d6732fea1b44e2caa17ececb10203d9798)) +- **connector:** + - [Adyen] implement Alipay HK for Adyen ([#1547](https://github.com/juspay/hyperswitch/pull/1547)) ([`2f9c289`](https://github.com/juspay/hyperswitch/commit/2f9c28938f95a58532604817b1ed370ef8285dd8)) + - [Mollie] Implement Przelewy24 and BancontactCard Bank Redirects for Mollie connector ([#1303](https://github.com/juspay/hyperswitch/pull/1303)) ([`f091be6`](https://github.com/juspay/hyperswitch/commit/f091be60cc628eff4a3537cd6f5d00402a08650d)) + - [Multisafepay] implement Googlepay for Multisafepay ([#1456](https://github.com/juspay/hyperswitch/pull/1456)) ([`2136326`](https://github.com/juspay/hyperswitch/commit/213632616642522df0983e62a69fb48d170f4e80)) + - [TrustPay] Add Google Pay support ([#1515](https://github.com/juspay/hyperswitch/pull/1515)) ([`47cd08a`](https://github.com/juspay/hyperswitch/commit/47cd08a0b07d457793d376b6cca3143011426f22)) + - [Airwallex] Implement Google Pay in Wallets ([#1316](https://github.com/juspay/hyperswitch/pull/1316)) ([`7489c87`](https://github.com/juspay/hyperswitch/commit/7489c870d9d85f169fb7fca469778fad5b2cc37a)) + - [Multisafepay] implement Paypal for Multisafepay ([#1459](https://github.com/juspay/hyperswitch/pull/1459)) ([`2c10e0b`](https://github.com/juspay/hyperswitch/commit/2c10e0b05c571a7c34c8f3f641b401bae68132a0)) +- **db:** Implement `ConfigInterface` for `MockDb` ([#1586](https://github.com/juspay/hyperswitch/pull/1586)) ([`2ac1f2e`](https://github.com/juspay/hyperswitch/commit/2ac1f2e29ec08c457781a7456cb30a80a2bdd1f4)) +- **email:** Implement process_tracker for scheduling email when api_key is about to expire ([#1233](https://github.com/juspay/hyperswitch/pull/1233)) ([`ee7cdef`](https://github.com/juspay/hyperswitch/commit/ee7cdef10754a72106271bf164e0acd751a8d35f)) +- **payment_method:** [upi] add new payment method and use in iatapay ([#1528](https://github.com/juspay/hyperswitch/pull/1528)) ([`2d11bf5`](https://github.com/juspay/hyperswitch/commit/2d11bf5b3ac94b207978ef7a67d3ab70bd77a139)) +- **payments:** Add field manual_retry_allowed in payments response ([#1298](https://github.com/juspay/hyperswitch/pull/1298)) ([`44b8da4`](https://github.com/juspay/hyperswitch/commit/44b8da430c5e5b0114e73b80c5a49d06beebf350)) +- **router:** + - Add requeue support for payments and fix duplicate entry error in process tracker for requeued payments ([#1567](https://github.com/juspay/hyperswitch/pull/1567)) ([`b967d23`](https://github.com/juspay/hyperswitch/commit/b967d232519b106d88d79da2d6baec550c9256df)) + - Add metrics for webhooks ([#1266](https://github.com/juspay/hyperswitch/pull/1266)) ([`d528132`](https://github.com/juspay/hyperswitch/commit/d528132932266aaa793bfe27fa6f40dcd56a8e6a)) by [email protected] +- Feat: add `merchant_name` field in the response body ([#1280](https://github.com/juspay/hyperswitch/pull/1280)) ([`dd4ba63`](https://github.com/juspay/hyperswitch/commit/dd4ba63cc4940b3e968a2a8eaf841de2ae14b3f8)) +- Add `GenericNotFoundError` error response and `set_key_if_not_exists_with_expiry` Redis command ([#1526](https://github.com/juspay/hyperswitch/pull/1526)) ([`9a88a32`](https://github.com/juspay/hyperswitch/commit/9a88a32d5092cdacacc41bc8ec12ff56d4f53adf)) + +### Bug Fixes + +- **disputes:** Update 4xx error for Files - Delete endpoint ([#1531](https://github.com/juspay/hyperswitch/pull/1531)) ([`eabe16c`](https://github.com/juspay/hyperswitch/commit/eabe16cc8516335b402fdecfd299d26c89cd8ce7)) +- **payment_method:** Do not save card in locker in case of error from connector ([#1341](https://github.com/juspay/hyperswitch/pull/1341)) ([`9794079`](https://github.com/juspay/hyperswitch/commit/9794079c797dcb30edcd88e93e8448948321287c)) by [email protected] +- Return nick name for each card while listing saved cards ([#1391](https://github.com/juspay/hyperswitch/pull/1391)) ([`4808af3`](https://github.com/juspay/hyperswitch/commit/4808af37503ed9cf506ac16c5d7cc68a79e30050)) +- Add appropriate printable text for Result returned from delete_tokenized_data() ([#1369](https://github.com/juspay/hyperswitch/pull/1369)) ([`cebe993`](https://github.com/juspay/hyperswitch/commit/cebe993660c1afbbd0c442c0811f215286ccff8d)) + +### Refactors + +- **connector:** [ACI] Use verbose names for `InstructionSource` variants ([#1575](https://github.com/juspay/hyperswitch/pull/1575)) ([`df01f8f`](https://github.com/juspay/hyperswitch/commit/df01f8f382ef68ff1798e5c8023f1aef83deeb2b)) +- **payment_methods:** Added clone derivation for PaymentMethodId ([#1568](https://github.com/juspay/hyperswitch/pull/1568)) ([`6739b59`](https://github.com/juspay/hyperswitch/commit/6739b59bc8c94650e398901b402e977de28661e6)) +- **payments_start:** Remove redundant call to fetch payment method data ([#1574](https://github.com/juspay/hyperswitch/pull/1574)) ([`6dd61b6`](https://github.com/juspay/hyperswitch/commit/6dd61b62ef322462e1a592e2dd3ef31683507f65)) +- Add payment id and merchant id to logs ([#1548](https://github.com/juspay/hyperswitch/pull/1548)) ([`9a48c9e`](https://github.com/juspay/hyperswitch/commit/9a48c9ef723f1028bced71396a4f450af5703e82)) + +### Miscellaneous Tasks + +- Update connector creds ([#1597](https://github.com/juspay/hyperswitch/pull/1597)) ([`d5b3f7c`](https://github.com/juspay/hyperswitch/commit/d5b3f7c0301b1cca809b37ce1288c939ee4a7277)) + +- - - + +## 1.0.2 (2023-06-30) + +### Features + +- **connector:** + - [Opayo] Add script generated template code ([#1295](https://github.com/juspay/hyperswitch/pull/1295)) ([`60e15dd`](https://github.com/juspay/hyperswitch/commit/60e15ddabbf7ca81ace088a08814c626215301eb)) + - [ACI] implement Card Mandates for ACI ([#1174](https://github.com/juspay/hyperswitch/pull/1174)) ([`15c2a70`](https://github.com/juspay/hyperswitch/commit/15c2a70b427df1c7ec719c2e738f83be1b6a5662)) + - [cryptopay] add new connector cryptopay, authorize, sync, webhook and testcases ([#1511](https://github.com/juspay/hyperswitch/pull/1511)) ([`7bb0aa5`](https://github.com/juspay/hyperswitch/commit/7bb0aa5ceb2e0d12b590602b9ad7c6803e1d5c43)) +- **router:** Add filters for refunds ([#1501](https://github.com/juspay/hyperswitch/pull/1501)) ([`88860b9`](https://github.com/juspay/hyperswitch/commit/88860b9c0be0bc91bcdd6f89b60eb43a18b83b08)) + +### Testing + +- **connector:** Add tests for Paypal, Adyen and Airwallex ([#1290](https://github.com/juspay/hyperswitch/pull/1290)) ([`cd4dbcb`](https://github.com/juspay/hyperswitch/commit/cd4dbcb3f6aba9a4b40f28a1ac5f0bb00a21029e)) + +**Full Changelog:** [`v1.0.1...v1.0.2`](https://github.com/juspay/hyperswitch/compare/v1.0.1...v1.0.2) + +- - - + +## 1.0.1 (2023-06-28) + +### Features + +- **connector:** + - Add connector cashtocode ([#1429](https://github.com/juspay/hyperswitch/pull/1429)) ([`784847b`](https://github.com/juspay/hyperswitch/commit/784847b08ca00ee5b77abf6faaeb9673b57adec3)) + - [Adyen] Add support for Samsung Pay ([#1525](https://github.com/juspay/hyperswitch/pull/1525)) ([`33309da`](https://github.com/juspay/hyperswitch/commit/33309daf5ced2197c030d2c51b02a9d9d1878b9f)) + - [Noon] add error response handling in payments response ([#1494](https://github.com/juspay/hyperswitch/pull/1494)) ([`8254555`](https://github.com/juspay/hyperswitch/commit/82545555d79da654575decf5ed02aa6f12df6469)) + - [Stripe] Add support for refund webhooks ([#1488](https://github.com/juspay/hyperswitch/pull/1488)) ([`e6529b6`](https://github.com/juspay/hyperswitch/commit/e6529b6a63760fd78c26084f96aeeff7e6f844dc)) + - [Payme] Add template code for Payme connector ([#1486](https://github.com/juspay/hyperswitch/pull/1486)) ([`5305a7b`](https://github.com/juspay/hyperswitch/commit/5305a7b2f849fc29a786968ba02b9522d82164e4)) + - [Mollie] Implement Sepa Direct Debit ([#1301](https://github.com/juspay/hyperswitch/pull/1301)) ([`b4b6440`](https://github.com/juspay/hyperswitch/commit/b4b6440a9135b75ae76eff1c1bb8c013aa2dd7f3)) + - Add refund and dispute webhooks for Rapyd ([#1313](https://github.com/juspay/hyperswitch/pull/1313)) ([`db011f3`](https://github.com/juspay/hyperswitch/commit/db011f3d7690458c64c8bba75920b0646b502646)) +- **db:** Implement `EphemeralKeyInterface` for `MockDb` ([#1285](https://github.com/juspay/hyperswitch/pull/1285)) ([`8c93904`](https://github.com/juspay/hyperswitch/commit/8c93904c3e34cb7543ce10e022fa5a7f5a10e56f)) +- **router:** + - Implement `PaymentMethodInterface` for `MockDB` ([#1535](https://github.com/juspay/hyperswitch/pull/1535)) ([`772fc84`](https://github.com/juspay/hyperswitch/commit/772fc8457749ceed121f6f7bd9244e4d8b66350e)) + - Add `connector_transaction_id` in payments response ([#1542](https://github.com/juspay/hyperswitch/pull/1542)) ([`1a8f5ff`](https://github.com/juspay/hyperswitch/commit/1a8f5ff2258a90f9cef5bcf5a1891804250f4560)) + +### Bug Fixes + +- **connector:** + - [Braintree] Map `SubmittedForSettlement` status to `Pending` instead of `Charged` ([#1508](https://github.com/juspay/hyperswitch/pull/1508)) ([`9cc14b8`](https://github.com/juspay/hyperswitch/commit/9cc14b80445ed6b036e7ebc3ea02371465f20f62)) + - [Cybersource] Throw proper unauthorised message ([#1529](https://github.com/juspay/hyperswitch/pull/1529)) ([`3e284b0`](https://github.com/juspay/hyperswitch/commit/3e284b04b1f02f190cd386f1ee6149bf7b25aa87)) + - [Bluesnap] add cardholder info in bluesnap payment request ([#1540](https://github.com/juspay/hyperswitch/pull/1540)) ([`0bc1e04`](https://github.com/juspay/hyperswitch/commit/0bc1e043fe2ff4e6514ef6c87fab2bb7c0911453)) +- **payment_methods:** Return appropriate error when basilisk locker token expires ([#1517](https://github.com/juspay/hyperswitch/pull/1517)) ([`9969c93`](https://github.com/juspay/hyperswitch/commit/9969c930a9fc0e983f77e38da45710b87e1203d1)) +- **routes:** Register handler for retrieve disput evidence endpoint ([#1516](https://github.com/juspay/hyperswitch/pull/1516)) ([`6bc4188`](https://github.com/juspay/hyperswitch/commit/6bc4188ff981f9539637752464d07e18fba4ba39)) +- Invalidate all cache on invalidate cache route ([#1498](https://github.com/juspay/hyperswitch/pull/1498)) ([`2c6cc6a`](https://github.com/juspay/hyperswitch/commit/2c6cc6ab50b1cc83d14f8e164c5e780392288d5f)) +- Add 3ds card_holder_info and 2 digit expiry year ([#1560](https://github.com/juspay/hyperswitch/pull/1560)) ([`5f83fae`](https://github.com/juspay/hyperswitch/commit/5f83fae3c4b84e0d512a536d936d17c4f44b23ef)) +- Add config create route back ([#1559](https://github.com/juspay/hyperswitch/pull/1559)) ([`379d1d1`](https://github.com/juspay/hyperswitch/commit/379d1d1375783f2c35edbf4dda6bbb0eb9351a3c)) + +### Performance + +- **logging:** Remove redundant heap allocation present in the logging framework ([#1487](https://github.com/juspay/hyperswitch/pull/1487)) ([`b1ed934`](https://github.com/juspay/hyperswitch/commit/b1ed93468cf8c54f2ae53420c0293a2e5a15fca4)) + +### Refactors + +- **mandates:** Refactor mandates to check for misleading error codes in mandates ([#1377](https://github.com/juspay/hyperswitch/pull/1377)) ([`a899c97`](https://github.com/juspay/hyperswitch/commit/a899c9738941fd1a34841369c9a13b2ac49dda9c)) + +### Testing + +- **connector:** + - [Checkout] Add tests for 3DS and Gpay ([#1267](https://github.com/juspay/hyperswitch/pull/1267)) ([`218803a`](https://github.com/juspay/hyperswitch/commit/218803aaa75e4acdf145872056da76055424a595)) + - [Adyen] Add test for bank debits, bank redirects, and wallets ([#1260](https://github.com/juspay/hyperswitch/pull/1260)) ([`eddcc34`](https://github.com/juspay/hyperswitch/commit/eddcc3455b91569d60ecc955c0ba62d71dc8fefd)) + - [Bambora] Add tests for 3DS ([#1254](https://github.com/juspay/hyperswitch/pull/1254)) ([`295d41a`](https://github.com/juspay/hyperswitch/commit/295d41abba3ff02d7942534163ebc24ae57adf44)) + - [Mollie] Add tests for PayPal, Sofort, Ideal, Giropay and EPS ([#1246](https://github.com/juspay/hyperswitch/pull/1246)) ([`9ea9e55`](https://github.com/juspay/hyperswitch/commit/9ea9e5523b480d862d94cf22b92eb8533f0b8175)) + - Add tests for Globalpay and Bluesnap ([#1281](https://github.com/juspay/hyperswitch/pull/1281)) ([`c5ff6ed`](https://github.com/juspay/hyperswitch/commit/c5ff6ed45b6d053de1b5aa9db918a62887feb417)) + - [Shift4] Add tests for 3DS and Bank Redirect ([#1250](https://github.com/juspay/hyperswitch/pull/1250)) ([`041ecbb`](https://github.com/juspay/hyperswitch/commit/041ecbbcf39bbba5e2c274c7b6a485f3f096aa50)) + +### Miscellaneous Tasks + +- **connector:** [Payme] disable payme connector in code ([#1561](https://github.com/juspay/hyperswitch/pull/1561)) ([`3cd4746`](https://github.com/juspay/hyperswitch/commit/3cd474604d04875a9e39ea0ee520dbb59b130867)) + +**Full Changelog:** [`v1.0.0...v1.0.1`](https://github.com/juspay/hyperswitch/compare/v1.0.0...v1.0.1) + +- - - + +## 1.0.0 (2023-06-23) + +### Features + +- **connector:** Enforce logging for connector requests ([#1467](https://github.com/juspay/hyperswitch/pull/1467)) ([`e575fde`](https://github.com/juspay/hyperswitch/commit/e575fde6dc22675af18e80b005872dec2f6cc22c)) +- **router:** Add route to invalidate cache entry ([#1100](https://github.com/juspay/hyperswitch/pull/1100)) ([`21f2ccd`](https://github.com/juspay/hyperswitch/commit/21f2ccd47c3627c760ade1b5fe90c3c13a46210e)) +- Fetch merchant key store only once per session ([#1400](https://github.com/juspay/hyperswitch/pull/1400)) ([`d321aa1`](https://github.com/juspay/hyperswitch/commit/d321aa1f7296932074ce86d6d0df97f312777bc7)) +- Add default pm_filters ([#1493](https://github.com/juspay/hyperswitch/pull/1493)) ([`69e9e51`](https://github.com/juspay/hyperswitch/commit/69e9e518f40c4267c1d58b455b83088e431f767f)) + +### Bug Fixes + +- **compatibility:** Add metadata object in both payment_intent and setup_intent request ([#1519](https://github.com/juspay/hyperswitch/pull/1519)) ([`6ec6272`](https://github.com/juspay/hyperswitch/commit/6ec6272f2acae6d5cb5e3120b2dbcc87ae2875ec)) +- **configs:** Remove pix and twint from pm_filters for adyen ([#1509](https://github.com/juspay/hyperswitch/pull/1509)) ([`c1e8ad1`](https://github.com/juspay/hyperswitch/commit/c1e8ad194f45c2d08cb3975237ec4d266cf4ee83)) +- **connector:** + - [NMI] Fix Psync flow ([#1474](https://github.com/juspay/hyperswitch/pull/1474)) ([`2fdd14c`](https://github.com/juspay/hyperswitch/commit/2fdd14c38292653494c65560fff0aac6fbc6a726)) + - [DummyConnector] change dummy connector names ([#1328](https://github.com/juspay/hyperswitch/pull/1328)) ([`6645c4d`](https://github.com/juspay/hyperswitch/commit/6645c4d123399e2b6615c02932adf4571b8bcd91)) + - [ACI] fix cancel and refund request encoder ([#1507](https://github.com/juspay/hyperswitch/pull/1507)) ([`cf72dcd`](https://github.com/juspay/hyperswitch/commit/cf72dcdbb6d2164b83b22593f4ebd1be9c774b58)) + - Convert state of US and CA in ISO format for cybersource connector ([#1506](https://github.com/juspay/hyperswitch/pull/1506)) ([`4a047ce`](https://github.com/juspay/hyperswitch/commit/4a047ce133661d160c028d502b5f5eb96b7bdb12)) + - [Trustpay] handle errors fields as optional in TrustpayErrorResponse object ([#1514](https://github.com/juspay/hyperswitch/pull/1514)) ([`efe1ed9`](https://github.com/juspay/hyperswitch/commit/efe1ed9b770dc0924cf00f76ed02e8777bea4ed2)) + - [TrustPay] change the request encoding ([#1530](https://github.com/juspay/hyperswitch/pull/1530)) ([`692d370`](https://github.com/juspay/hyperswitch/commit/692d3704976aa80ea10dfc4cea808f8dba59959e)) + - Fix url_encode issue for paypal and payu ([#1534](https://github.com/juspay/hyperswitch/pull/1534)) ([`e296a49`](https://github.com/juspay/hyperswitch/commit/e296a49b623004784cece505ab08b172a5aa796c)) +- **core:** `payment_method_type` not set in the payment attempt when making a recurring mandate payment ([#1415](https://github.com/juspay/hyperswitch/pull/1415)) ([`38b9e59`](https://github.com/juspay/hyperswitch/commit/38b9e59b7511b0486556f9899870d1c9c95c7518)) +- **encryption:** Do not log encrypted binary data ([#1352](https://github.com/juspay/hyperswitch/pull/1352)) ([`b0c103a`](https://github.com/juspay/hyperswitch/commit/b0c103a19304cc21e9988675786c3c17dac9fb63)) +- **errors:** Use `format!()` for `RefundNotPossibleError` ([#1518](https://github.com/juspay/hyperswitch/pull/1518)) ([`1da411e`](https://github.com/juspay/hyperswitch/commit/1da411e67a2e30e773beb87228cd2fb1fd4b1507)) +- **payments:** Fix client secret parsing ([#1358](https://github.com/juspay/hyperswitch/pull/1358)) ([`2b71d4d`](https://github.com/juspay/hyperswitch/commit/2b71d4d8c40c3697e902398fc76bc1256d5b25ee)) +- **process_tracker:** Log and ignore the duplicate entry error ([#1502](https://github.com/juspay/hyperswitch/pull/1502)) ([`424e77c`](https://github.com/juspay/hyperswitch/commit/424e77c912e3f9722660b424581aaf9b132fd3a6)) +- **update_trackers:** Handle preprocessing steps status update ([#1496](https://github.com/juspay/hyperswitch/pull/1496)) ([`b452314`](https://github.com/juspay/hyperswitch/commit/b45231468db1e71a113ecc1f35841e80f82d8b3f)) +- Add requires_customer_action status to payment confirm ([#1500](https://github.com/juspay/hyperswitch/pull/1500)) ([`6944415`](https://github.com/juspay/hyperswitch/commit/6944415da14cda3e9d5fbef62805d7b18d64eacf)) +- Update adyen payment method supported countries and currencies in development.toml ([#1401](https://github.com/juspay/hyperswitch/pull/1401)) ([`5274f53`](https://github.com/juspay/hyperswitch/commit/5274f53dcc250804e59c1c13b2fe71daa36195e7)) + +### Refactors + +- **core:** Rename `MandateTxnType` to `MandateTransactionType` ([#1322](https://github.com/juspay/hyperswitch/pull/1322)) ([`1069172`](https://github.com/juspay/hyperswitch/commit/10691728d2d6926672d12de124237d1842085cc7)) +- **fix:** [Stripe] Fix bug in Stripe ([#1505](https://github.com/juspay/hyperswitch/pull/1505)) ([`957d5e0`](https://github.com/juspay/hyperswitch/commit/957d5e0f62ca43d1df3ee39b88ed6c7f6e92a099)) +- **refunds:** Refactor refunds create to check for unintended 5xx ([#1332](https://github.com/juspay/hyperswitch/pull/1332)) ([`ff17b62`](https://github.com/juspay/hyperswitch/commit/ff17b62dc27092b6e04d19604e02e8f492c19efb)) +- Add serde rename_all for refund enums ([#1520](https://github.com/juspay/hyperswitch/pull/1520)) ([`0c86243`](https://github.com/juspay/hyperswitch/commit/0c8624334c480a42bd5f06fced4f38ab66cdf07f)) + +### Build System / Dependencies + +- **deps:** Bump openssl from 0.10.54 to 0.10.55 ([#1503](https://github.com/juspay/hyperswitch/pull/1503)) ([`c4f9029`](https://github.com/juspay/hyperswitch/commit/c4f9029c8ba3ea2570688e00e551ea979859d3be)) + +**Full Changelog:** [`v0.6.0...v1.0.0`](https://github.com/juspay/hyperswitch/compare/v0.6.0...v1.0.0) + +- - - + +## 0.6.0 (2023-06-20) + +### Features + +- **compatibility:** + - Add receipt_ipaddress and user_agent in stripe compatibility ([#1417](https://github.com/juspay/hyperswitch/pull/1417)) ([`de2a6e8`](https://github.com/juspay/hyperswitch/commit/de2a6e86d767e77b7ab15b21832747531231453b)) + - Wallet support compatibility layer ([#1214](https://github.com/juspay/hyperswitch/pull/1214)) ([`3e64321`](https://github.com/juspay/hyperswitch/commit/3e64321bfd25cfeb6b02b70188c8e08b3cd4bfcc)) +- **connector:** + - [Noon] Add Card Payments, Capture, Void and Refund ([#1207](https://github.com/juspay/hyperswitch/pull/1207)) ([`2761036`](https://github.com/juspay/hyperswitch/commit/27610361b948c56f3422caa7c70beeb9e87bb69c)) + - [Noon] Add Card Mandates and Webhooks Support ([#1243](https://github.com/juspay/hyperswitch/pull/1243)) ([`ba8a17d`](https://github.com/juspay/hyperswitch/commit/ba8a17d66f12fce01fa3a2d50bd9a5591bf8ef2f)) + - [Noon] Add reference id in Order Struct ([#1371](https://github.com/juspay/hyperswitch/pull/1371)) ([`f0cd5ee`](https://github.com/juspay/hyperswitch/commit/f0cd5ee20d6f8a836f7b1f7117c2d0e43014eaba)) + - [Zen] add apple pay redirect flow support for zen connector ([#1383](https://github.com/juspay/hyperswitch/pull/1383)) ([`b3b16fc`](https://github.com/juspay/hyperswitch/commit/b3b16fcf95321f7ade05ed5b6678dcd851ba6ee5)) + - Mask pii information in connector request and response for stripe, bluesnap, checkout, zen ([#1435](https://github.com/juspay/hyperswitch/pull/1435)) ([`5535159`](https://github.com/juspay/hyperswitch/commit/5535159d5c2cc7278c9e189dcf3629efd67e6fb5)) + - Add request & response logs for top 4 connector ([#1427](https://github.com/juspay/hyperswitch/pull/1427)) ([`1e61f39`](https://github.com/juspay/hyperswitch/commit/1e61f396bd02ca66c7448776a5aab045dc06df10)) + - [Noon] Add GooglePay, ApplePay, PayPal Support ([#1450](https://github.com/juspay/hyperswitch/pull/1450)) ([`8ebcc1c`](https://github.com/juspay/hyperswitch/commit/8ebcc1ce39356307667e8c70be0ed5bdf034ed50)) + - [Zen] add google pay redirect flow support ([#1454](https://github.com/juspay/hyperswitch/pull/1454)) ([`3a225b2`](https://github.com/juspay/hyperswitch/commit/3a225b2118c52f7b28a40a87bbcd8b126b01eeef)) +- **core:** Add signature to outgoing webhooks ([#1249](https://github.com/juspay/hyperswitch/pull/1249)) ([`3534cac`](https://github.com/juspay/hyperswitch/commit/3534caca68e18d222c685fa1ea50bc407ee3178e)) +- **db:** + - Implement `RefundInterface` for `MockDb` ([#1277](https://github.com/juspay/hyperswitch/pull/1277)) ([`10691c5`](https://github.com/juspay/hyperswitch/commit/10691c5fce630d60aade862080d25c62a5cddb44)) + - Implement `DisputeInterface` for `MockDb` ([#1345](https://github.com/juspay/hyperswitch/pull/1345)) ([`e5e39a7`](https://github.com/juspay/hyperswitch/commit/e5e39a74911057849748424dbefda7ac26bab45d)) + - Implement `LockerMockInterface` for `MockDb` ([#1347](https://github.com/juspay/hyperswitch/pull/1347)) ([`1322aa7`](https://github.com/juspay/hyperswitch/commit/1322aa757902662a1bd90cc3f09e887a7fdbf841)) + - Implement `MerchantConnectorAccountInterface` for `MockDb` ([#1248](https://github.com/juspay/hyperswitch/pull/1248)) ([`b002c97`](https://github.com/juspay/hyperswitch/commit/b002c97c9c11f7d725aa7ab5b29d49988baa6aea)) + - Implement `MandateInterface` for `MockDb` ([#1387](https://github.com/juspay/hyperswitch/pull/1387)) ([`2555c37`](https://github.com/juspay/hyperswitch/commit/2555c37adab4b0ab10f3e6d507e1b93b3eab1c67)) +- **headers:** Add optional header masking feature to outbound request ([#1320](https://github.com/juspay/hyperswitch/pull/1320)) ([`fc6acd0`](https://github.com/juspay/hyperswitch/commit/fc6acd04cb28f02a4f52ec77d8ae003957183ff2)) +- **kms:** Reduce redundant kms calls ([#1264](https://github.com/juspay/hyperswitch/pull/1264)) ([`71a17c6`](https://github.com/juspay/hyperswitch/commit/71a17c682e87a708adbea4f2d9f99a4a0172e76e)) +- **logging:** Logging the request payload during `BeginRequest` ([#1247](https://github.com/juspay/hyperswitch/pull/1247)) ([`253eead`](https://github.com/juspay/hyperswitch/commit/253eead301bc919ff18af2ebe0064ca004d9852d)) +- **metrics:** + - Add flow-specific metrics ([#1259](https://github.com/juspay/hyperswitch/pull/1259)) ([`5e90a36`](https://github.com/juspay/hyperswitch/commit/5e90a369db32b125414c3674404dc34d134bf1da)) + - Add response metrics ([#1263](https://github.com/juspay/hyperswitch/pull/1263)) ([`4ebd26f`](https://github.com/juspay/hyperswitch/commit/4ebd26f27e43dddeae7498d81ed43516f3eb0e61)) +- **order_details:** Adding order_details both inside and outside of metadata, in payments request, for backward compatibility ([#1344](https://github.com/juspay/hyperswitch/pull/1344)) ([`913b833`](https://github.com/juspay/hyperswitch/commit/913b833117e1adb02324d32857dedf050791ec3a)) +- **payment:** Customer ip field inclusion ([#1370](https://github.com/juspay/hyperswitch/pull/1370)) ([`11a827a`](https://github.com/juspay/hyperswitch/commit/11a827a76d9efb81b70b4439a681eb17de73b94f)) +- **response-log:** + - Add logging to the response ([#1433](https://github.com/juspay/hyperswitch/pull/1433)) ([`96c5efe`](https://github.com/juspay/hyperswitch/commit/96c5efea2b0edc032d7199046650e7b00a276c5e)) + - Add logging to the response for stripe compatibility layer ([#1470](https://github.com/juspay/hyperswitch/pull/1470)) ([`96c71e1`](https://github.com/juspay/hyperswitch/commit/96c71e1b1bbf2b67a6e2c87478b98bcbb7cdb3ef)) +- **router:** + - Implement `CardsInfoInterface` for `MockDB` ([#1262](https://github.com/juspay/hyperswitch/pull/1262)) ([`cbff605`](https://github.com/juspay/hyperswitch/commit/cbff605f2af257f4f0ba45c1afe276ce902680ab)) + - Add mandate connector to payment data ([#1392](https://github.com/juspay/hyperswitch/pull/1392)) ([`7933e98`](https://github.com/juspay/hyperswitch/commit/7933e98c8cadfa27154b5a7ba5d7d12b33272ec6)) + - [Bluesnap] add kount frms session_id support for bluesnap connector ([#1403](https://github.com/juspay/hyperswitch/pull/1403)) ([`fbaecdc`](https://github.com/juspay/hyperswitch/commit/fbaecdc352e653f81bcc036ce0aabc222c91e92d)) + - Add caching for MerchantKeyStore ([#1409](https://github.com/juspay/hyperswitch/pull/1409)) ([`fda3fb4`](https://github.com/juspay/hyperswitch/commit/fda3fb4d2bc69297a8b8220e44798c4ca9dea9c2)) +- Use subscriber client for subscription in pubsub ([#1297](https://github.com/juspay/hyperswitch/pull/1297)) ([`864d855`](https://github.com/juspay/hyperswitch/commit/864d85534fbc174d8e989493c3231497f5c79fe5)) +- Encrypt PII fields before saving it in the database ([#1043](https://github.com/juspay/hyperswitch/pull/1043)) ([`fa392c4`](https://github.com/juspay/hyperswitch/commit/fa392c40a86b2589a55c3adf1de5b862a544dbe9)) +- Add error type for empty connector list ([#1363](https://github.com/juspay/hyperswitch/pull/1363)) ([`b2da920`](https://github.com/juspay/hyperswitch/commit/b2da9202809089e6725405351f51d81837b08667)) +- Add new error response for 403 ([#1330](https://github.com/juspay/hyperswitch/pull/1330)) ([`49d5ad7`](https://github.com/juspay/hyperswitch/commit/49d5ad7b3c24fc9c9847b473fda370398e3c7e38)) +- Applepay through trustpay ([#1422](https://github.com/juspay/hyperswitch/pull/1422)) ([`8032e02`](https://github.com/juspay/hyperswitch/commit/8032e0290b0a0ee33a640740b3bd4567a939712c)) + +### Bug Fixes + +- **api_models:** Fix bank namings ([#1315](https://github.com/juspay/hyperswitch/pull/1315)) ([`a8f2494`](https://github.com/juspay/hyperswitch/commit/a8f2494a87a7731deb104fe2eda548fbccdac895)) +- **config:** Fix docker compose local setup ([#1372](https://github.com/juspay/hyperswitch/pull/1372)) ([`d21fcc7`](https://github.com/juspay/hyperswitch/commit/d21fcc7bfc3bdf672b9cfbc5a234a3f3d03771c8)) +- **connector:** + - [Authorizedotnet] Fix webhooks ([#1261](https://github.com/juspay/hyperswitch/pull/1261)) ([`776c833`](https://github.com/juspay/hyperswitch/commit/776c833de706dcd8e93786d1fa294769669303cd)) + - [Checkout] Fix error message in error handling ([#1221](https://github.com/juspay/hyperswitch/pull/1221)) ([`22b2fa3`](https://github.com/juspay/hyperswitch/commit/22b2fa30610ad5ca97cd53df187ccd994411f4e2)) + - [coinbase] remove non-mandatory fields ([#1252](https://github.com/juspay/hyperswitch/pull/1252)) ([`bfd7dad`](https://github.com/juspay/hyperswitch/commit/bfd7dad2f1d694bbdc0a18782732ff95ee7730f6)) + - [Rapyd] Fix payment response structure ([#1258](https://github.com/juspay/hyperswitch/pull/1258)) ([`3af3a3c`](https://github.com/juspay/hyperswitch/commit/3af3a3cb39641633aecc2d4fc120ece13a6ee72a)) + - [Adyen] Address Internal Server Error when calling PSync without redirection ([#1311](https://github.com/juspay/hyperswitch/pull/1311)) ([`b966525`](https://github.com/juspay/hyperswitch/commit/b96652507a6ab37f3c75aeb0cf715fd6454b9f32)) + - [opennode] webhook url fix ([#1364](https://github.com/juspay/hyperswitch/pull/1364)) ([`e484193`](https://github.com/juspay/hyperswitch/commit/e484193101ffdc693044fd43c130b12821256111)) + - [Zen] fix additional base url required for Zen apple pay checkout integration ([#1394](https://github.com/juspay/hyperswitch/pull/1394)) ([`7955007`](https://github.com/juspay/hyperswitch/commit/795500797d1061630b5ca493187a4e19d98d26c0)) + - [Bluesnap] Throw proper error message for redirection scenario ([#1367](https://github.com/juspay/hyperswitch/pull/1367)) ([`4a8de77`](https://github.com/juspay/hyperswitch/commit/4a8de7741d43da07e655bc7382927c68e8ac1eb5)) + - [coinbase][opennode][bitpay] handle error response ([#1406](https://github.com/juspay/hyperswitch/pull/1406)) ([`301c3dc`](https://github.com/juspay/hyperswitch/commit/301c3dc44bb740709a0c5c54ee95fc811c2897ed)) + - [Zen][ACI] Error handling and Mapping ([#1436](https://github.com/juspay/hyperswitch/pull/1436)) ([`8a4f4a4`](https://github.com/juspay/hyperswitch/commit/8a4f4a4c307d75dee8a1fac8f029091a7d49d432)) + - [Bluesnap] fix expiry year ([#1426](https://github.com/juspay/hyperswitch/pull/1426)) ([`92c8222`](https://github.com/juspay/hyperswitch/commit/92c822257e3780fce11f7f0df9a0db48ae1b86e0)) + - [Shift4]Add Refund webhooks ([#1307](https://github.com/juspay/hyperswitch/pull/1307)) ([`1691bea`](https://github.com/juspay/hyperswitch/commit/1691beacc3a1c604ce6a1f4cf236f5f7932ed7ae)) + - [Shift4] validate pretask for threeds cards ([#1428](https://github.com/juspay/hyperswitch/pull/1428)) ([`2c1dcff`](https://github.com/juspay/hyperswitch/commit/2c1dcff046407aa9053b96c549ab578988b5c618)) + - Fix trustpay error response for transaction status api ([#1445](https://github.com/juspay/hyperswitch/pull/1445)) ([`7db94a6`](https://github.com/juspay/hyperswitch/commit/7db94a620882d7b4d14ac97f35f6ced06ae529d7)) + - Fix for sending refund_amount in connectors refund request ([#1278](https://github.com/juspay/hyperswitch/pull/1278)) ([`016857f`](https://github.com/juspay/hyperswitch/commit/016857fff0681058f3321a7952c7bd917442293a)) + - Use reference as payment_id in trustpay ([#1444](https://github.com/juspay/hyperswitch/pull/1444)) ([`3645c49`](https://github.com/juspay/hyperswitch/commit/3645c49b3830e6dc9e23d91b3ac66213727dca9f)) + - Implement ConnectorErrorExt for error_stack::Result<T, ConnectorError> ([#1382](https://github.com/juspay/hyperswitch/pull/1382)) ([`3ef1d29`](https://github.com/juspay/hyperswitch/commit/3ef1d2935e32a8b581e4d2d7f328d970ade4b7f9)) + - [Adyen] fix charged status for Auto capture payment ([#1462](https://github.com/juspay/hyperswitch/pull/1462)) ([`6c818ef`](https://github.com/juspay/hyperswitch/commit/6c818ef3366e9f094d39523334199a9a3abb78e9)) + - [Adyen] fix unit test ([#1469](https://github.com/juspay/hyperswitch/pull/1469)) ([`6e581c6`](https://github.com/juspay/hyperswitch/commit/6e581c6060423af9984375ad4169a1fec94d4585)) + - [Airwallex] Fix refunds ([#1468](https://github.com/juspay/hyperswitch/pull/1468)) ([`1b2841b`](https://github.com/juspay/hyperswitch/commit/1b2841be5997083cd2e414fc698d3d39f9c24c04)) + - [Zen] Convert the amount to base denomination in order_details ([#1477](https://github.com/juspay/hyperswitch/pull/1477)) ([`7ca62d3`](https://github.com/juspay/hyperswitch/commit/7ca62d3c7c04997c7eed6e82ec02dc39ea046b2f)) + - [Shift4] Fix incorrect deserialization of webhook event type ([#1463](https://github.com/juspay/hyperswitch/pull/1463)) ([`b44f35d`](https://github.com/juspay/hyperswitch/commit/b44f35d4d9ddf4fcd725f0e0a5d51fa9eb7f7e3f)) + - [Trustpay] add missing failure status ([#1485](https://github.com/juspay/hyperswitch/pull/1485)) ([`ecf16b0`](https://github.com/juspay/hyperswitch/commit/ecf16b0c7437fefa3550db7275ca2f73d1499b72)) + - [Trustpay] add reason to all the error responses ([#1482](https://github.com/juspay/hyperswitch/pull/1482)) ([`1d216db`](https://github.com/juspay/hyperswitch/commit/1d216db5ceeac3dc61d672de89a921501dcaee45)) +- **core:** + - Remove `missing_required_field_error` being thrown in `should_add_task_to_process_tracker` function ([#1239](https://github.com/juspay/hyperswitch/pull/1239)) ([`3857d06`](https://github.com/juspay/hyperswitch/commit/3857d06627d4c1b85b2e5b9687d80298acf82c14)) + - Return an empty array when the customer does not have any payment methods ([#1431](https://github.com/juspay/hyperswitch/pull/1431)) ([`6563587`](https://github.com/juspay/hyperswitch/commit/6563587564a6de579888a751b8c21e832060d728)) + - Fix amount capturable in payments response ([#1437](https://github.com/juspay/hyperswitch/pull/1437)) ([`5bc1aab`](https://github.com/juspay/hyperswitch/commit/5bc1aaba5945bd829bc2dffcef59db074fa523a7)) + - Save payment_method_type when creating a record in the payment_method table ([#1378](https://github.com/juspay/hyperswitch/pull/1378)) ([`76cb15e`](https://github.com/juspay/hyperswitch/commit/76cb15e01de748f9328d57968d6ddee9831720aa)) + - Add validation for card expiry month, expiry year and card cvc ([#1416](https://github.com/juspay/hyperswitch/pull/1416)) ([`c40617a`](https://github.com/juspay/hyperswitch/commit/c40617aea66eb3c14ad47efbce28374cd28626e0)) +- **currency:** Add RON and TRY currencies ([#1455](https://github.com/juspay/hyperswitch/pull/1455)) ([`495a98f`](https://github.com/juspay/hyperswitch/commit/495a98f0454787ae322f63f2adc3e3a6b6e0b515)) +- **error:** Propagate MissingRequiredFields api_error ([#1244](https://github.com/juspay/hyperswitch/pull/1244)) ([`798881a`](https://github.com/juspay/hyperswitch/commit/798881ab5b0e7a095daad9e920a29c36961ec13d)) +- **kms:** Add metrics to external_services kms ([#1237](https://github.com/juspay/hyperswitch/pull/1237)) ([`28f0d1f`](https://github.com/juspay/hyperswitch/commit/28f0d1f5351f0d3f6abd982ebe99bc15a74797c2)) +- **list:** Add mandate type in payment_method_list ([#1238](https://github.com/juspay/hyperswitch/pull/1238)) ([`9341191`](https://github.com/juspay/hyperswitch/commit/9341191e39627b661b9d105d65a869e8348c81ed)) +- **locker:** Remove unnecessary assertions for locker_id on BasiliskLocker when saving cards ([#1337](https://github.com/juspay/hyperswitch/pull/1337)) ([`23458bc`](https://github.com/juspay/hyperswitch/commit/23458bc42776e6440e76d324d37f36b65c393451)) +- **logging:** Fix traces export through opentelemetry ([#1355](https://github.com/juspay/hyperswitch/pull/1355)) ([`b2b9dc0`](https://github.com/juspay/hyperswitch/commit/b2b9dc0b58d737ea114d078fe02271a10accaefa)) +- **payments:** Do not delete client secret on payment failure ([#1226](https://github.com/juspay/hyperswitch/pull/1226)) ([`c1b631b`](https://github.com/juspay/hyperswitch/commit/c1b631bd1e0025452f2cf37345996ea789810839)) +- **refund:** Change amount to refund_amount ([#1268](https://github.com/juspay/hyperswitch/pull/1268)) ([`24c3a42`](https://github.com/juspay/hyperswitch/commit/24c3a42898a37dccf3f99a9fcc259127606598dd)) +- **router:** + - Subscriber return type ([#1292](https://github.com/juspay/hyperswitch/pull/1292)) ([`55bb117`](https://github.com/juspay/hyperswitch/commit/55bb117e1ddc147d7309823dc593bd1a05fe69a9)) + - Hotfixes for stripe webhook event mapping and reference id retrieval ([#1368](https://github.com/juspay/hyperswitch/pull/1368)) ([`5c2232b`](https://github.com/juspay/hyperswitch/commit/5c2232b737f5430a68fdf6cba9aa5f4c1d6cf3e2)) + - [Trustpay] fix email & user-agent information as mandatory fields in trustpay card payment request ([#1414](https://github.com/juspay/hyperswitch/pull/1414)) ([`7ef011a`](https://github.com/juspay/hyperswitch/commit/7ef011ad737257fc83f7a43d16f1bf4ac54336ae)) + - [Trustpay] fix email & user-agent information as mandatory fields in trustpay card payment request ([#1418](https://github.com/juspay/hyperswitch/pull/1418)) ([`c596d12`](https://github.com/juspay/hyperswitch/commit/c596d121a846e6c0fa399b8f28ffe4ab6124651a)) + - Fix payment status updation for 2xx error responses ([#1457](https://github.com/juspay/hyperswitch/pull/1457)) ([`a7ac4af`](https://github.com/juspay/hyperswitch/commit/a7ac4af5d916ff1e7965be35f347ce0e13407747)) +- **router/webhooks:** + - Use api error response for returning errors from webhooks core ([#1305](https://github.com/juspay/hyperswitch/pull/1305)) ([`cd0cf40`](https://github.com/juspay/hyperswitch/commit/cd0cf40fe29358700f92c1520475934752bb4b30)) + - Correct webhook error mapping and make source verification optional for all connectors ([#1333](https://github.com/juspay/hyperswitch/pull/1333)) ([`7131509`](https://github.com/juspay/hyperswitch/commit/71315097dd01ee675b0e4df3087b930637de416c)) + - Map webhook event type not found errors to 422 ([#1340](https://github.com/juspay/hyperswitch/pull/1340)) ([`61bacd8`](https://github.com/juspay/hyperswitch/commit/61bacd8c9590a78a6d5067e378bfed6301d64d07)) +- **session_token:** Log error only when it occurs ([#1136](https://github.com/juspay/hyperswitch/pull/1136)) ([`ebf3de4`](https://github.com/juspay/hyperswitch/commit/ebf3de41018f131f7501b17936e58c05276ead77)) +- **stripe:** Fix logs on stripe connector integration ([#1448](https://github.com/juspay/hyperswitch/pull/1448)) ([`c42b436`](https://github.com/juspay/hyperswitch/commit/c42b436abe1ed980d9b861dd4ba56324c8361a5a)) +- Remove multiple call to locker ([#1230](https://github.com/juspay/hyperswitch/pull/1230)) ([`b3c6b1f`](https://github.com/juspay/hyperswitch/commit/b3c6b1f0aacb9950d225779aa7de1ac49fe148d2)) +- Populate meta_data in payment_intent ([#1240](https://github.com/juspay/hyperswitch/pull/1240)) ([`1ac3eb0`](https://github.com/juspay/hyperswitch/commit/1ac3eb0a36030412ef51ec2664e8af43c9c2fc54)) +- Merchant webhook config should be looked up in config table instead of redis ([#1241](https://github.com/juspay/hyperswitch/pull/1241)) ([`48e5375`](https://github.com/juspay/hyperswitch/commit/48e537568debccdcd01c78eabce0b480a96beda2)) +- Invalidation of in-memory cache ([#1270](https://github.com/juspay/hyperswitch/pull/1270)) ([`e78b3a6`](https://github.com/juspay/hyperswitch/commit/e78b3a65d45429357adf3534b6028798d1f68620)) +- Customer id is not mandatory during confirm ([#1317](https://github.com/juspay/hyperswitch/pull/1317)) ([`1261791`](https://github.com/juspay/hyperswitch/commit/1261791d9f70794b3d6426ff35f4eb0fc1076be0)) +- Certificate decode failed when creating the session token for applepay ([#1385](https://github.com/juspay/hyperswitch/pull/1385)) ([`8497c55`](https://github.com/juspay/hyperswitch/commit/8497c55283d548c04b3a01560b06d9594e7d634c)) +- Update customer data if passed in payments ([#1402](https://github.com/juspay/hyperswitch/pull/1402)) ([`86f679a`](https://github.com/juspay/hyperswitch/commit/86f679abc1549b59239ece4a1123b60e40c26b96)) +- Fix some fields not being updated during payments create, update and confirm ([#1451](https://github.com/juspay/hyperswitch/pull/1451)) ([`1764085`](https://github.com/juspay/hyperswitch/commit/17640858eabb5d5a56a17c9e0a52e5773a0c592f)) + +### Refactors + +- **api_models:** Follow naming convention for wallets & paylater payment method data enums ([#1338](https://github.com/juspay/hyperswitch/pull/1338)) ([`6c0d136`](https://github.com/juspay/hyperswitch/commit/6c0d136cee106fc25fbcf63e4bbc01b28baa1519)) +- **auth_type:** Updated auth type in `update tracker` and also changed the default flow to `non-3ds` from `3ds` ([#1424](https://github.com/juspay/hyperswitch/pull/1424)) ([`1616051`](https://github.com/juspay/hyperswitch/commit/1616051145c1e276fdd7d0f85cda76baaeaa0023)) +- **compatibility:** Map connector to routing in payments request for backward compatibility ([#1339](https://github.com/juspay/hyperswitch/pull/1339)) ([`166688a`](https://github.com/juspay/hyperswitch/commit/166688a5906a2fcbb034c40a113452f6dc2e7160)) +- **compatibility, connector:** Add holder name and change trust pay merchant_ref id to payment_id ([`d091549`](https://github.com/juspay/hyperswitch/commit/d091549576676c87f855e06678544704339d82e4)) +- **configs:** Make kms module and KmsDecrypt pub ([#1274](https://github.com/juspay/hyperswitch/pull/1274)) ([`f0db993`](https://github.com/juspay/hyperswitch/commit/f0db9937c7b33858a1ff3e17eaecba094ca4c18c)) +- **connector:** + - Update error handling for Nexinets, Cybersource ([#1151](https://github.com/juspay/hyperswitch/pull/1151)) ([`2ede8ad`](https://github.com/juspay/hyperswitch/commit/2ede8ade8cff56443d8712518c64de7d952f4a0c)) + - [Zen] refactor connector_meta_data for zen connector applepay session data ([#1390](https://github.com/juspay/hyperswitch/pull/1390)) ([`0575b26`](https://github.com/juspay/hyperswitch/commit/0575b26b4fc229e92aef179146dfd561a9ee7f27)) +- **connector_customer:** Incorrect mapping of connector customer ([#1275](https://github.com/juspay/hyperswitch/pull/1275)) ([`ebdfde7`](https://github.com/juspay/hyperswitch/commit/ebdfde75ecc1c39720396ad7c18062f5c108b8d3)) +- **core:** + - Generate response hash key if not specified in create merchant account request ([#1232](https://github.com/juspay/hyperswitch/pull/1232)) ([`7b74cab`](https://github.com/juspay/hyperswitch/commit/7b74cab385db68e510d2d513083a725a4f945ae3)) + - Add 'redirect_response' field to CompleteAuthorizeData ([#1222](https://github.com/juspay/hyperswitch/pull/1222)) ([`77e60c8`](https://github.com/juspay/hyperswitch/commit/77e60c82fa123ef780485a8507ce779f2f41e166)) + - Use HMAC-SHA512 to calculate payments response hash ([#1302](https://github.com/juspay/hyperswitch/pull/1302)) ([`7032ea8`](https://github.com/juspay/hyperswitch/commit/7032ea849416cb740c892360d21e436d2675fbe4)) + - Accept customer data in customer object ([#1447](https://github.com/juspay/hyperswitch/pull/1447)) ([`cff1ce6`](https://github.com/juspay/hyperswitch/commit/cff1ce61f0347665d18040486cfbbcd93139950b)) + - Move update trackers after build request ([#1472](https://github.com/juspay/hyperswitch/pull/1472)) ([`6114fb6`](https://github.com/juspay/hyperswitch/commit/6114fb634063a9a6d732af38e2a9e343d940a15e)) + - Update trackers for preprocessing steps ([#1481](https://github.com/juspay/hyperswitch/pull/1481)) ([`8fffc16`](https://github.com/juspay/hyperswitch/commit/8fffc161ea909fb29a81090f97ee9f811431d539)) +- **disputes:** Resolve incorrect 5xx error mappings for disputes ([#1360](https://github.com/juspay/hyperswitch/pull/1360)) ([`c9b400e`](https://github.com/juspay/hyperswitch/commit/c9b400e186731b7de6073fece662fd0fcbbfc953)) +- **errors:** + - Remove RedisErrorExt ([#1389](https://github.com/juspay/hyperswitch/pull/1389)) ([`5d51505`](https://github.com/juspay/hyperswitch/commit/5d515050cf77705e3bf8c4b83f81ee51a8bff052)) + - Refactor `actix_web::ResponseError` for `ApiErrorResponse` ([#1362](https://github.com/juspay/hyperswitch/pull/1362)) ([`02a3ce7`](https://github.com/juspay/hyperswitch/commit/02a3ce74b84e86b0e17f8809c9b7651998a1c864)) +- **fix:** + - [Stripe] Fix bug in Stripe ([#1412](https://github.com/juspay/hyperswitch/pull/1412)) ([`e48202e`](https://github.com/juspay/hyperswitch/commit/e48202e0a06fa4d61a2637f57830ffa4aae1335d)) + - [Adyen] Fix bug in Adyen ([#1375](https://github.com/juspay/hyperswitch/pull/1375)) ([`d3a6906`](https://github.com/juspay/hyperswitch/commit/d3a69060b4db24fbbfc5c03934684dd8bfd45711)) +- **mca:** Use separate struct for connector metadata ([#1465](https://github.com/juspay/hyperswitch/pull/1465)) ([`8d20578`](https://github.com/juspay/hyperswitch/commit/8d2057844ef4a29474d266d814c8ee01cc557961)) +- **payments:** + - Attempt to address unintended 5xx and 4xx in payments ([#1376](https://github.com/juspay/hyperswitch/pull/1376)) ([`cf64862`](https://github.com/juspay/hyperswitch/commit/cf64862daca0ad05b7af27646430d12bac71a5ee)) + - Add udf field and remove refactor metadata ([#1466](https://github.com/juspay/hyperswitch/pull/1466)) ([`6419953`](https://github.com/juspay/hyperswitch/commit/641995371db4deba13dc246179d726ed390b6b3e)) +- **process_tracker:** Attempt to identify unintended 5xx in process_tracker ([#1359](https://github.com/juspay/hyperswitch/pull/1359)) ([`d8adf4c`](https://github.com/juspay/hyperswitch/commit/d8adf4c2b542a5cdd7888b956b085a69bd900920)) +- **router:** + - Router_parameters field inclusion ([#1251](https://github.com/juspay/hyperswitch/pull/1251)) ([`16cd325`](https://github.com/juspay/hyperswitch/commit/16cd32513bc6528e064058907a8c3c848fdba132)) + - Remove `pii-encryption-script` feature and use of timestamps for decryption ([#1350](https://github.com/juspay/hyperswitch/pull/1350)) ([`9f2832f`](https://github.com/juspay/hyperswitch/commit/9f2832f60078b98e6faae34b05b63d2dab6b7969)) + - Infer ip address for online mandates from request headers if absent ([#1419](https://github.com/juspay/hyperswitch/pull/1419)) ([`a1a009d`](https://github.com/juspay/hyperswitch/commit/a1a009d7966d2354d12bba86fbc59c1b853e14a1)) + - Send 200 response for 5xx status codes received from connector ([#1440](https://github.com/juspay/hyperswitch/pull/1440)) ([`1e5d2a2`](https://github.com/juspay/hyperswitch/commit/1e5d2a28f6592106a5924044fc8d6fc49ab20acf)) +- **webhook:** Added the unknown field to the webhook_event_status of every connector ([#1343](https://github.com/juspay/hyperswitch/pull/1343)) ([`65d4a95`](https://github.com/juspay/hyperswitch/commit/65d4a95b59ee950ba67ce5b38688a650c5131149)) +- Make NextAction as enum ([#1234](https://github.com/juspay/hyperswitch/pull/1234)) ([`a359b76`](https://github.com/juspay/hyperswitch/commit/a359b76d09ffc581d5808e3750dac7326c389876)) +- Make bank names optional in payment method data ([#1483](https://github.com/juspay/hyperswitch/pull/1483)) ([`8198559`](https://github.com/juspay/hyperswitch/commit/8198559966313ab147161eb72c07a230ecebb70c)) + +### Testing + +- **connector:** + - [Stripe] Fix redirection UI tests ([#1215](https://github.com/juspay/hyperswitch/pull/1215)) ([`ea6bce6`](https://github.com/juspay/hyperswitch/commit/ea6bce663dcb084b5990834cb922eec5c626e897)) + - [Globalpay] Fix unit tests ([#1217](https://github.com/juspay/hyperswitch/pull/1217)) ([`71c0d4c`](https://github.com/juspay/hyperswitch/commit/71c0d4c500f7daca7b00f737d714f2d98cc91513)) +- **postman-collection:** Add Github action to run postman collection ([#1272](https://github.com/juspay/hyperswitch/pull/1272)) ([`92c7767`](https://github.com/juspay/hyperswitch/commit/92c776714f63d02055fc46b5b750cee71328f5eb)) +- **selenium:** Read config from `CONNECTOR_AUTH_FILE_PATH` environment variable and fix bugs in UI tests ([#1225](https://github.com/juspay/hyperswitch/pull/1225)) ([`d9a16ed`](https://github.com/juspay/hyperswitch/commit/d9a16ed5abdafa6d48bf30a6ba8c3783bed3dff5)) + +### Documentation + +- **CONTRIBUTING:** Update commit guidelines ([#1351](https://github.com/juspay/hyperswitch/pull/1351)) ([`5d8895c`](https://github.com/juspay/hyperswitch/commit/5d8895c06412ff05d5abbfefaaa4933db853eb13)) +- Add changelog to 0.5.15 ([#1216](https://github.com/juspay/hyperswitch/pull/1216)) ([`0be900d`](https://github.com/juspay/hyperswitch/commit/0be900d2388ad732a40b788223bd48aee9b3aa95)) +- Add `ApplePayRedirectionData` to OpenAPI schema ([#1386](https://github.com/juspay/hyperswitch/pull/1386)) ([`d0d3254`](https://github.com/juspay/hyperswitch/commit/d0d32544c23481a1acd91182055a7a0afb78d723)) + +### Miscellaneous Tasks + +- **common_utils:** Apply the new type pattern for phone numbers ([#1286](https://github.com/juspay/hyperswitch/pull/1286)) ([`98e73e2`](https://github.com/juspay/hyperswitch/commit/98e73e2e90b4c79d0cc6cf8682693c1e5aad50a3)) +- **config:** + - Add bank config for online_banking_poland, online_banking_slovakia ([#1220](https://github.com/juspay/hyperswitch/pull/1220)) ([`ee5466a`](https://github.com/juspay/hyperswitch/commit/ee5466a3b04f69c92dc5d04faca80d1f04275a9c)) + - Add bank config for przelewy24 ([#1460](https://github.com/juspay/hyperswitch/pull/1460)) ([`3ee97cd`](https://github.com/juspay/hyperswitch/commit/3ee97cda552e0745b8d75daad2e300288673a4d7)) +- **migrations:** Shrink `merchant_id` column of `merchant_key_store` to 64 characters ([#1476](https://github.com/juspay/hyperswitch/pull/1476)) ([`0fdd6ec`](https://github.com/juspay/hyperswitch/commit/0fdd6ecd4ac4bc5e1fc11e5cf79292c99eae71c1)) +- Address Rust 1.70 clippy lints ([#1334](https://github.com/juspay/hyperswitch/pull/1334)) ([`b681f78`](https://github.com/juspay/hyperswitch/commit/b681f78d964d02f80249751cc6fd12e3c85bc4d7)) + +### Build System / Dependencies + +- **deps:** + - Bump `diesel` from `2.0.3` to `2.1.0` ([#1287](https://github.com/juspay/hyperswitch/pull/1287)) ([`b9ec38a`](https://github.com/juspay/hyperswitch/commit/b9ec38a1b54abbaa90bbc967aa8cdd450f149947)) + - Update dependencies ([#1342](https://github.com/juspay/hyperswitch/pull/1342)) ([`bce01ce`](https://github.com/juspay/hyperswitch/commit/bce01ced11e3869699d454827dc659fc82941951)) +- **docker:** Use `debian:bookworm-slim` as base image for builder and runner stages ([#1473](https://github.com/juspay/hyperswitch/pull/1473)) ([`5eb0333`](https://github.com/juspay/hyperswitch/commit/5eb033336321b5deb197f4416c8409abf99a8421)) +- Unify `sandbox` and `production` cargo features as `release` ([#1356](https://github.com/juspay/hyperswitch/pull/1356)) ([`695d3cd`](https://github.com/juspay/hyperswitch/commit/695d3cdac27448806fcde8cbb9cdc6ba4e7cbe7e)) + +**Full Changelog:** [`v0.5.15...v0.6.0`](https://github.com/juspay/hyperswitch/compare/v0.5.15...v0.6.0) + +- - - + ## 0.5.15 (2023-05-19) ### Features @@ -57,6 +449,8 @@ All notable changes to HyperSwitch will be documented here. - **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 @@ -82,6 +476,8 @@ All notable changes to HyperSwitch will be documented here. - **CHANGELOG:** Add changelog for 0.5.13 ([#1166](https://github.com/juspay/hyperswitch/pull/1166)) ([`94fe1af`](https://github.com/juspay/hyperswitch/commit/94fe1af1b0bce3b4ecaef8665909fc8f5cd4bbbb)) +- - - + ## 0.5.13 (2023-05-15) ### Features @@ -108,6 +504,8 @@ All notable changes to HyperSwitch will be documented here. - Fix Stripe status to attempt status map ([#1132](https://github.com/juspay/hyperswitch/pull/1132)) ([`8b85647`](https://github.com/juspay/hyperswitch/commit/8b85647a169d1d3ea59d2b472eabb99482f71eda)) - **mandate:** Allow card details to be provided in case of network transaction id ([#1138](https://github.com/juspay/hyperswitch/pull/1138)) ([`cc121d0`](https://github.com/juspay/hyperswitch/commit/cc121d0febcb397a989e512928d33a8cff2fbdee)) +- - - + ## 0.5.12 (2023-05-11) ### Features @@ -140,6 +538,8 @@ All notable changes to HyperSwitch will be documented here. - Refactor(merchant_account): add back `api_key` field for backward compatibility ([#761](https://github.com/juspay/hyperswitch/pull/761)) ([#1062](https://github.com/juspay/hyperswitch/pull/1062)) ([`f481abb`](https://github.com/juspay/hyperswitch/commit/f481abb8551f3ec5e495cf9916d9d8a5cecd62da)) +- - - + ## 0.5.11 (2023-05-10) ### Features @@ -180,6 +580,8 @@ All notable changes to HyperSwitch will be documented here. - **CODEOWNERS:** Update CODEOWNERS ([#1076](https://github.com/juspay/hyperswitch/pull/1076)) ([`1456580`](https://github.com/juspay/hyperswitch/commit/1456580366c618300db4e0746db08a7466e04ea8)) +- - - + ## 0.5.10 (2023-05-08) ### Features @@ -217,6 +619,7 @@ All notable changes to HyperSwitch will be documented here. - Include payment method type in connector choice for session flow ([#1036](https://github.com/juspay/hyperswitch/pull/1036)) ([`73b8988`](https://github.com/juspay/hyperswitch/commit/73b8988322e3d15f90b2c4ca776d135d23e97710)) - Use newtype pattern for email addresses ([#819](https://github.com/juspay/hyperswitch/pull/819)) ([`b8e2b1c`](https://github.com/juspay/hyperswitch/commit/b8e2b1c5f42dcd41a3d02e0d2422e1407b6a41de)) +- - - ## 0.5.9 (2023-05-04) @@ -260,6 +663,8 @@ All notable changes to HyperSwitch will be documented here. - **deps:** Make AWS dependencies optional ([#1030](https://github.com/juspay/hyperswitch/pull/1030)) ([`a4f6f3f`](https://github.com/juspay/hyperswitch/commit/a4f6f3fdaa23f7bd849eb44971de8311f9363ac3)) +- - - + ## 0.5.8 (2023-04-25) ### Chores @@ -315,6 +720,7 @@ All notable changes to HyperSwitch will be documented here. * **db:** remove `connector_transaction_id` from PaymentAttemptNew ([#949](https://github.com/juspay/orca/pull/949)) ([57327b82](https://github.com/juspay/orca/commit/57327b829776c58fa6c3569c5546c4706d2c66af)) * **api_keys:** use `merchant_id` and `key_id` to query the table ([#939](https://github.com/juspay/orca/pull/939)) ([40898c0a](https://github.com/juspay/orca/commit/40898c0ac9199258fbc6e8e12950d4fa54ec3339)) +- - - ## 0.5.7 (2023-04-18) @@ -348,6 +754,8 @@ All notable changes to HyperSwitch will be documented here. * **storage_models, errors:** impl StorageErrorExt for error_stack::Result<T, errors::StorageError> (#886) (b4020294) * **router:** KMS decrypt secrets when kms feature is enabled (#868) (8905e663) +- - - + ## 0.5.6 2023-04-14 ### Build System / Dependencies @@ -384,6 +792,7 @@ All notable changes to HyperSwitch will be documented here. * **router_env:** improve logging setup (#847) (1b94d25f) * **refund_type:** Feat/add copy derive (#849) (ccf03273) +- - - ## 0.5.5 (2023-04-10) @@ -407,6 +816,8 @@ All notable changes to HyperSwitch will be documented here. * **scheduler:** remove scheduler options & adding graceful shutdown to producer (#840) (11df8436) * **router:** refactor amount in PaymentsCaptureData from Option<i64> to i64 (#821) (b8bcba4e) +- - - + ## 0.5.4 (2023-04-04) ### New Features @@ -431,6 +842,8 @@ All notable changes to HyperSwitch will be documented here. * **drainer, router:** KMS decrypt database password when `kms` feature is enabled (#733) (9d6e4ee3) +- - - + ## 0.5.3 (2023-03-29) ### Documentation Changes @@ -451,6 +864,8 @@ All notable changes to HyperSwitch will be documented here. * **api_models:** enhance accepted countries/currencies types (#807) (f9ef3135) * **services:** make AppState impl generic using AppStateInfo (#805) (642c3f3a) +- - - + ## 0.5.2 (2023-03-24) ### Chores @@ -469,6 +884,8 @@ All notable changes to HyperSwitch will be documented here. * extract kms module to `external_services` crate (#793) (029e3894) +- - - + ## 0.5.1 (2023-03-21) ### Documentation Changes @@ -501,6 +918,8 @@ All notable changes to HyperSwitch will be documented here. * get connection pool based on olap/oltp features (#743) (a392fb16) +- - - + ## 0.5.0 (2023-03-21) ### Build System / Dependencies @@ -569,6 +988,9 @@ All notable changes to HyperSwitch will be documented here. ### Tests * **masking:** add suitable feature gates for basic tests (#745) (4859b6e4) + +- - - + ## 0.3.0 (2023-03-05) ### Chores @@ -655,6 +1077,8 @@ All notable changes to HyperSwitch will be documented here. * **connector-template:** raise errors instead of using `todo!()` (#620) (b1a6be5a) * **redirection:** `From` impl for redirection data for ease of use (#613) (e8255b4a) +- - - + ## 0.3.0 (2023-02-25) ### Build System / Dependencies @@ -716,6 +1140,8 @@ All notable changes to HyperSwitch will be documented here. * send full payment object for payment sync (#526) (6c2a1fea) * **middleware:** change visibility to `pub` (#587) (4884a24d) +- - - + ## 0.2.1 (2023-02-17) ### Fixes @@ -723,6 +1149,7 @@ All notable changes to HyperSwitch will be documented here. - Decide connector only when the payment method is confirm ([10ea4919ba07d3198a6bbe3f3d4d817a23605924](https://github.com/juspay/hyperswitch/commit/10ea4919ba07d3198a6bbe3f3d4d817a23605924)) - Fix panics caused with empty diesel updates ([448595498114cd15158b4a78fc32d8e6dc1b67ee](https://github.com/juspay/hyperswitch/commit/448595498114cd15158b4a78fc32d8e6dc1b67ee)) +- - - ## 0.2.0 (2023-01-23) - Initial Release diff --git a/cog.toml b/cog.toml new file mode 100644 index 00000000000..b42ec04664a --- /dev/null +++ b/cog.toml @@ -0,0 +1,22 @@ +tag_prefix = "v" +branch_whitelist = ["main"] +ignore_merge_commits = true + +# the HTML comments (`<!-- N -->`) are a workaround to have sections in custom order, since they are alphabetically sorted +[commit_types] +feat = { changelog_title = "<!-- 0 -->Features" } +fix = { changelog_title = "<!-- 1 -->Bug Fixes" } +perf = { changelog_title = "<!-- 2 -->Performance" } +refactor = { changelog_title = "<!-- 3 -->Refactors" } +test = { changelog_title = "<!-- 4 -->Testing" } +docs = { changelog_title = "<!-- 5 -->Documentation" } +chore = { changelog_title = "<!-- 6 -->Miscellaneous Tasks" } +build = { changelog_title = "<!-- 7 -->Build System / Dependencies" } +ci = { changelog_title = "Continuous Integration", omit_from_changelog = true } + +[changelog] +path = "CHANGELOG.md" +template = ".github/cocogitto-changelog-template" +remote = "github.com" +owner = "juspay" +repository = "hyperswitch"
ci
add workflow to create tags on schedule (#1642)
84d91a7b344df47899ff31a87b86b8410c204f95
2024-02-26 19:31:36
Narayan Bhat
fix(core): do not construct request if it is already available (#3826)
false
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 738f57e9d70..bfba31c3446 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -338,30 +338,31 @@ where ], ); - let connector_request = connector_request.or(connector_integration - .build_request(req, &state.conf.connectors) - .map_err(|error| { - if matches!( - error.current_context(), - &errors::ConnectorError::RequestEncodingFailed - | &errors::ConnectorError::RequestEncodingFailedWithReason(_) - ) { - metrics::REQUEST_BUILD_FAILURE.add( - &metrics::CONTEXT, - 1, - &[metrics::request::add_attributes( - "connector", - req.connector.to_string(), - )], - ) - } - error - })?); + let connector_request = match connector_request { + Some(connector_request) => Some(connector_request), + None => connector_integration + .build_request(req, &state.conf.connectors) + .map_err(|error| { + if matches!( + error.current_context(), + &errors::ConnectorError::RequestEncodingFailed + | &errors::ConnectorError::RequestEncodingFailedWithReason(_) + ) { + metrics::REQUEST_BUILD_FAILURE.add( + &metrics::CONTEXT, + 1, + &[metrics::request::add_attributes( + "connector", + req.connector.to_string(), + )], + ) + } + error + })?, + }; match connector_request { Some(request) => { - logger::debug!(connector_request=?request); - let masked_request_body = match &request.body { Some(request) => match request { RequestContent::Json(i) @@ -1828,7 +1829,7 @@ pub fn build_redirection_form( threeDSsecureInterface.on('challenge', function(e) {{ console.log('Challenged'); - document.getElementById('loader-wrapper').style.display = 'none'; + document.getElementById('loader-wrapper').style.display = 'none'; }}); threeDSsecureInterface.on('complete', function(e) {{
fix
do not construct request if it is already available (#3826)
be22d60ddac18d9fb3032f72247634799e8f4ceb
2024-02-05 15:37:07
Sai Harsha Vardhan
fix(router): handle empty body parse failures in bad request logger middleware (#3541)
false
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 1c80aff4397..ed443c9e418 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -258,8 +258,8 @@ pub fn get_application_builder( .wrap(middleware::default_response_headers()) .wrap(middleware::RequestId) .wrap(cors::cors()) - .wrap(middleware::LogSpanInitializer) // this middleware works only for Http1.1 requests .wrap(middleware::Http400RequestDetailsLogger) + .wrap(middleware::LogSpanInitializer) .wrap(router_env::tracing_actix_web::TracingLogger::default()) } diff --git a/crates/router/src/middleware.rs b/crates/router/src/middleware.rs index 9205f53a04b..6f3427bf7a4 100644 --- a/crates/router/src/middleware.rs +++ b/crates/router/src/middleware.rs @@ -258,13 +258,24 @@ where let response = response_fut.await?; // Log the request_details when we receive 400 status from the application if response.status() == 400 { - let value: serde_json::Value = serde_json::from_slice(&bytes)?; let request_id = request_id_fut.await?.as_hyphenated().to_string(); - logger::info!( - "request_id: {}, request_details: {}", - request_id, - get_request_details_from_value(&value, "") - ); + if !bytes.is_empty() { + let value_result: Result<serde_json::Value, serde_json::Error> = + serde_json::from_slice(&bytes); + match value_result { + Ok(value) => { + logger::info!( + "request_id: {request_id}, request_details: {}", + get_request_details_from_value(&value, "") + ); + } + Err(err) => { + logger::warn!("error while parsing the request in json value: {err}"); + } + } + } else { + logger::info!("request_id: {request_id}, request_details: Empty Body"); + } } Ok(response) })
fix
handle empty body parse failures in bad request logger middleware (#3541)
bcda67935e440d50c66cd5a7ddb3cf1005d416d6
2023-08-17 08:16:47
github-actions
chore(version): v1.21.2
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 920188d42f8..9ef2bf5f43c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.21.2 (2023-08-17) + +### Bug Fixes + +- **connector:** [Braintree] fix status mapping for braintree ([#1941](https://github.com/juspay/hyperswitch/pull/1941)) ([`d30fefb`](https://github.com/juspay/hyperswitch/commit/d30fefb2c08d4a086f4d8c0519196d83fa228d45)) +- **frm:** Added fraud_check_last_step field in fraud_check table to support 3DS transaction in frm ([#1944](https://github.com/juspay/hyperswitch/pull/1944)) ([`9a39345`](https://github.com/juspay/hyperswitch/commit/9a393455dd6643caf61747633698191ba8c59d49)) + +### Refactors + +- **connector:** Remove payment experience from Not Supported Payment Methods error ([#1937](https://github.com/juspay/hyperswitch/pull/1937)) ([`c5cf029`](https://github.com/juspay/hyperswitch/commit/c5cf029d1f20dc27f6b246094d61a381669feb68)) + +**Full Changelog:** [`v1.21.1...v1.21.2`](https://github.com/juspay/hyperswitch/compare/v1.21.1...v1.21.2) + +- - - + + ## 1.21.1 (2023-08-15) ### Bug Fixes
chore
v1.21.2
73dfc31f9d16d2cf71de8433fb630bea941a7020
2023-10-09 14:32:46
Narayan Bhat
feat(process_tracker): make long standing payments failed (#2380)
false
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 228d02e1dda..02db8b1754e 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -13,6 +13,8 @@ pub(crate) const ALPHABETS: [char; 62] = [ pub const REQUEST_TIME_OUT: u64 = 30; pub const REQUEST_TIMEOUT_ERROR_CODE: &str = "TIMEOUT"; pub const REQUEST_TIMEOUT_ERROR_MESSAGE: &str = "Connector did not respond in specified time"; +pub const REQUEST_TIMEOUT_ERROR_MESSAGE_FROM_PSYNC: &str = + "This Payment has been moved to failed as there is no response from the connector"; ///Payment intent fulfillment default timeout (in seconds) pub const DEFAULT_FULFILLMENT_TIME: i64 = 15 * 60; diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index a8069b4d4a6..c5e28110a6d 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -2,12 +2,11 @@ use std::{fmt::Debug, marker::PhantomData, str::FromStr}; use api_models::payments::FrmMessage; use common_utils::fp_utils; -use data_models::mandates::MandateData; use diesel_models::ephemeral_key; use error_stack::{IntoReport, ResultExt}; use router_env::{instrument, tracing}; -use super::{flows::Feature, PaymentAddress, PaymentData}; +use super::{flows::Feature, PaymentData}; use crate::{ configs::settings::{ConnectorRequestReferenceIdConfig, Server}, connector::Nexinets, @@ -202,40 +201,32 @@ where connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, connector_http_status_code: Option<u16>, ) -> RouterResponse<Self> { - let captures = payment_data - .multiple_capture_data - .and_then(|multiple_capture_data| { - multiple_capture_data - .expand_captures - .and_then(|should_expand| { - should_expand.then_some( - multiple_capture_data - .get_all_captures() - .into_iter() - .cloned() - .collect(), - ) - }) - }); + let captures = + payment_data + .multiple_capture_data + .clone() + .and_then(|multiple_capture_data| { + multiple_capture_data + .expand_captures + .and_then(|should_expand| { + should_expand.then_some( + multiple_capture_data + .get_all_captures() + .into_iter() + .cloned() + .collect(), + ) + }) + }); + payments_to_payments_response( req, - payment_data.payment_attempt, - payment_data.payment_intent, - payment_data.refunds, - payment_data.disputes, - payment_data.attempts, + payment_data, captures, - payment_data.payment_method_data, customer, auth_flow, - payment_data.address, server, - payment_data.connector_response.authentication_data, &operation, - payment_data.ephemeral_key, - payment_data.sessions_token, - payment_data.frm_message, - payment_data.setup_mandate, connector_request_reference_id_config, connector_http_status_code, ) @@ -333,31 +324,23 @@ where // try to use router data here so that already validated things , we don't want to repeat the validations. // Add internal value not found and external value not found so that we can give 500 / Internal server error for internal value not found #[allow(clippy::too_many_arguments)] -pub fn payments_to_payments_response<R, Op>( +pub fn payments_to_payments_response<R, Op, F: Clone>( payment_request: Option<R>, - payment_attempt: storage::PaymentAttempt, - payment_intent: storage::PaymentIntent, - refunds: Vec<storage::Refund>, - disputes: Vec<storage::Dispute>, - option_attempts: Option<Vec<storage::PaymentAttempt>>, + payment_data: PaymentData<F>, captures: Option<Vec<storage::Capture>>, - payment_method_data: Option<api::PaymentMethodData>, customer: Option<domain::Customer>, auth_flow: services::AuthFlow, - address: PaymentAddress, server: &Server, - redirection_data: Option<serde_json::Value>, operation: &Op, - ephemeral_key_option: Option<ephemeral_key::EphemeralKey>, - session_tokens: Vec<api::SessionToken>, - fraud_check: Option<payments::FraudCheck>, - mandate_data: Option<MandateData>, connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, connector_http_status_code: Option<u16>, ) -> RouterResponse<api::PaymentsResponse> where Op: Debug, { + let payment_attempt = payment_data.payment_attempt; + let payment_intent = payment_data.payment_intent; + let currency = payment_attempt .currency .as_ref() @@ -369,22 +352,31 @@ where field_name: "amount", })?; let mandate_id = payment_attempt.mandate_id.clone(); - let refunds_response = if refunds.is_empty() { + let refunds_response = if payment_data.refunds.is_empty() { None } else { - Some(refunds.into_iter().map(ForeignInto::foreign_into).collect()) + Some( + payment_data + .refunds + .into_iter() + .map(ForeignInto::foreign_into) + .collect(), + ) }; - let disputes_response = if disputes.is_empty() { + + let disputes_response = if payment_data.disputes.is_empty() { None } else { Some( - disputes + payment_data + .disputes .into_iter() .map(ForeignInto::foreign_into) .collect(), ) }; - let attempts_response = option_attempts.map(|attempts| { + + let attempts_response = payment_data.attempts.map(|attempts| { attempts .into_iter() .map(ForeignInto::foreign_into) @@ -419,7 +411,7 @@ where field_name: "payment_method_data", })?; let merchant_decision = payment_intent.merchant_decision.to_owned(); - let frm_message = fraud_check.map(FrmMessage::foreign_from); + let frm_message = payment_data.frm_message.map(FrmMessage::foreign_from); let payment_method_data_response = additional_payment_method_data.map(api::PaymentMethodDataResponse::from); @@ -441,13 +433,23 @@ where let output = Ok(match payment_request { Some(_request) => { - if payments::is_start_pay(&operation) && redirection_data.is_some() { - let redirection_data = redirection_data.get_required_value("redirection_data")?; + if payments::is_start_pay(&operation) + && payment_data + .connector_response + .authentication_data + .is_some() + { + let redirection_data = payment_data + .connector_response + .authentication_data + .get_required_value("redirection_data")?; + let form: RedirectForm = serde_json::from_value(redirection_data) .map_err(|_| errors::ApiErrorResponse::InternalServerError)?; + services::ApplicationResponse::Form(Box::new(services::RedirectionFormData { redirect_form: form, - payment_method_data, + payment_method_data: payment_data.payment_method_data, amount, currency: currency.to_string(), })) @@ -494,22 +496,23 @@ where display_to_timestamp: wait_screen_data.display_to_timestamp, } })) - .or(redirection_data.map(|_| { - api_models::payments::NextActionData::RedirectToUrl { + .or(payment_data + .connector_response + .authentication_data + .map(|_| api_models::payments::NextActionData::RedirectToUrl { redirect_to_url: helpers::create_startpay_url( server, &payment_attempt, &payment_intent, ), - } - })); + })); }; // next action check for third party sdk session (for ex: Apple pay through trustpay has third party sdk session response) if third_party_sdk_session_next_action(&payment_attempt, operation) { next_action_response = Some( api_models::payments::NextActionData::ThirdPartySdkSessionToken { - session_token: session_tokens.get(0).cloned(), + session_token: payment_data.sessions_token.get(0).cloned(), }, ) } @@ -555,7 +558,7 @@ where ) .set_mandate_id(mandate_id) .set_mandate_data( - mandate_data.map(|d| api::MandateData { + payment_data.setup_mandate.map(|d| api::MandateData { customer_acceptance: d.customer_acceptance.map(|d| { api::CustomerAcceptance { acceptance_type: match d.acceptance_type { @@ -621,8 +624,8 @@ where .or(payment_attempt.error_message), ) .set_error_code(payment_attempt.error_code) - .set_shipping(address.shipping) - .set_billing(address.billing) + .set_shipping(payment_data.address.shipping) + .set_billing(payment_data.address.billing) .set_next_action(next_action_response) .set_return_url(payment_intent.return_url) .set_cancellation_reason(payment_attempt.cancellation_reason) @@ -642,7 +645,9 @@ where .set_allowed_payment_method_types( payment_intent.allowed_payment_method_types, ) - .set_ephemeral_key(ephemeral_key_option.map(ForeignFrom::foreign_from)) + .set_ephemeral_key( + payment_data.ephemeral_key.map(ForeignFrom::foreign_from), + ) .set_frm_message(frm_message) .set_merchant_decision(merchant_decision) .set_manual_retry_allowed(helpers::is_manual_retry_allowed( @@ -696,8 +701,8 @@ where .as_ref() .and_then(|cus| cus.phone.as_ref().map(|s| s.to_owned())), mandate_id, - shipping: address.shipping, - billing: address.billing, + shipping: payment_data.address.shipping, + billing: payment_data.address.billing, cancellation_reason: payment_attempt.cancellation_reason, payment_token: payment_attempt.payment_token, metadata: payment_intent.metadata, diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 4ad8344501c..4f1537d5f48 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -861,13 +861,13 @@ pub async fn sync_refund_with_gateway_workflow( .await? } _ => { - payment_sync::retry_sync_task( + _ = payment_sync::retry_sync_task( &*state.store, response.connector, response.merchant_id, refund_tracker.to_owned(), ) - .await? + .await?; } } diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index 530d445b50d..7540845c343 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -695,11 +695,6 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: types::OutgoingWebhook }?; if state.conf.webhooks.outgoing_enabled { - let arbiter = actix::Arbiter::try_current() - .ok_or(errors::ApiErrorResponse::WebhookProcessingFailure) - .into_report() - .attach_printable("arbiter retrieval failure")?; - let outgoing_webhook = api::OutgoingWebhook { merchant_id: merchant_account.merchant_id.clone(), event_id: event.event_id, @@ -708,7 +703,9 @@ pub async fn create_event_and_trigger_outgoing_webhook<W: types::OutgoingWebhook timestamp: event.created_at, }; - arbiter.spawn(async move { + // Using a tokio spawn here and not arbiter because not all caller of this function + // may have an actix arbiter + tokio::spawn(async move { let result = trigger_webhook_to_merchant::<W>(merchant_account, outgoing_webhook, &state).await; diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index e8a5597eb26..a0491c18a5f 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -5,6 +5,8 @@ pub mod ext_traits; #[cfg(feature = "kv_store")] pub mod storage_partitioning; +use std::fmt::Debug; + use api_models::{enums, payments, webhooks}; use base64::Engine; pub use common_utils::{ @@ -27,11 +29,12 @@ use crate::{ consts, core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, - utils, + utils, webhooks as webhooks_core, }, db::StorageInterface, logger, routes::metrics, + services, types::{ self, domain::{ @@ -39,6 +42,7 @@ use crate::{ types::{encrypt_optional, AsyncLift}, }, storage, + transformers::{ForeignTryFrom, ForeignTryInto}, }, }; @@ -669,3 +673,89 @@ pub fn add_apple_pay_payment_status_metrics( } } } + +impl ForeignTryFrom<enums::IntentStatus> for enums::EventType { + type Error = errors::ValidationError; + + fn foreign_try_from(value: enums::IntentStatus) -> Result<Self, Self::Error> { + match value { + enums::IntentStatus::Succeeded => Ok(Self::PaymentSucceeded), + enums::IntentStatus::Failed => Ok(Self::PaymentFailed), + enums::IntentStatus::Processing => Ok(Self::PaymentProcessing), + enums::IntentStatus::RequiresMerchantAction + | enums::IntentStatus::RequiresCustomerAction => Ok(Self::ActionRequired), + _ => Err(errors::ValidationError::IncorrectValueProvided { + field_name: "intent_status", + }), + } + } +} + +pub async fn trigger_payments_webhook<F, Req, Op>( + merchant_account: domain::MerchantAccount, + payment_data: crate::core::payments::PaymentData<F>, + req: Option<Req>, + customer: Option<domain::Customer>, + state: &crate::routes::AppState, + operation: Op, +) -> RouterResult<()> +where + F: Send + Clone + Sync, + Op: Debug, +{ + let status = payment_data.payment_intent.status; + let payment_id = payment_data.payment_intent.payment_id.clone(); + let captures = payment_data + .multiple_capture_data + .clone() + .map(|multiple_capture_data| { + multiple_capture_data + .get_all_captures() + .into_iter() + .cloned() + .collect() + }); + + if matches!( + status, + enums::IntentStatus::Succeeded | enums::IntentStatus::Failed + ) { + let payments_response = crate::core::payments::transformers::payments_to_payments_response( + req, + payment_data, + captures, + customer, + services::AuthFlow::Merchant, + &state.conf.server, + &operation, + &state.conf.connector_request_reference_id_config, + None, + )?; + + let event_type: enums::EventType = status + .foreign_try_into() + .into_report() + .change_context(errors::ApiErrorResponse::WebhookProcessingFailure) + .attach_printable("payment event type mapping failed")?; + + if let services::ApplicationResponse::JsonWithHeaders((payments_response_json, _)) = + payments_response + { + Box::pin( + webhooks_core::create_event_and_trigger_appropriate_outgoing_webhook( + state.clone(), + merchant_account, + event_type, + diesel_models::enums::EventClass::Payments, + None, + payment_id, + diesel_models::enums::EventObjectType::PaymentDetails, + webhooks::OutgoingWebhookContent::PaymentDetails(payments_response_json), + ), + ) + .await?; + } + } + + Ok(()) +} diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs index 4dbf97081a6..cbb13be2f9b 100644 --- a/crates/router/src/workflows/payment_sync.rs +++ b/crates/router/src/workflows/payment_sync.rs @@ -4,11 +4,13 @@ use router_env::logger; use scheduler::{ consumer::{self, types::process_data, workflows::ProcessTrackerWorkflow}, db::process_tracker::ProcessTrackerExt, - errors as sch_errors, utils, SchedulerAppState, + errors as sch_errors, utils as scheduler_utils, SchedulerAppState, }; use crate::{ + consts, core::{ + errors::StorageErrorExt, payment_methods::Oss, payments::{self as payment_flows, operations}, }, @@ -20,6 +22,7 @@ use crate::{ api, storage::{self, enums}, }, + utils, }; pub struct PaymentsSyncWorkflow; @@ -57,7 +60,7 @@ impl ProcessTrackerWorkflow<AppState> for PaymentsSyncWorkflow { ) .await?; - let (payment_data, _, _, _) = + let (mut payment_data, _, customer, _) = payment_flows::payments_operation_core::<api::PSync, _, _, _, Oss>( state, merchant_account.clone(), @@ -93,15 +96,72 @@ impl ProcessTrackerWorkflow<AppState> for PaymentsSyncWorkflow { let connector = payment_data .payment_attempt .connector + .clone() .ok_or(sch_errors::ProcessTrackerError::MissingRequiredField)?; - retry_sync_task( + let is_last_retry = retry_sync_task( db, connector, - payment_data.payment_attempt.merchant_id, + payment_data.payment_attempt.merchant_id.clone(), process, ) - .await? + .await?; + + // If the payment status is still processing and there is no connector transaction_id + // then change the payment status to failed if all retries exceeded + if is_last_retry + && payment_data.payment_attempt.status == enums::AttemptStatus::Pending + && payment_data + .payment_attempt + .connector_transaction_id + .as_ref() + .is_none() + { + let payment_intent_update = data_models::payments::payment_intent::PaymentIntentUpdate::PGStatusUpdate { status: api_models::enums::IntentStatus::Failed }; + let payment_attempt_update = + data_models::payments::payment_attempt::PaymentAttemptUpdate::ErrorUpdate { + connector: None, + status: api_models::enums::AttemptStatus::AuthenticationFailed, + error_code: None, + error_message: None, + error_reason: Some(Some( + consts::REQUEST_TIMEOUT_ERROR_MESSAGE_FROM_PSYNC.to_string(), + )), + amount_capturable: Some(0), + }; + + payment_data.payment_attempt = db + .update_payment_attempt_with_attempt_id( + payment_data.payment_attempt, + payment_attempt_update, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + payment_data.payment_intent = db + .update_payment_intent( + payment_data.payment_intent, + payment_intent_update, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + // Trigger the outgoing webhook to notify the merchant about failed payment + let operation = operations::PaymentStatus; + utils::trigger_payments_webhook::<_, api_models::payments::PaymentsRequest, _>( + merchant_account, + payment_data, + None, + customer, + state, + operation, + ) + .await + .map_err(|error| logger::warn!(payments_outgoing_webhook_error=?error)) + .ok(); + } } }; Ok(()) @@ -117,6 +177,26 @@ impl ProcessTrackerWorkflow<AppState> for PaymentsSyncWorkflow { } } +/// Get the next schedule time +/// +/// The schedule time can be configured in configs by this key `pt_mapping_trustpay` +/// ```json +/// { +/// "default_mapping": { +/// "start_after": 60, +/// "frequency": [300], +/// "count": [5] +/// }, +/// "max_retries_count": 5 +/// } +/// ``` +/// +/// This config represents +/// +/// `start_after`: The first psync should happen after 60 seconds +/// +/// `frequency` and `count`: The next 5 retries should have an interval of 300 seconds between them +/// pub async fn get_sync_process_schedule_time( db: &dyn StorageInterface, connector: &str, @@ -142,25 +222,32 @@ pub async fn get_sync_process_schedule_time( process_data::ConnectorPTMapping::default() } }; - let time_delta = utils::get_schedule_time(mapping, merchant_id, retry_count + 1); + let time_delta = scheduler_utils::get_schedule_time(mapping, merchant_id, retry_count + 1); - Ok(utils::get_time_from_delta(time_delta)) + Ok(scheduler_utils::get_time_from_delta(time_delta)) } +/// Schedule the task for retry +/// +/// Returns bool which indicates whether this was the last retry or not pub async fn retry_sync_task( db: &dyn StorageInterface, connector: String, merchant_id: String, pt: storage::ProcessTracker, -) -> Result<(), sch_errors::ProcessTrackerError> { +) -> Result<bool, sch_errors::ProcessTrackerError> { let schedule_time = get_sync_process_schedule_time(db, &connector, &merchant_id, pt.retry_count).await?; match schedule_time { - Some(s_time) => pt.retry(db.as_scheduler(), s_time).await, + Some(s_time) => { + pt.retry(db.as_scheduler(), s_time).await?; + Ok(false) + } None => { pt.finish_with_status(db.as_scheduler(), "RETRIES_EXCEEDED".to_string()) - .await + .await?; + Ok(true) } } } @@ -173,9 +260,11 @@ mod tests { #[test] fn test_get_default_schedule_time() { let schedule_time_delta = - utils::get_schedule_time(process_data::ConnectorPTMapping::default(), "-", 0).unwrap(); + scheduler_utils::get_schedule_time(process_data::ConnectorPTMapping::default(), "-", 0) + .unwrap(); let first_retry_time_delta = - utils::get_schedule_time(process_data::ConnectorPTMapping::default(), "-", 1).unwrap(); + scheduler_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], diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs index 676ef330f9d..53f14bd1fb9 100644 --- a/crates/scheduler/src/utils.rs +++ b/crates/scheduler/src/utils.rs @@ -298,6 +298,7 @@ pub fn get_schedule_time( None => mapping.default_mapping, }; + // For first try, get the `start_after` time if retry_count == 0 { Some(mapping.start_after) } else { @@ -328,6 +329,7 @@ pub fn get_pm_schedule_time( } } +/// Get the delay based on the retry count fn get_delay<'a>( retry_count: i32, mut array: impl Iterator<Item = (&'a i32, &'a i32)>,
feat
make long standing payments failed (#2380)
ae7d16e23699c8ed95a7e2eab7539cfe20f847d0
2024-11-29 15:32:56
Prajjwal Kumar
refactor(currency_conversion): release redis lock if api call fails (#6671)
false
diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs index 2173478ab67..9ab2780da73 100644 --- a/crates/router/src/utils/currency.rs +++ b/crates/router/src/utils/currency.rs @@ -7,6 +7,7 @@ use error_stack::ResultExt; use masking::PeekInterface; use once_cell::sync::Lazy; use redis_interface::DelReply; +use router_env::{instrument, tracing}; use rust_decimal::Decimal; use strum::IntoEnumIterator; use tokio::{sync::RwLock, time::sleep}; @@ -150,11 +151,13 @@ impl TryFrom<DefaultExchangeRates> for ExchangeRates { let mut conversion_usable: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for (curr, conversion) in value.conversion { let enum_curr = enums::Currency::from_str(curr.as_str()) - .change_context(ForexCacheError::ConversionError)?; + .change_context(ForexCacheError::ConversionError) + .attach_printable("Unable to Convert currency received")?; conversion_usable.insert(enum_curr, CurrencyFactors::from(conversion)); } let base_curr = enums::Currency::from_str(value.base_currency.as_str()) - .change_context(ForexCacheError::ConversionError)?; + .change_context(ForexCacheError::ConversionError) + .attach_printable("Unable to convert base currency")?; Ok(Self { base_currency: base_curr, conversion: conversion_usable, @@ -170,6 +173,8 @@ impl From<Conversion> for CurrencyFactors { } } } + +#[instrument(skip_all)] pub async fn get_forex_rates( state: &SessionState, call_delay: i64, @@ -235,6 +240,7 @@ async fn successive_fetch_and_save_forex( Ok(rates) => Ok(successive_save_data_to_redis_local(state, rates).await?), Err(error) => stale_redis_data.ok_or({ logger::error!(?error); + release_redis_lock(state).await?; ForexCacheError::ApiUnresponsive.into() }), } @@ -254,9 +260,9 @@ async fn successive_save_data_to_redis_local( ) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { Ok(save_forex_to_redis(state, &forex) .await - .async_and_then(|_rates| async { release_redis_lock(state).await }) + .async_and_then(|_rates| release_redis_lock(state)) .await - .async_and_then(|_val| async { Ok(save_forex_to_local(forex.clone()).await) }) + .async_and_then(|_val| save_forex_to_local(forex.clone())) .await .map_or_else( |error| { @@ -336,11 +342,15 @@ async fn fetch_forex_rates( false, ) .await - .change_context(ForexCacheError::ApiUnresponsive)?; + .change_context(ForexCacheError::ApiUnresponsive) + .attach_printable("Primary forex fetch api unresponsive")?; let forex_response = response .json::<ForexResponse>() .await - .change_context(ForexCacheError::ParsingError)?; + .change_context(ForexCacheError::ParsingError) + .attach_printable( + "Unable to parse response received from primary api into ForexResponse", + )?; logger::info!("{:?}", forex_response); @@ -392,11 +402,16 @@ pub async fn fallback_fetch_forex_rates( false, ) .await - .change_context(ForexCacheError::ApiUnresponsive)?; + .change_context(ForexCacheError::ApiUnresponsive) + .attach_printable("Fallback forex fetch api unresponsive")?; + let fallback_forex_response = response .json::<FallbackForexResponse>() .await - .change_context(ForexCacheError::ParsingError)?; + .change_context(ForexCacheError::ParsingError) + .attach_printable( + "Unable to parse response received from falback api into ForexResponse", + )?; logger::info!("{:?}", fallback_forex_response); let mut conversions: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); @@ -453,6 +468,7 @@ async fn release_redis_lock( .delete_key(REDIX_FOREX_CACHE_KEY) .await .change_context(ForexCacheError::RedisLockReleaseFailed) + .attach_printable("Unable to release redis lock") } async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexCacheError> { @@ -475,6 +491,7 @@ async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexCac .await .map(|val| matches!(val, redis_interface::SetnxReply::KeySet)) .change_context(ForexCacheError::CouldNotAcquireLock) + .attach_printable("Unable to acquire redis lock") } async fn save_forex_to_redis( @@ -488,6 +505,7 @@ async fn save_forex_to_redis( .serialize_and_set_key(REDIX_FOREX_CACHE_DATA, forex_exchange_cache_entry) .await .change_context(ForexCacheError::RedisWriteError) + .attach_printable("Unable to save forex data to redis") } async fn retrieve_forex_from_redis( @@ -500,6 +518,7 @@ async fn retrieve_forex_from_redis( .get_and_deserialize_key(REDIX_FOREX_CACHE_DATA, "FxExchangeRatesCache") .await .change_context(ForexCacheError::EntryNotFound) + .attach_printable("Forex entry not found in redis") } async fn is_redis_expired( @@ -515,6 +534,7 @@ async fn is_redis_expired( }) } +#[instrument(skip_all)] pub async fn convert_currency( state: SessionState, amount: i64, @@ -532,14 +552,17 @@ pub async fn convert_currency( .change_context(ForexCacheError::ApiError)?; let to_currency = enums::Currency::from_str(to_currency.as_str()) - .change_context(ForexCacheError::CurrencyNotAcceptable)?; + .change_context(ForexCacheError::CurrencyNotAcceptable) + .attach_printable("The provided currency is not acceptable")?; let from_currency = enums::Currency::from_str(from_currency.as_str()) - .change_context(ForexCacheError::CurrencyNotAcceptable)?; + .change_context(ForexCacheError::CurrencyNotAcceptable) + .attach_printable("The provided currency is not acceptable")?; let converted_amount = currency_conversion::conversion::convert(&rates.data, from_currency, to_currency, amount) - .change_context(ForexCacheError::ConversionError)?; + .change_context(ForexCacheError::ConversionError) + .attach_printable("Unable to perform currency conversion")?; Ok(api_models::currency::CurrencyConversionResponse { converted_amount: converted_amount.to_string(),
refactor
release redis lock if api call fails (#6671)
c525c9f4c9d23802989bc594a4acd26c7d7cd27d
2024-12-19 13:11:44
sweta-kumari-sharma
feat(klarna): Klarna Kustom Checkout Integration (#6839)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 58a81caeed3..c8a87f1a617 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -11854,70 +11854,6 @@ } } }, - "OrderDetails": { - "type": "object", - "required": [ - "product_name", - "quantity" - ], - "properties": { - "product_name": { - "type": "string", - "description": "Name of the product that is being purchased", - "example": "shirt", - "maxLength": 255 - }, - "quantity": { - "type": "integer", - "format": "int32", - "description": "The quantity of the product to be purchased", - "example": 1, - "minimum": 0 - }, - "requires_shipping": { - "type": "boolean", - "nullable": true - }, - "product_img_link": { - "type": "string", - "description": "The image URL of the product", - "nullable": true - }, - "product_id": { - "type": "string", - "description": "ID of the product that is being purchased", - "nullable": true - }, - "category": { - "type": "string", - "description": "Category of the product that is being purchased", - "nullable": true - }, - "sub_category": { - "type": "string", - "description": "Sub category of the product that is being purchased", - "nullable": true - }, - "brand": { - "type": "string", - "description": "Brand of the product that is being purchased", - "nullable": true - }, - "product_type": { - "allOf": [ - { - "$ref": "#/components/schemas/ProductType" - } - ], - "nullable": true - }, - "product_tax_code": { - "type": "string", - "description": "The tax code for the product", - "nullable": true - } - } - }, "OrderDetailsWithAmount": { "type": "object", "required": [ @@ -11940,7 +11876,21 @@ "minimum": 0 }, "amount": { - "$ref": "#/components/schemas/MinorUnit" + "type": "integer", + "format": "int64", + "description": "the amount per quantity of product" + }, + "tax_rate": { + "type": "number", + "format": "double", + "description": "tax rate applicable to the product", + "nullable": true + }, + "total_tax_amount": { + "type": "integer", + "format": "int64", + "description": "total tax amount applicable to the product", + "nullable": true }, "requires_shipping": { "type": "boolean", @@ -12353,6 +12303,17 @@ } } }, + { + "type": "object", + "required": [ + "klarna_checkout" + ], + "properties": { + "klarna_checkout": { + "type": "object" + } + } + }, { "type": "object", "required": [ @@ -12486,6 +12447,13 @@ "description": "The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,", "example": 6540 }, + "order_tax_amount": { + "type": "integer", + "format": "int64", + "description": "The payment attempt tax_amount.", + "example": 6540, + "nullable": true + }, "currency": { "allOf": [ { diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 33dd5d87a47..57e4ac1948a 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -14732,70 +14732,6 @@ } } }, - "OrderDetails": { - "type": "object", - "required": [ - "product_name", - "quantity" - ], - "properties": { - "product_name": { - "type": "string", - "description": "Name of the product that is being purchased", - "example": "shirt", - "maxLength": 255 - }, - "quantity": { - "type": "integer", - "format": "int32", - "description": "The quantity of the product to be purchased", - "example": 1, - "minimum": 0 - }, - "requires_shipping": { - "type": "boolean", - "nullable": true - }, - "product_img_link": { - "type": "string", - "description": "The image URL of the product", - "nullable": true - }, - "product_id": { - "type": "string", - "description": "ID of the product that is being purchased", - "nullable": true - }, - "category": { - "type": "string", - "description": "Category of the product that is being purchased", - "nullable": true - }, - "sub_category": { - "type": "string", - "description": "Sub category of the product that is being purchased", - "nullable": true - }, - "brand": { - "type": "string", - "description": "Brand of the product that is being purchased", - "nullable": true - }, - "product_type": { - "allOf": [ - { - "$ref": "#/components/schemas/ProductType" - } - ], - "nullable": true - }, - "product_tax_code": { - "type": "string", - "description": "The tax code for the product", - "nullable": true - } - } - }, "OrderDetailsWithAmount": { "type": "object", "required": [ @@ -14818,7 +14754,21 @@ "minimum": 0 }, "amount": { - "$ref": "#/components/schemas/MinorUnit" + "type": "integer", + "format": "int64", + "description": "the amount per quantity of product" + }, + "tax_rate": { + "type": "number", + "format": "double", + "description": "tax rate applicable to the product", + "nullable": true + }, + "total_tax_amount": { + "type": "integer", + "format": "int64", + "description": "total tax amount applicable to the product", + "nullable": true }, "requires_shipping": { "type": "boolean", @@ -15224,6 +15174,17 @@ } } }, + { + "type": "object", + "required": [ + "klarna_checkout" + ], + "properties": { + "klarna_checkout": { + "type": "object" + } + } + }, { "type": "object", "required": [ @@ -15357,6 +15318,13 @@ "description": "The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,", "example": 6540 }, + "order_tax_amount": { + "type": "integer", + "format": "int64", + "description": "The payment attempt tax_amount.", + "example": 6540, + "nullable": true + }, "currency": { "allOf": [ { @@ -17155,6 +17123,13 @@ "nullable": true, "minimum": 0 }, + "order_tax_amount": { + "type": "integer", + "format": "int64", + "description": "Total tax amount applicable to the order", + "example": 6540, + "nullable": true + }, "currency": { "allOf": [ { @@ -17533,6 +17508,13 @@ "description": "The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1Β₯ since Β₯ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies)", "minimum": 0 }, + "order_tax_amount": { + "type": "integer", + "format": "int64", + "description": "Total tax amount applicable to the order", + "example": 6540, + "nullable": true + }, "currency": { "$ref": "#/components/schemas/Currency" }, @@ -18659,6 +18641,13 @@ "nullable": true, "minimum": 0 }, + "order_tax_amount": { + "type": "integer", + "format": "int64", + "description": "Total tax amount applicable to the order", + "example": 6540, + "nullable": true + }, "currency": { "allOf": [ { @@ -19805,6 +19794,13 @@ "nullable": true, "minimum": 0 }, + "order_tax_amount": { + "type": "integer", + "format": "int64", + "description": "Total tax amount applicable to the order", + "example": 6540, + "nullable": true + }, "currency": { "allOf": [ { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 0381e347f4f..632d40a0951 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -741,6 +741,10 @@ pub struct PaymentsRequest { // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, + /// Total tax amount applicable to the order + #[schema(value_type = Option<i64>, example = 6540)] + pub order_tax_amount: Option<MinorUnit>, + /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] @@ -1308,6 +1312,9 @@ pub struct PaymentAttemptResponse { /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, + /// The payment attempt tax_amount. + #[schema(value_type = Option<i64>, example = 6540)] + pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, @@ -1858,6 +1865,7 @@ pub enum PayLaterData { /// The token for the sdk workflow token: String, }, + KlarnaCheckout {}, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option @@ -1915,6 +1923,7 @@ impl GetAddressFromPaymentMethodData for PayLaterData { | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } + | Self::KlarnaCheckout {} | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } @@ -2376,6 +2385,7 @@ impl GetPaymentMethodType for PayLaterData { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, + Self::KlarnaCheckout {} => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, @@ -5471,7 +5481,7 @@ pub struct PaymentsRetrieveRequest { pub expand_attempts: Option<bool>, } -#[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] +#[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] @@ -5480,7 +5490,13 @@ pub struct OrderDetailsWithAmount { #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product + #[schema(value_type = i64)] pub amount: MinorUnit, + /// tax rate applicable to the product + pub tax_rate: Option<f64>, + /// total tax amount applicable to the product + #[schema(value_type = Option<i64>)] + pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product @@ -5501,32 +5517,6 @@ pub struct OrderDetailsWithAmount { impl masking::SerializableSecret for OrderDetailsWithAmount {} -#[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] -pub struct OrderDetails { - /// Name of the product that is being purchased - #[schema(max_length = 255, example = "shirt")] - pub product_name: String, - /// The quantity of the product to be purchased - #[schema(example = 1)] - pub quantity: u16, - // Does the order include shipping - pub requires_shipping: Option<bool>, - /// The image URL of the product - pub product_img_link: Option<String>, - /// ID of the product that is being purchased - pub product_id: Option<String>, - /// Category of the product that is being purchased - pub category: Option<String>, - /// Sub category of the product that is being purchased - pub sub_category: Option<String>, - /// Brand of the product that is being purchased - pub brand: Option<String>, - /// Type of the product that is being purchased - pub product_type: Option<ProductType>, - /// The tax code for the product - pub product_tax_code: Option<String>, -} - #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] diff --git a/crates/diesel_models/src/types.rs b/crates/diesel_models/src/types.rs index 94f1fa8d266..6562abab4d6 100644 --- a/crates/diesel_models/src/types.rs +++ b/crates/diesel_models/src/types.rs @@ -30,6 +30,10 @@ pub struct OrderDetailsWithAmount { pub product_type: Option<common_enums::ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, + /// tax rate applicable to the product + pub tax_rate: Option<f64>, + /// total tax amount applicable to the product + pub total_tax_amount: Option<MinorUnit>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} diff --git a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs index 479abf13b13..a60e8bdc79e 100644 --- a/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs @@ -746,6 +746,7 @@ impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>> email: Some(match paylater { PayLaterData::KlarnaRedirect {} => item.router_data.get_billing_email()?, PayLaterData::KlarnaSdk { token: _ } + | PayLaterData::KlarnaCheckout {} | PayLaterData::AffirmRedirect {} | PayLaterData::AfterpayClearpayRedirect {} | PayLaterData::PayBrightRedirect {} diff --git a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs index 08ca9a54fa4..5abc93b3f88 100644 --- a/crates/hyperswitch_connectors/src/connectors/square/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/square/transformers.rs @@ -85,6 +85,7 @@ impl TryFrom<(&types::TokenizationRouterData, PayLaterData)> for SquareTokenRequ PayLaterData::AfterpayClearpayRedirect { .. } | PayLaterData::KlarnaRedirect { .. } | PayLaterData::KlarnaSdk { .. } + | PayLaterData::KlarnaCheckout {} | PayLaterData::AffirmRedirect { .. } | PayLaterData::PayBrightRedirect { .. } | PayLaterData::WalleyRedirect { .. } diff --git a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs index 7a30a434a5d..41dc60f8248 100644 --- a/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/zen/transformers.rs @@ -751,6 +751,7 @@ impl TryFrom<&PayLaterData> for ZenPaymentsRequest { match value { PayLaterData::KlarnaRedirect { .. } | PayLaterData::KlarnaSdk { .. } + | PayLaterData::KlarnaCheckout {} | PayLaterData::AffirmRedirect {} | PayLaterData::AfterpayClearpayRedirect { .. } | PayLaterData::PayBrightRedirect {} diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs index 6dce48e6996..cf32d966e05 100644 --- a/crates/hyperswitch_connectors/src/utils.rs +++ b/crates/hyperswitch_connectors/src/utils.rs @@ -2092,6 +2092,7 @@ pub enum PaymentMethodDataType { SwishQr, KlarnaRedirect, KlarnaSdk, + KlarnaCheckout, AffirmRedirect, AfterpayClearpayRedirect, PayBrightRedirect, @@ -2216,6 +2217,7 @@ impl From<PaymentMethodData> for PaymentMethodDataType { PaymentMethodData::PayLater(pay_later_data) => match pay_later_data { payment_method_data::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect, payment_method_data::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk, + payment_method_data::PayLaterData::KlarnaCheckout {} => Self::KlarnaCheckout, payment_method_data::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect, payment_method_data::PayLaterData::AfterpayClearpayRedirect { .. } => { Self::AfterpayClearpayRedirect diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index 0e8722644bd..6e353afd399 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -133,6 +133,8 @@ impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsW brand, product_type, product_tax_code, + tax_rate, + total_tax_amount, } = from; Self { product_name, @@ -146,6 +148,8 @@ impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsW brand, product_type, product_tax_code, + tax_rate, + total_tax_amount, } } @@ -162,6 +166,8 @@ impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsW brand, product_type, product_tax_code, + tax_rate, + total_tax_amount, } = self; ApiOrderDetailsWithAmount { product_name, @@ -175,6 +181,8 @@ impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsW brand, product_type, product_tax_code, + tax_rate, + total_tax_amount, } } } diff --git a/crates/hyperswitch_domain_models/src/payment_method_data.rs b/crates/hyperswitch_domain_models/src/payment_method_data.rs index 169719cb5da..8c19a20ef32 100644 --- a/crates/hyperswitch_domain_models/src/payment_method_data.rs +++ b/crates/hyperswitch_domain_models/src/payment_method_data.rs @@ -155,6 +155,7 @@ pub enum CardRedirectData { pub enum PayLaterData { KlarnaRedirect {}, KlarnaSdk { token: String }, + KlarnaCheckout {}, AffirmRedirect {}, AfterpayClearpayRedirect {}, PayBrightRedirect {}, @@ -897,6 +898,7 @@ impl From<api_models::payments::PayLaterData> for PayLaterData { match value { api_models::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect {}, api_models::payments::PayLaterData::KlarnaSdk { token } => Self::KlarnaSdk { token }, + api_models::payments::PayLaterData::KlarnaCheckout {} => Self::KlarnaCheckout {}, api_models::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect {}, api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { Self::AfterpayClearpayRedirect {} @@ -1550,6 +1552,7 @@ impl GetPaymentMethodType for PayLaterData { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, + Self::KlarnaCheckout {} => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index 2f68b481d88..0e25e195c73 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -29,6 +29,7 @@ pub struct PaymentsAuthorizeData { /// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount /// ``` pub amount: i64, + pub order_tax_amount: Option<MinorUnit>, pub email: Option<pii::Email>, pub customer_name: Option<Secret<String>>, pub currency: storage_enums::Currency, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 65c76f8929f..03c28031869 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -381,7 +381,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::SwishQrData, api_models::payments::AirwallexData, api_models::payments::NoonData, - api_models::payments::OrderDetails, api_models::payments::OrderDetailsWithAmount, api_models::payments::NextActionType, api_models::payments::WalletData, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index b5de979b3ae..c9e4595ef49 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -341,7 +341,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::SwishQrData, api_models::payments::AirwallexData, api_models::payments::NoonData, - api_models::payments::OrderDetails, api_models::payments::OrderDetailsWithAmount, api_models::payments::NextActionType, api_models::payments::WalletData, diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index d0dad91f717..aece1df6546 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -2350,7 +2350,8 @@ impl check_required_field(billing_address, "billing")?; Ok(AdyenPaymentMethod::Atome) } - domain::payments::PayLaterData::KlarnaSdk { .. } => { + domain::payments::PayLaterData::KlarnaCheckout {} + | domain::payments::PayLaterData::KlarnaSdk { .. } => { Err(errors::ConnectorError::NotImplemented( utils::get_unimplemented_payment_method_error_message("Adyen"), ) diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index d2bdaae0493..77e2a027d83 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -448,7 +448,24 @@ impl let endpoint = build_region_specific_endpoint(self.base_url(connectors), &req.connector_meta_data)?; - Ok(format!("{endpoint}ordermanagement/v1/orders/{order_id}")) + let payment_experience = req.request.payment_experience; + + match payment_experience { + Some(common_enums::PaymentExperience::InvokeSdkClient) => { + Ok(format!("{endpoint}ordermanagement/v1/orders/{order_id}")) + } + Some(common_enums::PaymentExperience::RedirectToUrl) => { + Ok(format!("{endpoint}checkout/v3/orders/{order_id}")) + } + None => Err(error_stack::report!(errors::ConnectorError::NotSupported { + message: "payment_experience not supported".to_string(), + connector: "klarna", + })), + _ => Err(error_stack::report!(errors::ConnectorError::NotSupported { + message: "payment_experience not supported".to_string(), + connector: "klarna", + })), + } } fn build_request( @@ -653,6 +670,122 @@ impl })), } } + domain::PaymentMethodData::PayLater(domain::PayLaterData::KlarnaCheckout {}) => { + match (payment_experience, payment_method_type) { + ( + common_enums::PaymentExperience::RedirectToUrl, + common_enums::PaymentMethodType::Klarna, + ) => Ok(format!("{endpoint}checkout/v3/orders",)), + ( + common_enums::PaymentExperience::DisplayQrCode + | common_enums::PaymentExperience::DisplayWaitScreen + | common_enums::PaymentExperience::InvokePaymentApp + | common_enums::PaymentExperience::InvokeSdkClient + | common_enums::PaymentExperience::LinkWallet + | common_enums::PaymentExperience::OneClick + | common_enums::PaymentExperience::RedirectToUrl + | common_enums::PaymentExperience::CollectOtp, + common_enums::PaymentMethodType::Ach + | common_enums::PaymentMethodType::Affirm + | common_enums::PaymentMethodType::AfterpayClearpay + | common_enums::PaymentMethodType::Alfamart + | common_enums::PaymentMethodType::AliPay + | common_enums::PaymentMethodType::AliPayHk + | common_enums::PaymentMethodType::Alma + | common_enums::PaymentMethodType::ApplePay + | common_enums::PaymentMethodType::Atome + | common_enums::PaymentMethodType::Bacs + | common_enums::PaymentMethodType::BancontactCard + | common_enums::PaymentMethodType::Becs + | common_enums::PaymentMethodType::Benefit + | common_enums::PaymentMethodType::Bizum + | common_enums::PaymentMethodType::Blik + | common_enums::PaymentMethodType::Boleto + | common_enums::PaymentMethodType::BcaBankTransfer + | common_enums::PaymentMethodType::BniVa + | common_enums::PaymentMethodType::BriVa + | common_enums::PaymentMethodType::CardRedirect + | common_enums::PaymentMethodType::CimbVa + | common_enums::PaymentMethodType::ClassicReward + | common_enums::PaymentMethodType::Credit + | common_enums::PaymentMethodType::CryptoCurrency + | common_enums::PaymentMethodType::Cashapp + | common_enums::PaymentMethodType::Dana + | common_enums::PaymentMethodType::DanamonVa + | common_enums::PaymentMethodType::Debit + | common_enums::PaymentMethodType::DirectCarrierBilling + | common_enums::PaymentMethodType::Efecty + | common_enums::PaymentMethodType::Eps + | common_enums::PaymentMethodType::Evoucher + | common_enums::PaymentMethodType::Giropay + | common_enums::PaymentMethodType::Givex + | common_enums::PaymentMethodType::GooglePay + | common_enums::PaymentMethodType::GoPay + | common_enums::PaymentMethodType::Gcash + | common_enums::PaymentMethodType::Ideal + | common_enums::PaymentMethodType::Interac + | common_enums::PaymentMethodType::Indomaret + | common_enums::PaymentMethodType::Klarna + | common_enums::PaymentMethodType::KakaoPay + | common_enums::PaymentMethodType::MandiriVa + | common_enums::PaymentMethodType::Knet + | common_enums::PaymentMethodType::MbWay + | common_enums::PaymentMethodType::MobilePay + | common_enums::PaymentMethodType::Momo + | common_enums::PaymentMethodType::MomoAtm + | common_enums::PaymentMethodType::Multibanco + | common_enums::PaymentMethodType::LocalBankRedirect + | common_enums::PaymentMethodType::OnlineBankingThailand + | common_enums::PaymentMethodType::OnlineBankingCzechRepublic + | common_enums::PaymentMethodType::OnlineBankingFinland + | common_enums::PaymentMethodType::OnlineBankingFpx + | common_enums::PaymentMethodType::OnlineBankingPoland + | common_enums::PaymentMethodType::OnlineBankingSlovakia + | common_enums::PaymentMethodType::Oxxo + | common_enums::PaymentMethodType::PagoEfectivo + | common_enums::PaymentMethodType::PermataBankTransfer + | common_enums::PaymentMethodType::OpenBankingUk + | common_enums::PaymentMethodType::PayBright + | common_enums::PaymentMethodType::Paypal + | common_enums::PaymentMethodType::Paze + | common_enums::PaymentMethodType::Pix + | common_enums::PaymentMethodType::PaySafeCard + | common_enums::PaymentMethodType::Przelewy24 + | common_enums::PaymentMethodType::Pse + | common_enums::PaymentMethodType::RedCompra + | common_enums::PaymentMethodType::RedPagos + | common_enums::PaymentMethodType::SamsungPay + | common_enums::PaymentMethodType::Sepa + | common_enums::PaymentMethodType::Sofort + | common_enums::PaymentMethodType::Swish + | common_enums::PaymentMethodType::TouchNGo + | common_enums::PaymentMethodType::Trustly + | common_enums::PaymentMethodType::Twint + | common_enums::PaymentMethodType::UpiCollect + | common_enums::PaymentMethodType::UpiIntent + | common_enums::PaymentMethodType::Venmo + | common_enums::PaymentMethodType::Vipps + | common_enums::PaymentMethodType::Walley + | common_enums::PaymentMethodType::WeChatPay + | common_enums::PaymentMethodType::SevenEleven + | common_enums::PaymentMethodType::Lawson + | common_enums::PaymentMethodType::LocalBankTransfer + | common_enums::PaymentMethodType::MiniStop + | common_enums::PaymentMethodType::FamilyMart + | common_enums::PaymentMethodType::Seicomart + | common_enums::PaymentMethodType::PayEasy + | common_enums::PaymentMethodType::Mifinity + | common_enums::PaymentMethodType::Fps + | common_enums::PaymentMethodType::DuitNow + | common_enums::PaymentMethodType::PromptPay + | common_enums::PaymentMethodType::VietQr + | common_enums::PaymentMethodType::OpenBankingPIS, + ) => Err(error_stack::report!(errors::ConnectorError::NotSupported { + message: payment_method_type.to_string(), + connector: "klarna", + })), + } + } domain::PaymentMethodData::Card(_) | domain::PaymentMethodData::CardRedirect(_) @@ -726,7 +859,7 @@ impl event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: klarna::KlarnaPaymentsResponse = res + let response: klarna::KlarnaAuthResponse = res .response .parse_struct("KlarnaPaymentsResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs index 803dc4a428d..0826b0f2665 100644 --- a/crates/router/src/connector/klarna/transformers.rs +++ b/crates/router/src/connector/klarna/transformers.rs @@ -1,7 +1,9 @@ use api_models::payments; use common_utils::{pii, types::MinorUnit}; use error_stack::{report, ResultExt}; -use hyperswitch_domain_models::router_data::KlarnaSdkResponse; +use hyperswitch_domain_models::{ + router_data::KlarnaSdkResponse, router_response_types::RedirectForm, +}; use masking::{ExposeInterface, Secret}; use serde::{Deserialize, Serialize}; @@ -10,7 +12,7 @@ use crate::{ self, AddressData, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData, }, core::errors, - types::{self, api, storage::enums, transformers::ForeignFrom}, + types::{self, api, domain, storage::enums, transformers::ForeignFrom}, }; #[derive(Debug, Serialize)] @@ -61,9 +63,29 @@ impl TryFrom<&Option<pii::SecretSerdeValue>> for KlarnaConnectorMetadataObject { } } -#[derive(Default, Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] +#[serde(untagged)] +pub enum PaymentMethodSpecifics { + KlarnaCheckout(KlarnaCheckoutRequestData), + KlarnaSdk, +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct MerchantURLs { + terms: String, + checkout: String, + confirmation: String, + push: String, +} + +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct KlarnaCheckoutRequestData { + merchant_urls: MerchantURLs, + options: CheckoutOptions, +} + +#[derive(Default, Debug, Deserialize, Serialize)] pub struct KlarnaPaymentsRequest { - auto_capture: bool, order_lines: Vec<OrderLines>, order_amount: MinorUnit, purchase_country: enums::CountryAlpha2, @@ -71,15 +93,32 @@ pub struct KlarnaPaymentsRequest { merchant_reference1: Option<String>, merchant_reference2: Option<String>, shipping_address: Option<KlarnaShippingAddress>, + auto_capture: Option<bool>, + order_tax_amount: Option<MinorUnit>, + #[serde(flatten)] + payment_method_specifics: Option<PaymentMethodSpecifics>, } #[derive(Debug, Deserialize, Serialize)] -pub struct KlarnaPaymentsResponse { +#[serde(untagged)] +pub enum KlarnaAuthResponse { + KlarnaPaymentsAuthResponse(PaymentsResponse), + KlarnaCheckoutAuthResponse(CheckoutResponse), +} + +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct PaymentsResponse { order_id: String, fraud_status: KlarnaFraudStatus, authorized_payment_method: Option<AuthorizedPaymentMethod>, } +#[derive(Debug, Clone, Deserialize, Serialize)] +pub struct CheckoutResponse { + order_id: String, + status: KlarnaCheckoutStatus, + html_snippet: String, +} #[derive(Debug, Clone, Deserialize, Serialize)] pub struct AuthorizedPaymentMethod { #[serde(rename = "type")] @@ -106,7 +145,7 @@ pub struct KlarnaSessionRequest { shipping_address: Option<KlarnaShippingAddress>, } -#[derive(Debug, Serialize)] +#[derive(Debug, Serialize, Deserialize)] pub struct KlarnaShippingAddress { city: String, country: enums::CountryAlpha2, @@ -120,6 +159,10 @@ pub struct KlarnaShippingAddress { street_address2: Option<Secret<String>>, } +#[derive(Default, Debug, Serialize, Deserialize)] +pub struct CheckoutOptions { + auto_capture: bool, +} #[derive(Deserialize, Serialize, Debug)] pub struct KlarnaSessionResponse { pub client_token: Secret<String>, @@ -149,6 +192,8 @@ impl TryFrom<&KlarnaRouterData<&types::PaymentsSessionRouterData>> for KlarnaSes quantity: data.quantity, unit_price: data.amount, total_amount: data.amount * data.quantity, + total_tax_amount: None, + tax_rate: None, }) .collect(), shipping_address: get_address_info(item.router_data.get_optional_shipping()) @@ -190,29 +235,100 @@ impl TryFrom<&KlarnaRouterData<&types::PaymentsAuthorizeRouterData>> for KlarnaP item: &KlarnaRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { let request = &item.router_data.request; - match request.order_details.clone() { - Some(order_details) => Ok(Self { - purchase_country: item.router_data.get_billing_country()?, - purchase_currency: request.currency, - order_amount: item.amount, - order_lines: order_details - .iter() - .map(|data| OrderLines { - name: data.product_name.clone(), - quantity: data.quantity, - unit_price: data.amount, - total_amount: data.amount * data.quantity, - }) - .collect(), - merchant_reference1: Some(item.router_data.connector_request_reference_id.clone()), - merchant_reference2: item.router_data.request.merchant_order_reference_id.clone(), - auto_capture: request.is_auto_capture()?, - shipping_address: get_address_info(item.router_data.get_optional_shipping()) - .transpose()?, - }), - None => Err(report!(errors::ConnectorError::MissingRequiredField { - field_name: "order_details" - })), + let payment_method_data = request.payment_method_data.clone(); + let return_url = item.router_data.request.get_return_url()?; + let webhook_url = item.router_data.request.get_webhook_url()?; + match payment_method_data { + domain::PaymentMethodData::PayLater(domain::PayLaterData::KlarnaSdk { .. }) => { + match request.order_details.clone() { + Some(order_details) => Ok(Self { + purchase_country: item.router_data.get_billing_country()?, + purchase_currency: request.currency, + order_amount: item.amount, + order_lines: order_details + .iter() + .map(|data| OrderLines { + name: data.product_name.clone(), + quantity: data.quantity, + unit_price: data.amount, + total_amount: data.amount * data.quantity, + total_tax_amount: None, + tax_rate: None, + }) + .collect(), + merchant_reference1: Some( + item.router_data.connector_request_reference_id.clone(), + ), + merchant_reference2: item + .router_data + .request + .merchant_order_reference_id + .clone(), + auto_capture: Some(request.is_auto_capture()?), + shipping_address: get_address_info( + item.router_data.get_optional_shipping(), + ) + .transpose()?, + order_tax_amount: None, + payment_method_specifics: None, + }), + None => Err(report!(errors::ConnectorError::MissingRequiredField { + field_name: "order_details" + })), + } + } + domain::PaymentMethodData::PayLater(domain::PayLaterData::KlarnaCheckout {}) => { + match request.order_details.clone() { + Some(order_details) => Ok(Self { + purchase_country: item.router_data.get_billing_country()?, + purchase_currency: request.currency, + order_amount: item.amount + - request.order_tax_amount.unwrap_or(MinorUnit::zero()), + order_tax_amount: request.order_tax_amount, + order_lines: order_details + .iter() + .map(|data| OrderLines { + name: data.product_name.clone(), + quantity: data.quantity, + unit_price: data.amount, + total_amount: data.amount * data.quantity, + total_tax_amount: data.total_tax_amount, + tax_rate: data.tax_rate, + }) + .collect(), + payment_method_specifics: Some(PaymentMethodSpecifics::KlarnaCheckout( + KlarnaCheckoutRequestData { + merchant_urls: MerchantURLs { + terms: return_url.clone(), + checkout: return_url.clone(), + confirmation: return_url, + push: webhook_url, + }, + options: CheckoutOptions { + auto_capture: request.is_auto_capture()?, + }, + }, + )), + shipping_address: get_address_info( + item.router_data.get_optional_shipping(), + ) + .transpose()?, + merchant_reference1: Some( + item.router_data.connector_request_reference_id.clone(), + ), + merchant_reference2: item + .router_data + .request + .merchant_order_reference_id + .clone(), + auto_capture: None, + }), + None => Err(report!(errors::ConnectorError::MissingRequiredField { + field_name: "order_details" + })), + } + } + _ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()), } } } @@ -240,53 +356,82 @@ fn get_address_info( }) } -impl TryFrom<types::PaymentsResponseRouterData<KlarnaPaymentsResponse>> +impl TryFrom<types::PaymentsResponseRouterData<KlarnaAuthResponse>> for types::PaymentsAuthorizeRouterData { type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( - item: types::PaymentsResponseRouterData<KlarnaPaymentsResponse>, + item: types::PaymentsResponseRouterData<KlarnaAuthResponse>, ) -> Result<Self, Self::Error> { - let connector_response = types::ConnectorResponseData::with_additional_payment_method_data( - match item.response.authorized_payment_method { - Some(authorized_payment_method) => { - types::AdditionalPaymentMethodConnectorResponse::from(authorized_payment_method) - } - None => { - types::AdditionalPaymentMethodConnectorResponse::PayLater { klarna_sdk: None } - } - }, - ); - - Ok(Self { - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - item.response.order_id.clone(), - ), - redirection_data: Box::new(None), - mandate_reference: Box::new(None), - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: Some(item.response.order_id.clone()), - incremental_authorization_allowed: None, - charge_id: None, + match item.response { + KlarnaAuthResponse::KlarnaPaymentsAuthResponse(ref response) => { + let connector_response = + response + .authorized_payment_method + .as_ref() + .map(|authorized_payment_method| { + types::ConnectorResponseData::with_additional_payment_method_data( + types::AdditionalPaymentMethodConnectorResponse::from( + authorized_payment_method.clone(), + ), + ) + }); + + Ok(Self { + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + response.order_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(response.order_id.clone()), + incremental_authorization_allowed: None, + charge_id: None, + }), + status: enums::AttemptStatus::foreign_from(( + response.fraud_status.clone(), + item.data.request.is_auto_capture()?, + )), + connector_response, + ..item.data + }) + } + KlarnaAuthResponse::KlarnaCheckoutAuthResponse(ref response) => Ok(Self { + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + response.order_id.clone(), + ), + redirection_data: Box::new(Some(RedirectForm::Html { + html_data: response.html_snippet.clone(), + })), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(response.order_id.clone()), + incremental_authorization_allowed: None, + charge_id: None, + }), + status: enums::AttemptStatus::foreign_from(( + response.status.clone(), + item.data.request.is_auto_capture()?, + )), + connector_response: None, + ..item.data }), - status: enums::AttemptStatus::foreign_from(( - item.response.fraud_status, - item.data.request.is_auto_capture()?, - )), - connector_response: Some(connector_response), - ..item.data - }) + } } } - -#[derive(Debug, Serialize)] +#[derive(Default, Debug, Serialize, Deserialize)] pub struct OrderLines { name: String, quantity: u16, unit_price: MinorUnit, total_amount: MinorUnit, + total_tax_amount: Option<MinorUnit>, + tax_rate: Option<f64>, } #[derive(Debug, Serialize)] @@ -325,6 +470,13 @@ pub enum KlarnaFraudStatus { Rejected, } +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum KlarnaCheckoutStatus { + CheckoutComplete, + CheckoutIncomplete, +} + impl ForeignFrom<(KlarnaFraudStatus, bool)> for enums::AttemptStatus { fn foreign_from((klarna_status, is_auto_capture): (KlarnaFraudStatus, bool)) -> Self { match klarna_status { @@ -341,13 +493,42 @@ impl ForeignFrom<(KlarnaFraudStatus, bool)> for enums::AttemptStatus { } } +impl ForeignFrom<(KlarnaCheckoutStatus, bool)> for enums::AttemptStatus { + fn foreign_from((klarna_status, is_auto_capture): (KlarnaCheckoutStatus, bool)) -> Self { + match klarna_status { + KlarnaCheckoutStatus::CheckoutIncomplete => { + if is_auto_capture { + Self::AuthenticationPending + } else { + Self::Authorized + } + } + KlarnaCheckoutStatus::CheckoutComplete => Self::Charged, + } + } +} + +#[derive(Debug, Deserialize, Serialize)] +#[serde(untagged)] +pub enum KlarnaPsyncResponse { + KlarnaSDKPsyncResponse(KlarnaSDKSyncResponse), + KlarnaCheckoutPSyncResponse(KlarnaCheckoutSyncResponse), +} + #[derive(Debug, Serialize, Deserialize)] -pub struct KlarnaPsyncResponse { +pub struct KlarnaSDKSyncResponse { pub order_id: String, pub status: KlarnaPaymentStatus, pub klarna_reference: Option<String>, } +#[derive(Debug, Serialize, Deserialize)] +pub struct KlarnaCheckoutSyncResponse { + pub order_id: String, + pub status: KlarnaCheckoutStatus, + pub options: CheckoutOptions, +} + #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum KlarnaPaymentStatus { @@ -379,25 +560,45 @@ impl<F, T> fn try_from( item: types::ResponseRouterData<F, KlarnaPsyncResponse, 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.order_id.clone(), - ), - redirection_data: Box::new(None), - mandate_reference: Box::new(None), - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: item - .response - .klarna_reference - .or(Some(item.response.order_id)), - incremental_authorization_allowed: None, - charge_id: None, + match item.response { + KlarnaPsyncResponse::KlarnaSDKPsyncResponse(response) => Ok(Self { + status: enums::AttemptStatus::from(response.status), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + response.order_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: response + .klarna_reference + .or(Some(response.order_id.clone())), + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data }), - ..item.data - }) + KlarnaPsyncResponse::KlarnaCheckoutPSyncResponse(response) => Ok(Self { + status: enums::AttemptStatus::foreign_from(( + response.status.clone(), + response.options.auto_capture, + )), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + response.order_id.clone(), + ), + redirection_data: Box::new(None), + mandate_reference: Box::new(None), + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some(response.order_id.clone()), + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }), + } } } diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 121ec1d7b7c..a4195655ed3 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -977,6 +977,7 @@ where get_pay_later_info(AlternativePaymentMethodType::AfterPay, item) } domain::PayLaterData::KlarnaSdk { .. } + | domain::PayLaterData::KlarnaCheckout {} | domain::PayLaterData::AffirmRedirect {} | domain::PayLaterData::PayBrightRedirect {} | domain::PayLaterData::WalleyRedirect {} diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index 11e01b78e13..600b7ab0e22 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -1256,6 +1256,7 @@ impl TryFrom<&domain::PayLaterData> for PaypalPaymentsRequest { match value { domain::PayLaterData::KlarnaRedirect { .. } | domain::PayLaterData::KlarnaSdk { .. } + | domain::PayLaterData::KlarnaCheckout {} | domain::PayLaterData::AffirmRedirect {} | domain::PayLaterData::AfterpayClearpayRedirect { .. } | domain::PayLaterData::PayBrightRedirect {} diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 2f0b0e0316f..262b0348b5a 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -992,6 +992,7 @@ impl TryFrom<&domain::payments::PayLaterData> for StripePaymentMethodType { } domain::PayLaterData::KlarnaSdk { .. } + | domain::PayLaterData::KlarnaCheckout {} | domain::PayLaterData::PayBrightRedirect {} | domain::PayLaterData::WalleyRedirect {} | domain::PayLaterData::AlmaRedirect {} diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 1ea7565f69f..171f19bc70a 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -2793,6 +2793,7 @@ pub enum PaymentMethodDataType { SwishQr, KlarnaRedirect, KlarnaSdk, + KlarnaCheckout, AffirmRedirect, AfterpayClearpayRedirect, PayBrightRedirect, @@ -2916,6 +2917,7 @@ impl From<domain::payments::PaymentMethodData> for PaymentMethodDataType { domain::payments::PaymentMethodData::PayLater(pay_later_data) => match pay_later_data { domain::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect, domain::payments::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk, + domain::payments::PayLaterData::KlarnaCheckout {} => Self::KlarnaCheckout, domain::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect, domain::payments::PayLaterData::AfterpayClearpayRedirect { .. } => { Self::AfterpayClearpayRedirect diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index aa551ce6fff..96406932445 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1514,6 +1514,7 @@ impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for surcharge_amount, tax_amount, ), + connector_mandate_detail: payment_data .payment_attempt .connector_mandate_detail, diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index a316d6edc37..36b338f2d52 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -1428,6 +1428,15 @@ impl PaymentCreate { let skip_external_tax_calculation = request.skip_external_tax_calculation; + let tax_details = request + .order_tax_amount + .map(|tax_amount| diesel_models::TaxDetails { + default: Some(diesel_models::DefaultTax { + order_tax_amount: tax_amount, + }), + payment_method_type: None, + }); + Ok(storage::PaymentIntent { payment_id: payment_id.to_owned(), merchant_id: merchant_account.get_id().to_owned(), @@ -1482,7 +1491,7 @@ impl PaymentCreate { is_payment_processor_token_flow, organization_id: merchant_account.organization_id.clone(), shipping_cost: request.shipping_cost, - tax_details: None, + tax_details, skip_external_tax_calculation, psd2_sca_exemption_type: request.psd2_sca_exemption_type, }) diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 85bc51a09a7..528eb99e7df 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -259,6 +259,7 @@ pub async fn construct_payment_router_data_for_authorize<'a>( .net_amount .get_amount_as_i64(), minor_amount: payment_data.payment_attempt.amount_details.net_amount, + order_tax_amount: None, currency: payment_data.payment_intent.amount_details.currency, browser_info: None, email: None, @@ -2427,25 +2428,6 @@ pub fn mobile_payment_next_steps_check( Ok(mobile_payment_next_step) } -pub fn change_order_details_to_new_type( - order_amount: MinorUnit, - order_details: api_models::payments::OrderDetails, -) -> Option<Vec<api_models::payments::OrderDetailsWithAmount>> { - Some(vec![api_models::payments::OrderDetailsWithAmount { - product_name: order_details.product_name, - quantity: order_details.quantity, - amount: order_amount, - product_img_link: order_details.product_img_link, - requires_shipping: order_details.requires_shipping, - product_id: order_details.product_id, - category: order_details.category, - sub_category: order_details.sub_category, - brand: order_details.brand, - product_type: order_details.product_type, - product_tax_code: order_details.product_tax_code, - }]) -} - impl ForeignFrom<api_models::payments::QrCodeInformation> for api_models::payments::NextActionData { fn foreign_from(qr_info: api_models::payments::QrCodeInformation) -> Self { match qr_info { @@ -2625,6 +2607,10 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz statement_descriptor: payment_data.payment_intent.statement_descriptor_name, capture_method: payment_data.payment_attempt.capture_method, amount: amount.get_amount_as_i64(), + order_tax_amount: payment_data + .payment_attempt + .net_amount + .get_order_tax_amount(), minor_amount: amount, currency: payment_data.currency, browser_info, @@ -2961,7 +2947,6 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SdkPaymentsSessi #[cfg(feature = "v1")] impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SdkPaymentsSessionUpdateData { type Error = error_stack::Report<errors::ApiErrorResponse>; - fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { let payment_data = additional_data.payment_data; let order_tax_amount = payment_data diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 2ab43378516..de4c063c41a 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -873,6 +873,7 @@ impl ForeignFrom<&SetupMandateRouterData> for PaymentsAuthorizeData { email: data.request.email.clone(), customer_name: data.request.customer_name.clone(), amount: 0, + order_tax_amount: Some(MinorUnit::zero()), minor_amount: MinorUnit::new(0), statement_descriptor: None, capture_method: None, diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs index 3bd31873131..bd55bd96b96 100644 --- a/crates/router/src/types/api/verify_connector.rs +++ b/crates/router/src/types/api/verify_connector.rs @@ -29,6 +29,7 @@ impl VerifyConnectorData { amount: 1000, minor_amount: common_utils::types::MinorUnit::new(1000), confirm: true, + order_tax_amount: None, currency: storage_enums::Currency::USD, metadata: None, mandate_id: None, diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index d4cd5775436..1f55aa5801d 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1239,6 +1239,7 @@ impl ForeignFrom<storage::PaymentAttempt> for payments::PaymentAttemptResponse { attempt_id: payment_attempt.attempt_id, status: payment_attempt.status, amount: payment_attempt.net_amount.get_order_amount(), + order_tax_amount: payment_attempt.net_amount.get_order_tax_amount(), currency: payment_attempt.currency, connector: payment_attempt.connector, error_message: payment_attempt.error_reason, diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs index 1994acb6a65..15f980e242e 100644 --- a/crates/router/tests/connectors/payme.rs +++ b/crates/router/tests/connectors/payme.rs @@ -90,6 +90,8 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { brand: None, product_type: None, product_tax_code: None, + tax_rate: None, + total_tax_amount: None, }]), router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), @@ -391,6 +393,8 @@ async fn should_fail_payment_for_incorrect_cvc() { brand: None, product_type: None, product_tax_code: None, + tax_rate: None, + total_tax_amount: None, }]), router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), @@ -431,6 +435,8 @@ async fn should_fail_payment_for_invalid_exp_month() { brand: None, product_type: None, product_tax_code: None, + tax_rate: None, + total_tax_amount: None, }]), router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), @@ -471,6 +477,8 @@ async fn should_fail_payment_for_incorrect_expiry_year() { brand: None, product_type: None, product_tax_code: None, + tax_rate: None, + total_tax_amount: None, }]), router_return_url: Some("https://hyperswitch.io".to_string()), webhook_url: Some("https://hyperswitch.io".to_string()), diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index f195aeaf7c4..489b55a227b 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -939,6 +939,7 @@ impl Default for PaymentAuthorizeType { payment_method_data: types::domain::PaymentMethodData::Card(CCardType::default().0), amount: 100, minor_amount: MinorUnit::new(100), + order_tax_amount: Some(MinorUnit::zero()), currency: enums::Currency::USD, confirm: true, statement_descriptor_suffix: None, diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs index de60c5e8d86..a13fe48d255 100644 --- a/crates/router/tests/connectors/zen.rs +++ b/crates/router/tests/connectors/zen.rs @@ -334,6 +334,8 @@ async fn should_fail_payment_for_incorrect_card_number() { brand: None, product_type: None, product_tax_code: None, + tax_rate: None, + total_tax_amount: None, }]), email: Some(Email::from_str("[email protected]").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), @@ -377,6 +379,8 @@ async fn should_fail_payment_for_incorrect_cvc() { brand: None, product_type: None, product_tax_code: None, + tax_rate: None, + total_tax_amount: None, }]), email: Some(Email::from_str("[email protected]").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), @@ -420,6 +424,8 @@ async fn should_fail_payment_for_invalid_exp_month() { brand: None, product_type: None, product_tax_code: None, + tax_rate: None, + total_tax_amount: None, }]), email: Some(Email::from_str("[email protected]").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()), @@ -463,6 +469,8 @@ async fn should_fail_payment_for_incorrect_expiry_year() { brand: None, product_type: None, product_tax_code: None, + tax_rate: None, + total_tax_amount: None, }]), email: Some(Email::from_str("[email protected]").unwrap()), webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()),
feat
Klarna Kustom Checkout Integration (#6839)
e18ea7a7bab257a6082639e84da8d9e44f31168f
2024-07-24 16:59:58
Prajjwal Kumar
fix(euclid): remove business_profile routing feature flag (#5430)
false
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 5f5e59a89a5..fd8da0e24f3 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2362,7 +2362,6 @@ pub async fn list_payment_methods( let mut response: Vec<ResponsePaymentMethodIntermediate> = vec![]; // Key creation for storing PM_FILTER_CGRAPH - #[cfg(feature = "business_profile_routing")] let key = { let profile_id = profile_id .clone() @@ -2376,9 +2375,6 @@ pub async fn list_payment_methods( ) }; - #[cfg(not(feature = "business_profile_routing"))] - let key = { format!("pm_filters_cgraph_{}", &merchant_account.merchant_id) }; - if let Some(graph) = get_merchant_pm_filter_graph(&state, &key).await { // Derivation of PM_FILTER_CGRAPH from MokaCache successful for mca in &filtered_mcas {
fix
remove business_profile routing feature flag (#5430)
b2b9dc0b58d737ea114d078fe02271a10accaefa
2023-06-07 01:07:01
Ashok
fix(logging): fix traces export through opentelemetry (#1355)
false
diff --git a/Cargo.lock b/Cargo.lock index 50173a250e5..54d49ab4f39 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3327,8 +3327,9 @@ dependencies = [ [[package]] name = "opentelemetry" -version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f4b8347cc26099d3aeee044065ecc3ae11469796b4d65d065a23a584ed92a6f" dependencies = [ "opentelemetry_api", "opentelemetry_sdk", @@ -3336,8 +3337,9 @@ dependencies = [ [[package]] name = "opentelemetry-otlp" -version = "0.11.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8af72d59a4484654ea8eb183fea5ae4eb6a41d7ac3e3bae5f4d2a282a3a7d3ca" dependencies = [ "async-trait", "futures", @@ -3353,8 +3355,9 @@ dependencies = [ [[package]] name = "opentelemetry-proto" -version = "0.1.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "045f8eea8c0fa19f7d48e7bc3128a39c2e5c533d5c61298c548dfefc1064474c" dependencies = [ "futures", "futures-util", @@ -3365,23 +3368,25 @@ dependencies = [ [[package]] name = "opentelemetry_api" -version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed41783a5bf567688eb38372f2b7a8530f5a607a4b49d38dd7573236c23ca7e2" dependencies = [ "fnv", "futures-channel", "futures-util", "indexmap", - "js-sys", "once_cell", "pin-project-lite 0.2.9", "thiserror", + "urlencoding", ] [[package]] name = "opentelemetry_sdk" -version = "0.18.0" -source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b3a2a91fdbfdd4d212c0dcc2ab540de2c2bcbbd90be17de7a7daf8822d010c1" dependencies = [ "async-trait", "crossbeam-channel", @@ -5326,9 +5331,9 @@ dependencies = [ [[package]] name = "tracing-opentelemetry" -version = "0.18.0" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21ebb87a95ea13271332df069020513ab70bdb5637ca42d6e492dc3bbbad48de" +checksum = "00a39dcf9bfc1742fa4d6215253b33a6e474be78275884c216fc2a06267b3600" dependencies = [ "once_cell", "opentelemetry", diff --git a/Cargo.toml b/Cargo.toml index 1063e706bc7..cc7cc81548f 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -6,6 +6,3 @@ members = ["crates/*", "examples/*"] strip = true lto = true codegen-units = 1 - -[patch.crates-io] -opentelemetry = { git = "https://github.com/open-telemetry/opentelemetry-rust", rev = "44b90202fd744598db8b0ace5b8f0bad7ec45658" } diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 3efbdcd0217..23432aa2dd4 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -39,6 +39,7 @@ pool_size = 5 [secrets] admin_api_key = "test_admin" jwt_secret = "secret" +master_enc_key = "73ad7bbbbc640c845a150f67d058b279849370cd2c1f3c67c4dd6c869213e13a" [locker] host = "" diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.toml index a7bca49ea51..c023c1e7ea4 100644 --- a/crates/router_env/Cargo.toml +++ b/crates/router_env/Cargo.toml @@ -11,8 +11,8 @@ license = "Apache-2.0" config = { version = "0.13.3", features = ["toml"] } gethostname = "0.4.2" once_cell = "1.17.1" -opentelemetry = { git = "https://github.com/open-telemetry/opentelemetry-rust/", rev = "44b90202fd744598db8b0ace5b8f0bad7ec45658", features = ["rt-tokio-current-thread", "metrics"] } -opentelemetry-otlp = { git = "https://github.com/open-telemetry/opentelemetry-rust/", rev = "44b90202fd744598db8b0ace5b8f0bad7ec45658", features = ["metrics"] } +opentelemetry = { version = "0.19.0", features = ["rt-tokio-current-thread", "metrics"] } +opentelemetry-otlp = { version = "0.12.0", features = ["metrics"] } rustc-hash = "1.1" serde = { version = "1.0.160", features = ["derive"] } serde_json = "1.0.96" @@ -21,10 +21,10 @@ strum = { version = "0.24.1", features = ["derive"] } time = { version = "0.3.20", default-features = false, features = ["formatting"] } tokio = { version = "1.27.0" } tracing = { version = "=0.1.36" } -tracing-actix-web = { version = "0.7.4", features = ["opentelemetry_0_18"], optional = true } +tracing-actix-web = { version = "0.7.4", features = ["opentelemetry_0_19"], optional = true } tracing-appender = { version = "0.2.2" } tracing-attributes = "=0.1.22" -tracing-opentelemetry = { version = "0.18.0" } +tracing-opentelemetry = { version = "0.19.0" } tracing-subscriber = { version = "0.3.16", default-features = true, features = ["env-filter", "json", "registry"] } vergen = { version = "8.1.1", optional = true, features = ["cargo", "git", "git2", "rustc"] } diff --git a/crates/router_env/src/logger/setup.rs b/crates/router_env/src/logger/setup.rs index eb70e58da26..9bcb8736d8f 100644 --- a/crates/router_env/src/logger/setup.rs +++ b/crates/router_env/src/logger/setup.rs @@ -8,7 +8,9 @@ use opentelemetry::{ export::metrics::aggregation::cumulative_temporality_selector, metrics::{controllers::BasicController, selectors::simple}, propagation::TraceContextPropagator, - trace, Resource, + trace, + trace::BatchConfig, + Resource, }, KeyValue, }; @@ -145,11 +147,16 @@ fn setup_tracing_pipeline( if config.use_xray_generator { trace_config = trace_config.with_id_generator(trace::XrayIdGenerator::default()); } + + // Change the default export interval from 5 seconds to 1 second + let batch_config = BatchConfig::default().with_scheduled_delay(Duration::from_millis(1000)); + let traces_layer_result = opentelemetry_otlp::new_pipeline() .tracing() .with_exporter(get_opentelemetry_exporter(config)) + .with_batch_config(batch_config) .with_trace_config(trace_config) - .install_simple() + .install_batch(opentelemetry::runtime::TokioCurrentThread) .map(|tracer| tracing_opentelemetry::layer().with_tracer(tracer)); if config.ignore_errors { diff --git a/docker-compose.yml b/docker-compose.yml index bff24e4fee2..1d13d558536 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -84,7 +84,7 @@ services: - POSTGRES_DB=hyperswitch_db migration_runner: - image: rust:1.65 + image: rust:1.70 command: "bash -c 'cargo install diesel_cli --no-default-features --features \"postgres\" && diesel migration --database-url postgres://db_user:db_pass@pg:5432/hyperswitch_db run'" working_dir: /app networks: @@ -93,7 +93,7 @@ services: - ./:/app hyperswitch-server-init: - image: rust:1.65 + image: rust:1.70 command: cargo build --bin router working_dir: /app networks: @@ -105,7 +105,7 @@ services: environment: - CARGO_TARGET_DIR=/cargo_build_cache hyperswitch-server: - image: rust:1.65 + image: rust:1.70 command: /cargo_build_cache/debug/router -f ./config/docker_compose.toml working_dir: /app ports: @@ -132,7 +132,7 @@ services: condition: service_completed_successfully hyperswitch-producer: - image: rust:1.65 + image: rust:1.70 command: cargo run --bin scheduler -- -f ./config/docker_compose.toml working_dir: /app networks: @@ -153,7 +153,7 @@ services: logs: "promtail" hyperswitch-consumer: - image: rust:1.65 + image: rust:1.70 command: cargo run --bin scheduler -- -f ./config/docker_compose.toml working_dir: /app networks: @@ -270,7 +270,7 @@ services: - "4317" # otlp grpc restart: unless-stopped hyperswitch-drainer: - image: rust:1.65 + image: rust:1.70 command: cargo run --bin drainer -- -f ./config/docker_compose.toml working_dir: /app deploy:
fix
fix traces export through opentelemetry (#1355)
49cfe72cd2a20ba25c3323fca81bba7ea48b591b
2024-04-03 20:11:59
Chethan Rao
refactor(mandates): add validations for recurring mandates using payment_method_id (#4263)
false
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index e7a0ddd1ef1..dd6495bb979 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -282,6 +282,28 @@ fn saved_in_locker_default() -> bool { true } +impl From<CardDetailFromLocker> for payments::AdditionalCardInfo { + fn from(item: CardDetailFromLocker) -> Self { + Self { + card_issuer: item.card_issuer, + card_network: item.card_network, + card_type: item.card_type, + card_issuing_country: item.issuer_country, + bank_code: None, + last4: item.last4_digits, + card_isin: item.card_isin, + card_extended_bin: item + .card_number + .map(|card_number| card_number.get_card_extended_bin()), + card_exp_month: item.expiry_month, + card_exp_year: item.expiry_year, + card_holder_name: item.card_holder_name, + payment_checks: None, + authentication_data: None, + } + } +} + impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { fn from(item: CardDetailsPaymentMethod) -> Self { Self { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 4820db94841..51b95041898 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -469,6 +469,18 @@ pub async fn get_token_pm_type_mandate_details( errors::ApiErrorResponse::PaymentMethodNotFound, )?; + let customer_id = request + .customer_id + .clone() + .get_required_value("customer_id")?; + + verify_mandate_details_for_recurring_payments( + &payment_method_info.merchant_id, + &merchant_account.merchant_id, + &payment_method_info.customer_id, + &customer_id, + )?; + ( None, Some(payment_method_info.payment_method), @@ -869,6 +881,7 @@ pub fn validate_mandate( pub fn validate_recurring_details_and_token( recurring_details: &Option<RecurringDetails>, payment_token: &Option<String>, + mandate_id: &Option<String>, ) -> CustomResult<(), errors::ApiErrorResponse> { utils::when( recurring_details.is_some() && payment_token.is_some(), @@ -880,6 +893,12 @@ pub fn validate_recurring_details_and_token( }, )?; + utils::when(recurring_details.is_some() && mandate_id.is_some(), || { + Err(report!(errors::ApiErrorResponse::PreconditionFailed { + message: "Expected one out of recurring_details and mandate_id but got both".into() + })) + })?; + Ok(()) } @@ -1080,6 +1099,24 @@ pub fn verify_mandate_details( ) } +pub fn verify_mandate_details_for_recurring_payments( + mandate_merchant_id: &str, + merchant_id: &str, + mandate_customer_id: &str, + customer_id: &str, +) -> RouterResult<()> { + if mandate_merchant_id != merchant_id { + Err(report!(errors::ApiErrorResponse::MandateNotFound))? + } + if mandate_customer_id != customer_id { + Err(report!(errors::ApiErrorResponse::PreconditionFailed { + message: "customer_id must match mandate customer_id".into() + }))? + } + + Ok(()) +} + #[instrument(skip_all)] pub fn payment_attempt_status_fsm( payment_method_data: &Option<api::payments::PaymentMethodDataRequest>, diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 9d0971982a6..ccefb3b2b53 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -461,6 +461,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_recurring_details_and_token( &request.recurring_details, &request.payment_token, + &request.mandate_id, )?; Ok(( diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index eca8d2d90f6..4eac9c1f4de 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -1205,6 +1205,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_recurring_details_and_token( &request.recurring_details, &request.payment_token, + &request.mandate_id, )?; let payment_id = request diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index f66c28c555d..6ede6ad899a 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -1,15 +1,17 @@ use std::marker::PhantomData; -use api_models::{enums::FrmSuggestion, mandates::RecurringDetails}; +use api_models::{ + enums::FrmSuggestion, mandates::RecurringDetails, payment_methods::PaymentMethodsData, +}; use async_trait::async_trait; use common_utils::ext_traits::{AsyncExt, Encode, ValueExt}; use data_models::{ mandates::{MandateData, MandateDetails}, payments::payment_attempt::PaymentAttempt, }; -use diesel_models::ephemeral_key; +use diesel_models::{ephemeral_key, PaymentMethod}; use error_stack::{self, ResultExt}; -use masking::PeekInterface; +use masking::{ExposeInterface, PeekInterface}; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; use time::PrimitiveDateTime; @@ -259,6 +261,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> payment_method_billing_address .as_ref() .map(|address| address.address_id.clone()), + &payment_method_info, + merchant_key_store, ) .await?; @@ -691,6 +695,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_recurring_details_and_token( &request.recurring_details, &request.payment_token, + &request.mandate_id, )?; if request.confirm.unwrap_or(false) { @@ -744,6 +749,8 @@ impl PaymentCreate { browser_info: Option<serde_json::Value>, state: &AppState, payment_method_billing_address_id: Option<String>, + payment_method_info: &Option<PaymentMethod>, + key_store: &domain::MerchantKeyStore, ) -> RouterResult<( storage::PaymentAttemptNew, Option<api_models::payments::AdditionalPaymentData>, @@ -753,7 +760,7 @@ impl PaymentCreate { helpers::payment_attempt_status_fsm(&request.payment_method_data, request.confirm); let (amount, currency) = (money.0, Some(money.1)); - let additional_pm_data = request + let mut additional_pm_data = request .payment_method_data .as_ref() .async_map(|payment_method_data| async { @@ -764,6 +771,35 @@ impl PaymentCreate { .await }) .await; + + if additional_pm_data.is_none() { + // If recurring payment is made using payment_method_id, then fetch payment_method_data from retrieved payment_method object + additional_pm_data = payment_method_info + .as_ref() + .async_map(|pm_info| async { + domain::types::decrypt::<serde_json::Value, masking::WithType>( + pm_info.payment_method_data.clone(), + key_store.key.get_inner().peek(), + ) + .await + .change_context(errors::StorageError::DecryptionError) + .attach_printable("unable to decrypt card details") + .ok() + .flatten() + .map(|x| x.into_inner().expose()) + .and_then(|v| serde_json::from_value::<PaymentMethodsData>(v).ok()) + .and_then(|pmd| match pmd { + PaymentMethodsData::Card(crd) => Some(api::CardDetailFromLocker::from(crd)), + _ => None, + }) + }) + .await + .flatten() + .map(|card| { + api_models::payments::AdditionalPaymentData::Card(Box::new(card.into())) + }) + }; + let additional_pm_data_value = additional_pm_data .as_ref() .map(Encode::encode_to_value) @@ -842,7 +878,9 @@ impl PaymentCreate { connector: None, error_message: None, offer_amount: None, - payment_method_id: None, + payment_method_id: payment_method_info + .as_ref() + .map(|pm_info| pm_info.payment_method_id.clone()), cancellation_reason: None, error_code: None, connector_metadata: None, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index a6a41732f1b..76c28307dba 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -754,6 +754,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_recurring_details_and_token( &request.recurring_details, &request.payment_token, + &request.mandate_id, )?; Ok((
refactor
add validations for recurring mandates using payment_method_id (#4263)
6149d4fb607304ccdf184c8c5f28269a45ef3974
2024-03-18 15:09:22
Sahkal Poddar
refactor(router): Add FE error logs to loki (#4077)
false
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js index 9acfc8bfeca..3e262b45dfa 100644 --- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js +++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link.js @@ -188,7 +188,10 @@ var hyper = null; * - Initialize event listeners for updating UI on screen size changes * - Initialize SDK **/ + + function boot() { + // @ts-ignore var paymentDetails = window.__PAYMENT_DETAILS; var orderDetails = paymentDetails.order_details; diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 2cc3670ddd7..a4c6bdd0a16 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1449,7 +1449,8 @@ pub fn build_redirection_form( config: Settings, ) -> maud::Markup { use maud::PreEscaped; - + let logging_template = + include_str!("redirection/assets/redirect_error_logs_push.js").to_string(); match form { RedirectForm::Form { endpoint, @@ -1506,11 +1507,15 @@ pub fn build_redirection_form( } } - (PreEscaped(r#"<script type="text/javascript"> var frm = document.getElementById("payment_form"); window.setTimeout(function () { frm.submit(); }, 300); </script>"#)) + (PreEscaped(format!("<script type=\"text/javascript\"> {logging_template} var frm = document.getElementById(\"payment_form\"); window.setTimeout(function () {{ frm.submit(); }}, 300); </script>"))) + } } }, - RedirectForm::Html { html_data } => PreEscaped(html_data.to_string()), + RedirectForm::Html { html_data } => PreEscaped(format!( + "{} <script>{}</script>", + html_data, logging_template + )), RedirectForm::BlueSnap { payment_fields_token, } => { @@ -1557,6 +1562,7 @@ pub fn build_redirection_form( } (PreEscaped(format!("<script> + {logging_template} bluesnap.threeDsPaymentsSetup(\"{payment_fields_token}\", function(sdkResponse) {{ // console.log(sdkResponse); @@ -1621,6 +1627,7 @@ pub fn build_redirection_form( } </script>"#)) (PreEscaped(format!("<script> + {logging_template} window.addEventListener(\"message\", function(event) {{ if (event.origin === \"https://centinelapistag.cardinalcommerce.com\" || event.origin === \"https://centinelapi.cardinalcommerce.com\") {{ window.location.href = window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/cybersource?referenceId={reference_id}\"); @@ -1669,11 +1676,12 @@ pub fn build_redirection_form( (PreEscaped(format!("<form id=\"step-up-form\" method=\"POST\" action=\"{step_up_url}\"> <input type=\"hidden\" name=\"JWT\" value=\"{access_token}\"> </form>"))) - (PreEscaped(r#"<script> - window.onload = function() { + (PreEscaped(format!("<script> + {logging_template} + window.onload = function() {{ var stepUpForm = document.querySelector('#step-up-form'); if(stepUpForm) stepUpForm.submit(); - } - </script>"#)) + }} + </script>"))) }} } RedirectForm::Payme => { @@ -1682,7 +1690,8 @@ pub fn build_redirection_form( head { (PreEscaped(r#"<script src="https://cdn.paymeservice.com/hf/v1/hostedfields.js"></script>"#)) } - (PreEscaped("<script> + (PreEscaped(format!("<script> + {logging_template} var f = document.createElement('form'); f.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/payme\"); f.method='POST'; @@ -1700,7 +1709,7 @@ pub fn build_redirection_form( f.submit(); }}); </script> - ".to_string())) + "))) } } RedirectForm::Braintree { @@ -1741,6 +1750,7 @@ pub fn build_redirection_form( } (PreEscaped(format!("<script> + {logging_template} var my3DSContainer; var clientToken = \"{client_token}\"; braintree.threeDSecure.create({{ @@ -1838,6 +1848,7 @@ pub fn build_redirection_form( div id="threeds-wrapper" style="display: flex; width: 100%; height: 100vh; align-items: center; justify-content: center;" {""} } (PreEscaped(format!("<script> + {logging_template} const gateway = Gateway.create('{public_key_val}'); // Initialize the ThreeDSService @@ -1964,6 +1975,7 @@ pub fn build_payment_link_html( // Add modification to js template with dynamic data let js_template = include_str!("../core/payment_link/payment_link_initiate/payment_link.js").to_string(); + let _ = tera.add_raw_template("payment_link_js", &js_template); context.insert("payment_details_js_script", &payment_link_data.js_script); diff --git a/crates/router/src/services/redirection/assets/redirect_error_logs_push.js b/crates/router/src/services/redirection/assets/redirect_error_logs_push.js new file mode 100644 index 00000000000..ee59bf77266 --- /dev/null +++ b/crates/router/src/services/redirection/assets/redirect_error_logs_push.js @@ -0,0 +1,81 @@ +function parseRoute(url) { + const route = new URL(url).pathname; + const regex = /^\/payments\/redirect\/([^/]+)\/([^/]+)\/([^/]+)$|^\/payments\/([^/]+)\/([^/]+)\/redirect\/response\/([^/]+)(?:\/([^/]+)\/?)?$|^\/payments\/([^/]+)\/([^/]+)\/redirect\/complete\/([^/]+)$/; + const matches = route.match(regex); + const attemptIdExists = !( + route.includes("response") || route.includes("complete") + ); + if (matches) { + const [, paymentId, merchantId, attemptId, connector,credsIdentifier] = + matches; + return { + paymentId, + merchantId, + attemptId: attemptIdExists ? attemptId : "", + connector + }; + } else { + return { + paymentId: "", + merchantId: "", + attemptId: "", + connector: "", + }; + } + } + + function getEnvRoute(url) { + const route = new URL(url).hostname; + return route === "api.hyperswitch.io" ? "https://api.hyperswitch.io/logs/redirection" : "https://sandbox.hyperswitch.io/logs/redirection"; +} + + +async function postLog(log, urlToPost) { + + try { + const response = await fetch(urlToPost, { + method: "POST", + mode: "no-cors", + body: JSON.stringify(log), + headers: { + Accept: "application/json", + "Content-Type": "application/json", + }, + }); + } catch (err) { + console.error(`Error in logging: ${err}`); +} +} + + +window.addEventListener("error", (event) => { + let url = window.location.href; + let { paymentId, merchantId, attemptId, connector } = parseRoute(url); + let urlToPost = getEnvRoute(url); + let log = { + message: event.message, + url, + paymentId, + merchantId, + attemptId, + connector, + }; + postLog(log, urlToPost); +}); + +window.addEventListener("message", (event) => { + let url = window.location.href; + let { paymentId, merchantId, attemptId, connector } = parseRoute(url); + let urlToPost = getEnvRoute(url); + let log = { + message: event.data, + url, + paymentId, + merchantId, + attemptId, + connector, + }; + postLog(log, urlToPost); +}); + + \ No newline at end of file
refactor
Add FE error logs to loki (#4077)
e4b3cc790580f04012dba3d926e170dce4cec5d1
2023-09-21 12:42:06
Sangamesh Kulkarni
fix(connector): [Trustpay] Add missing error code (#2212)
false
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index d9148337916..515f7cc92f5 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -437,6 +437,7 @@ fn is_payment_failed(payment_status: &str) -> (bool, &'static str) { "800.100.190" => (true, "Transaction declined (invalid configuration data)"), "800.100.202" => (true, "Account Closed"), "800.120.100" => (true, "Rejected by throttling"), + "800.300.102" => (true, "Country blacklisted"), "800.300.401" => (true, "Bin blacklisted"), "800.700.100" => ( true,
fix
[Trustpay] Add missing error code (#2212)
6123823523847e709d9075c63a0a80a0c02216b7
2022-12-24 15:09:49
Sahebjot singh
feat(connector): Cybersource Authorize (#154)
false
diff --git a/config/Development.toml b/config/Development.toml index bc2b912fa37..f14f2300065 100644 --- a/config/Development.toml +++ b/config/Development.toml @@ -38,7 +38,7 @@ locker_decryption_key2 = "" [connectors.supported] wallets = ["klarna","braintree","applepay"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree","aci","shift4"] +cards = ["stripe","adyen","authorizedotnet","checkout","braintree","aci","shift4","cybersource"] [eph_key] validity = 1 @@ -67,6 +67,9 @@ base_url = "https://api-na.playground.klarna.com/" [connectors.applepay] base_url = "https://apple-pay-gateway.apple.com/" +[connectors.cybersource] +base_url = "https://apitest.cybersource.com/" + [connectors.shift4] base_url = "https://api.shift4.com/" diff --git a/config/config.example.toml b/config/config.example.toml index 6e9f4d152c0..196155c8182 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -119,14 +119,16 @@ base_url = "https://api-na.playground.klarna.com/" [connectors.applepay] base_url = "https://apple-pay-gateway.apple.com/" +[connectors.cybersource] +base_url = "https://apitest.cybersource.com/" + [connectors.shift4] base_url = "https://api.shift4.com/" # This data is used to call respective connectors for wallets and cards [connectors.supported] wallets = ["klarna","braintree","applepay"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree"] - +cards = ["stripe","adyen","authorizedotnet","checkout","braintree", "cybersource"] # Scheduler settings provides a point to modify the behaviour of scheduler flow. # It defines the the streams/queues name and configuration as well as event selection variables diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 58a22c7c5c6..265aefe903b 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -74,9 +74,12 @@ base_url = "https://api-na.playground.klarna.com/" [connectors.applepay] base_url = "https://apple-pay-gateway.apple.com/" +[connectors.cybersource] +base_url = "https://apitest.cybersource.com/" + [connectors.shift4] base_url = "https://api.shift4.com/" [connectors.supported] wallets = ["klarna","braintree","applepay"] -cards = ["stripe","adyen","authorizedotnet","checkout","braintree","shift4"] +cards = ["stripe","adyen","authorizedotnet","checkout","braintree","shift4","cybersource"] diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index e37de90ba7e..48c5a32a9d2 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -491,6 +491,7 @@ pub enum Connector { Authorizedotnet, Braintree, Checkout, + Cybersource, #[default] Dummy, Klarna, diff --git a/crates/router/src/configs/defaults.toml b/crates/router/src/configs/defaults.toml index c6680ebaacf..5ccfaefe39b 100644 --- a/crates/router/src/configs/defaults.toml +++ b/crates/router/src/configs/defaults.toml @@ -57,5 +57,5 @@ num_partitions = 64 max_read_count = 100 [connectors.supported] -wallets = ["klarna", "braintree"] -cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree"] +wallets = ["klarna","braintree"] +cards = ["stripe","adyen","authorizedotnet","checkout","braintree", "cybersource"] diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index e0cc902531b..f5e8e744318 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -113,6 +113,7 @@ pub struct Connectors { pub braintree: ConnectorParams, pub checkout: ConnectorParams, pub klarna: ConnectorParams, + pub cybersource: ConnectorParams, pub shift4: ConnectorParams, pub stripe: ConnectorParams, pub supported: SupportedConnectors, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index 9476a026693..9b598df8f34 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -4,6 +4,7 @@ pub mod applepay; pub mod authorizedotnet; pub mod braintree; pub mod checkout; +pub mod cybersource; pub mod klarna; pub mod stripe; @@ -11,5 +12,6 @@ pub mod shift4; pub use self::{ aci::Aci, adyen::Adyen, applepay::Applepay, authorizedotnet::Authorizedotnet, - braintree::Braintree, checkout::Checkout, klarna::Klarna, shift4::Shift4, stripe::Stripe, + braintree::Braintree, checkout::Checkout, cybersource::Cybersource, klarna::Klarna, + shift4::Shift4, stripe::Stripe, }; diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs new file mode 100644 index 00000000000..6bdb1f22a6d --- /dev/null +++ b/crates/router/src/connector/cybersource.rs @@ -0,0 +1,303 @@ +mod transformers; + +use std::fmt::Debug; + +use base64; +use bytes::Bytes; +use error_stack::{IntoReport, ResultExt}; +use ring::{digest, hmac}; +use time::OffsetDateTime; +use transformers as cybersource; +use url::Url; + +use crate::{ + configs::settings, + consts, + core::errors::{self, CustomResult}, + headers, logger, services, + types::{self, api}, + utils::{self, BytesExt}, +}; + +#[derive(Debug, Clone)] +pub struct Cybersource; + +impl Cybersource { + pub fn generate_digest(&self, payload: &[u8]) -> String { + let payload_digest = digest::digest(&digest::SHA256, payload); + base64::encode(payload_digest) + } + + pub fn generate_signature( + &self, + auth: cybersource::CybersourceAuthType, + host: String, + resource: &str, + payload: &str, + date: OffsetDateTime, + ) -> CustomResult<String, errors::ConnectorError> { + let cybersource::CybersourceAuthType { + api_key, + merchant_account, + api_secret, + } = auth; + + let headers_for_post_method = "host date (request-target) digest v-c-merchant-id"; + let signature_string = format!( + "host: {host}\n\ + date: {date}\n\ + (request-target): post {resource}\n\ + digest: SHA-256={}\n\ + v-c-merchant-id: {merchant_account}", + self.generate_digest(payload.as_bytes()) + ); + let key_value = base64::decode(api_secret) + .into_report() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value); + let signature_value = + base64::encode(hmac::sign(&key, signature_string.as_bytes()).as_ref()); + let signature_header = format!( + r#"keyid="{api_key}", algorithm="HmacSHA256", headers="{headers_for_post_method}", signature="{signature_value}""# + ); + + Ok(signature_header) + } +} + +impl api::ConnectorCommon for Cybersource { + fn id(&self) -> &'static str { + "cybersource" + } + + fn common_get_content_type(&self) -> &'static str { + "application/json" + } + + fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { + connectors.cybersource.base_url.as_ref() + } +} + +impl api::Payment for Cybersource {} +impl api::PaymentAuthorize for Cybersource {} +impl api::PaymentSync for Cybersource {} +impl api::PaymentVoid for Cybersource {} +impl api::PaymentCapture for Cybersource {} +impl api::PreVerify for Cybersource {} + +impl + services::ConnectorIntegration< + api::Verify, + types::VerifyRequestData, + types::PaymentsResponseData, + > for Cybersource +{ +} + +impl api::PaymentSession for Cybersource {} + +impl + services::ConnectorIntegration< + api::Session, + types::PaymentsSessionData, + types::PaymentsResponseData, + > for Cybersource +{ +} + +impl + services::ConnectorIntegration< + api::Capture, + types::PaymentsCaptureData, + types::PaymentsResponseData, + > for Cybersource +{ +} + +impl + services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> + for Cybersource +{ +} + +impl + services::ConnectorIntegration< + api::Authorize, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + > for Cybersource +{ + fn get_headers( + &self, + _req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { + let headers = vec![ + ( + headers::CONTENT_TYPE.to_string(), + types::PaymentsAuthorizeType::get_content_type(self).to_string(), + ), + ( + headers::ACCEPT.to_string(), + "application/hal+json;charset=utf-8".to_string(), + ), + ]; + Ok(headers) + } + + fn get_content_type(&self) -> &'static str { + "application/json;charset=utf-8" + } + + fn get_url( + &self, + _req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!( + "{}pts/v2/payments/", + api::ConnectorCommon::base_url(self, connectors) + )) + } + + fn build_request( + &self, + req: &types::PaymentsAuthorizeRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + let date = OffsetDateTime::now_utc(); + + let cybersource_req = + utils::Encode::<cybersource::CybersourcePaymentsRequest>::convert_and_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let auth: cybersource::CybersourceAuthType = + cybersource::CybersourceAuthType::try_from(&req.connector_auth_type)?; + let merchant_account = auth.merchant_account.clone(); + + let cybersource_host = Url::parse(connectors.cybersource.base_url.as_str()) + .into_report() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + match cybersource_host.host_str() { + Some(host) => { + let signature = self.generate_signature( + auth, + host.to_string(), + "/pts/v2/payments/", + &cybersource_req, + date, + )?; + let headers = vec![ + ( + "Digest".to_string(), + format!( + "SHA-256={}", + self.generate_digest(cybersource_req.as_bytes()) + ), + ), + ("v-c-merchant-id".to_string(), merchant_account), + ("Date".to_string(), date.to_string()), + ("Host".to_string(), host.to_string()), + ("Signature".to_string(), signature), + ]; + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(headers) + .headers(types::PaymentsAuthorizeType::get_headers(self, req)?) + .body(Some(cybersource_req)) + .build(); + + Ok(Some(request)) + } + None => Err(errors::ConnectorError::RequestEncodingFailed.into()), + } + } + + fn handle_response( + &self, + data: &types::PaymentsAuthorizeRouterData, + res: types::Response, + ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { + let response: cybersource::CybersourcePaymentsResponse = res + .response + .parse_struct("Cybersource PaymentResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + logger::debug!(cybersourcepayments_create_response=?response); + types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + } + .try_into() + .change_context(errors::ConnectorError::ResponseHandlingFailed) + } + + fn get_error_response( + &self, + res: Bytes, + ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { + let response: cybersource::ErrorResponse = res + .parse_struct("Cybersource ErrorResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + Ok(types::ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message: response + .message + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: None, + }) + } +} + +impl + services::ConnectorIntegration< + api::Void, + types::PaymentsCancelData, + types::PaymentsResponseData, + > for Cybersource +{ +} + +impl api::Refund for Cybersource {} +impl api::RefundExecute for Cybersource {} +impl api::RefundSync for Cybersource {} + +#[allow(dead_code)] +impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> + for Cybersource +{ +} + +#[allow(dead_code)] +impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> + for Cybersource +{ +} + +#[async_trait::async_trait] +impl api::IncomingWebhook for Cybersource { + fn get_webhook_object_reference_id( + &self, + _body: &[u8], + ) -> CustomResult<String, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("cybersource".to_string()).into()) + } + + fn get_webhook_event_type( + &self, + _body: &[u8], + ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("cybersource".to_string()).into()) + } + + fn get_webhook_resource_object( + &self, + _body: &[u8], + ) -> CustomResult<serde_json::Value, errors::ConnectorError> { + Err(errors::ConnectorError::NotImplemented("cybersource".to_string()).into()) + } +} + +impl services::ConnectorRedirectResponse for Cybersource {} diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs new file mode 100644 index 00000000000..7e1565e521b --- /dev/null +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -0,0 +1,316 @@ +use api_models::payments; +use common_utils::pii; +use masking::Secret; +use serde::{Deserialize, Serialize}; + +use crate::{ + core::errors, + pii::PeekInterface, + types::{self, api, storage::enums}, +}; + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct CybersourcePaymentsRequest { + processing_information: ProcessingInformation, + payment_information: PaymentInformation, + order_information: OrderInformationWithBill, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct ProcessingInformation { + capture: bool, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct PaymentInformation { + card: Card, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Card { + number: String, + expiration_month: String, + expiration_year: String, + security_code: String, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct OrderInformationWithBill { + amount_details: Amount, + bill_to: BillTo, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct OrderInformation { + amount_details: Amount, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct Amount { + total_amount: String, + currency: String, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +#[serde(rename_all = "camelCase")] +pub struct BillTo { + first_name: Secret<String>, + last_name: Secret<String>, + address1: Secret<String>, + locality: String, + administrative_area: Secret<String>, + postal_code: Secret<String>, + country: String, + email: Secret<String, pii::Email>, + phone_number: Secret<String>, +} + +// for cybersource each item in Billing is mandatory +fn build_bill_to( + address_details: payments::Address, + email: Secret<String, pii::Email>, + phone_number: Secret<String>, +) -> Option<BillTo> { + if let Some(api_models::payments::AddressDetails { + first_name: Some(f_name), + last_name: Some(last_name), + line1: Some(address1), + city: Some(city), + line2: Some(administrative_area), + zip: Some(postal_code), + country: Some(country), + .. + }) = address_details.address + { + Some(BillTo { + first_name: f_name, + last_name, + address1, + locality: city, + administrative_area, + postal_code, + country, + email, + phone_number, + }) + } else { + None + } +} + +impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> { + match item.request.payment_method_data { + api::PaymentMethod::Card(ref ccard) => { + let address = item + .address + .billing + .clone() + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let phone = address + .clone() + .phone + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let phone_number = phone + .number + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let country_code = phone + .country_code + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let number_with_code = + Secret::new(format!("{}{}", country_code, phone_number.peek())); + let email = item + .request + .email + .clone() + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let bill_to = build_bill_to(address, email, number_with_code) + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + + let order_information = OrderInformationWithBill { + amount_details: Amount { + total_amount: item.request.amount.to_string(), + currency: item.request.currency.to_string().to_uppercase(), + }, + bill_to, + }; + + let payment_information = PaymentInformation { + card: Card { + number: ccard.card_number.peek().clone(), + expiration_month: ccard.card_exp_month.peek().clone(), + expiration_year: ccard.card_exp_year.peek().clone(), + security_code: ccard.card_cvc.peek().clone(), + }, + }; + + let processing_information = ProcessingInformation { + capture: matches!( + item.request.capture_method, + Some(enums::CaptureMethod::Automatic) | None + ), + }; + + Ok(Self { + processing_information, + payment_information, + order_information, + }) + } + _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + } + } +} + +pub struct CybersourceAuthType { + pub(super) api_key: String, + pub(super) merchant_account: String, + pub(super) api_secret: String, +} + +impl TryFrom<&types::ConnectorAuthType> for CybersourceAuthType { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { + if let types::ConnectorAuthType::SignatureKey { + api_key, + key1, + api_secret, + } = auth_type + { + Ok(Self { + api_key: api_key.to_string(), + merchant_account: key1.to_string(), + api_secret: api_secret.to_string(), + }) + } else { + Err(errors::ConnectorError::FailedToObtainAuthType)? + } + } +} +#[derive(Debug, Default, Clone, Deserialize, Eq, PartialEq)] +#[serde(rename_all = "UPPERCASE")] +pub enum CybersourcePaymentStatus { + Authorized, + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<CybersourcePaymentStatus> for enums::AttemptStatus { + fn from(item: CybersourcePaymentStatus) -> Self { + match item { + CybersourcePaymentStatus::Authorized => Self::Authorized, + CybersourcePaymentStatus::Succeeded => Self::Charged, + CybersourcePaymentStatus::Failed => Self::Failure, + CybersourcePaymentStatus::Processing => Self::Authorizing, + } + } +} + +#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)] +pub struct CybersourcePaymentsResponse { + id: String, + status: CybersourcePaymentStatus, +} + +impl TryFrom<types::PaymentsResponseRouterData<CybersourcePaymentsResponse>> + for types::PaymentsAuthorizeRouterData +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::PaymentsResponseRouterData<CybersourcePaymentsResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: item.response.status.into(), + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: None, + redirect: false, + mandate_reference: None, + }), + ..item.data + }) + } +} + +#[derive(Debug, Default, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ErrorResponse { + pub error_information: Option<ErrorInformation>, + pub status: String, + pub message: Option<String>, +} + +#[derive(Debug, Default, Deserialize)] +pub struct ErrorInformation { + pub message: String, + pub reason: String, +} + +#[derive(Default, Debug, Serialize)] +pub struct CybersourceRefundRequest { + order_information: OrderInformation, +} + +impl<F> TryFrom<&types::RefundsRouterData<F>> for CybersourceRefundRequest { + type Error = error_stack::Report<errors::ParsingError>; + fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { + Ok(Self { + order_information: OrderInformation { + amount_details: Amount { + total_amount: item.request.amount.to_string(), + currency: item.request.currency.to_string(), + }, + }, + }) + } +} + +#[allow(dead_code)] +#[derive(Debug, Default, Deserialize, Clone)] +pub enum RefundStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<RefundStatus> for enums::RefundStatus { + fn from(item: RefundStatus) -> Self { + match item { + self::RefundStatus::Succeeded => Self::Success, + self::RefundStatus::Failed => Self::Failure, + self::RefundStatus::Processing => Self::Pending, + } + } +} + +#[derive(Default, Debug, Clone, Deserialize)] +pub struct CybersourceRefundResponse { + pub id: String, + pub status: RefundStatus, +} + +impl TryFrom<types::RefundsResponseRouterData<api::RSync, CybersourceRefundResponse>> + for types::RefundsRouterData<api::RSync> +{ + type Error = error_stack::Report<errors::ParsingError>; + fn try_from( + item: types::RefundsResponseRouterData<api::RSync, CybersourceRefundResponse>, + ) -> Result<Self, Self::Error> { + Ok(Self { + response: Ok(types::RefundsResponseData { + connector_refund_id: item.response.id, + refund_status: enums::RefundStatus::from(item.response.status), + }), + ..item.data + }) + } +} diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index b10478a1adc..8ca9322c75e 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -469,6 +469,7 @@ where pub refunds: Vec<storage::Refund>, pub sessions_token: Vec<api::SessionToken>, pub card_cvc: Option<pii::Secret<String>>, + pub email: Option<masking::Secret<String, pii::Email>>, } #[derive(Debug)] diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 5647f3dc5d6..6377231744f 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -113,6 +113,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest> payment_attempt, currency, amount, + email: None, mandate_id: None, setup_mandate: None, token: None, diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index 81620fb9e77..356ff837ea3 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -125,6 +125,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu currency, force_sync: None, amount, + email: None, mandate_id: None, setup_mandate: None, token: None, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 93cd443a71c..e92bd7cafe0 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -142,6 +142,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa currency, connector_response, amount, + email: request.email.clone(), mandate_id: None, setup_mandate, token, diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 33f1df2a88d..357416fe2b2 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -214,6 +214,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa payment_attempt, currency, amount, + email: request.email.clone(), mandate_id, setup_mandate, token, diff --git a/crates/router/src/core/payments/operations/payment_method_validate.rs b/crates/router/src/core/payments/operations/payment_method_validate.rs index bc3aa5e89b8..5e9b510ca31 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -136,6 +136,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym /// currency and amount are irrelevant in this scenario currency: storage_enums::Currency::default(), amount: api::Amount::Zero, + email: None, mandate_id: None, setup_mandate: request.mandate_data.clone(), token: request.payment_token.clone(), diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 185889feaa0..9f940cf3963 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -13,6 +13,7 @@ use crate::{ payments::{self, helpers, operations, PaymentData}, }, db::StorageInterface, + pii, pii::Secret, routes::AppState, types::{ @@ -131,6 +132,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> payment_attempt, currency, amount, + email: None::<Secret<String, pii::Email>>, mandate_id: None, token: None, setup_mandate: None, diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index cf847caae47..8f086e6695b 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -12,6 +12,7 @@ use crate::{ payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, }, db::StorageInterface, + pii, pii::Secret, routes::AppState, types::{ @@ -128,6 +129,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f payment_intent, currency, amount, + email: None::<Secret<String, pii::Email>>, mandate_id: None, connector_response, setup_mandate: None, diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 693a1f4ed8f..4cf76066045 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -275,6 +275,7 @@ async fn get_tracker_for_sync< connector_response, currency, amount, + email: None, mandate_id: None, setup_mandate: None, token: None, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index a9d1560b81d..e9347e1aaeb 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -164,6 +164,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa payment_attempt, currency, amount, + email: request.email.clone(), mandate_id, token, setup_mandate, diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 7e963424505..36df6cdbc32 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -433,6 +433,7 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsAuthorizeData { amount: payment_data.amount.into(), currency: payment_data.currency, browser_info, + email: payment_data.email, order_details, }) } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 088e009038c..7ab6221cf39 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -13,6 +13,7 @@ pub mod transformers; use std::marker::PhantomData; pub use api_models::enums::Connector; +use common_utils::pii::Email; use error_stack::{IntoReport, ResultExt}; use self::{api::payments, storage::enums as storage_enums}; @@ -90,6 +91,7 @@ pub struct RouterData<Flow, Request, Response> { pub struct PaymentsAuthorizeData { pub payment_method_data: payments::PaymentMethod, pub amount: i64, + pub email: Option<masking::Secret<String, Email>>, pub currency: storage_enums::Currency, pub confirm: bool, pub statement_descriptor_suffix: Option<String>, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index ff73559ad9f..e34849fabe6 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -146,6 +146,7 @@ impl ConnectorData { "braintree" => Ok(Box::new(&connector::Braintree)), "klarna" => Ok(Box::new(&connector::Klarna)), "applepay" => Ok(Box::new(&connector::Applepay)), + "cybersource" => Ok(Box::new(&connector::Cybersource)), "shift4" => Ok(Box::new(&connector::Shift4)), _ => Err(report!(errors::UnexpectedError) .attach_printable(format!("invalid connector name: {connector_name}"))) diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 630107deabe..3d417b15d5b 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -48,6 +48,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { capture_method: None, browser_info: None, order_details: None, + email: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs index 6b9fe6b67cc..45b8b18e3d9 100644 --- a/crates/router/tests/connectors/authorizedotnet.rs +++ b/crates/router/tests/connectors/authorizedotnet.rs @@ -48,6 +48,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { capture_method: None, browser_info: None, order_details: None, + email: None, }, payment_method_id: None, response: Err(types::ErrorResponse::default()), diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs index cefd2e1d8a8..578a7fab93e 100644 --- a/crates/router/tests/connectors/checkout.rs +++ b/crates/router/tests/connectors/checkout.rs @@ -45,6 +45,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { capture_method: None, browser_info: None, order_details: None, + email: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 51fdfc87109..8997da2b5ad 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -134,6 +134,7 @@ impl Default for PaymentAuthorizeType { setup_mandate_details: None, browser_info: None, order_details: None, + email: None, }; Self(data) }
feat
Cybersource Authorize (#154)
9ea9e5523b480d862d94cf22b92eb8533f0b8175
2023-06-28 19:25:31
Swangi Kumari
test(connector): [Mollie] Add tests for PayPal, Sofort, Ideal, Giropay and EPS (#1246)
false
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index bce32484151..473a0f6d715 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -28,6 +28,7 @@ mod forte; mod globalpay; mod iatapay; mod mollie; +mod mollie_ui; mod multisafepay; mod nexinets; mod nmi; diff --git a/crates/router/tests/connectors/mollie_ui.rs b/crates/router/tests/connectors/mollie_ui.rs new file mode 100644 index 00000000000..61ec5a7acc7 --- /dev/null +++ b/crates/router/tests/connectors/mollie_ui.rs @@ -0,0 +1,161 @@ +use serial_test::serial; +use thirtyfour::{prelude::*, WebDriver}; + +use crate::{selenium::*, tester}; + +struct MollieSeleniumTest; + +impl SeleniumTest for MollieSeleniumTest { + fn get_connector_name(&self) -> String { + "mollie".to_string() + } +} + +async fn should_make_mollie_paypal_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = MollieSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/32"))), + 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_sofort_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = MollieSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/29"))), + 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_ideal_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn: MollieSeleniumTest = MollieSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/36"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Assert(Assert::IsPresent("Test profile")), + Event::Trigger(Trigger::Click(By::ClassName( + "payment-method-list--bordered", + ))), + 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_eps_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = MollieSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/38"))), + 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_giropay_payment(c: WebDriver) -> Result<(), WebDriverError> { + let conn = MollieSeleniumTest {}; + conn.make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/41"))), + 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() { + tester!(should_make_mollie_paypal_payment); +} + +#[test] +#[serial] +fn should_make_mollie_sofort_payment_test() { + tester!(should_make_mollie_sofort_payment); +} + +#[test] +#[serial] +fn should_make_mollie_ideal_payment_test() { + tester!(should_make_mollie_ideal_payment); +} + +#[test] +#[serial] +fn should_make_mollie_eps_payment_test() { + tester!(should_make_mollie_eps_payment); +} + +#[test] +#[serial] +fn should_make_mollie_giropay_payment_test() { + tester!(should_make_mollie_giropay_payment); +}
test
[Mollie] Add tests for PayPal, Sofort, Ideal, Giropay and EPS (#1246)
2d394f98e96d0beafca24abe2ac9f10a05460993
2024-04-05 13:05:21
Rachit Naithani
feat(users): Implemented cookie parsing for auth (#4298)
false
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs index 0181ec4e799..a7c54ef8f34 100644 --- a/crates/router/src/compatibility/stripe/errors.rs +++ b/crates/router/src/compatibility/stripe/errors.rs @@ -427,6 +427,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode { | errors::ApiErrorResponse::InvalidJwtToken | errors::ApiErrorResponse::GenericUnauthorized { .. } | errors::ApiErrorResponse::AccessForbidden { .. } + | errors::ApiErrorResponse::InvalidCookie | errors::ApiErrorResponse::InvalidEphemeralKey => Self::Unauthorized, errors::ApiErrorResponse::InvalidRequestUrl | errors::ApiErrorResponse::InvalidHttpMethod diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs index b3fbbaaf141..dc3e19cb725 100644 --- a/crates/router/src/core/errors/api_error_response.rs +++ b/crates/router/src/core/errors/api_error_response.rs @@ -260,6 +260,11 @@ pub enum ApiErrorResponse { CurrencyConversionFailed, #[error(error_type = ErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")] PaymentMethodDeleteFailed, + #[error( + error_type = ErrorType::InvalidRequestError, code = "IR_26", + message = "Invalid Cookie" + )] + InvalidCookie, } impl PTError for ApiErrorResponse { diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs index 110feb22df3..7c06fc92c99 100644 --- a/crates/router/src/core/errors/transformers.rs +++ b/crates/router/src/core/errors/transformers.rs @@ -292,6 +292,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon Self::PaymentMethodDeleteFailed => { AER::BadRequest(ApiError::new("IR", 25, "Cannot delete the default payment method", None)) } + Self::InvalidCookie => { + AER::BadRequest(ApiError::new("IR", 26, "Invalid Cookie", None)) + } } } } diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index d2247150d3c..f7acbe6f933 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -5,6 +5,7 @@ use common_utils::date_time; use error_stack::{report, ResultExt}; use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation}; use masking::PeekInterface; +use router_env::logger; use serde::Serialize; use self::blacklist::BlackList; @@ -33,7 +34,6 @@ use crate::{ utils::OptionExt, }; pub mod blacklist; -#[cfg(feature = "olap")] pub mod cookies; #[derive(Clone, Debug)] @@ -598,6 +598,15 @@ where A: AppStateInfo + Sync, { let token = get_jwt_from_authorization_header(headers)?; + if let Some(token_from_cookies) = get_cookie_from_header(headers) + .ok() + .and_then(|cookies| cookies::parse_cookie(cookies).ok()) + { + logger::info!( + "Cookie header and authorization header JWT comparison result: {}", + token == token_from_cookies + ); + } let payload = decode_jwt(token, state).await?; Ok(payload) @@ -959,6 +968,13 @@ pub fn get_jwt_from_authorization_header(headers: &HeaderMap) -> RouterResult<&s .ok_or(errors::ApiErrorResponse::InvalidJwtToken.into()) } +pub fn get_cookie_from_header(headers: &HeaderMap) -> RouterResult<&str> { + headers + .get(cookies::get_cookie_header()) + .and_then(|header_value| header_value.to_str().ok()) + .ok_or(errors::ApiErrorResponse::InvalidCookie.into()) +} + pub fn strip_jwt_token(token: &str) -> RouterResult<&str> { token .strip_prefix("Bearer ") diff --git a/crates/router/src/services/authentication/cookies.rs b/crates/router/src/services/authentication/cookies.rs index d7fc4c10315..96518840800 100644 --- a/crates/router/src/services/authentication/cookies.rs +++ b/crates/router/src/services/authentication/cookies.rs @@ -1,15 +1,27 @@ +use cookie::Cookie; +#[cfg(feature = "olap")] use cookie::{ time::{Duration, OffsetDateTime}, - Cookie, SameSite, + SameSite, }; -use masking::{ExposeInterface, Mask, Secret}; +use error_stack::{report, ResultExt}; +#[cfg(feature = "olap")] +use masking::Mask; +#[cfg(feature = "olap")] +use masking::{ExposeInterface, Secret}; use crate::{ - consts::{JWT_TOKEN_COOKIE_NAME, JWT_TOKEN_TIME_IN_SECS}, + consts::JWT_TOKEN_COOKIE_NAME, + core::errors::{ApiErrorResponse, RouterResult}, +}; +#[cfg(feature = "olap")] +use crate::{ + consts::JWT_TOKEN_TIME_IN_SECS, core::errors::{UserErrors, UserResponse}, services::ApplicationResponse, }; +#[cfg(feature = "olap")] pub fn set_cookie_response<R>(response: R, token: Secret<String>) -> UserResponse<R> { let jwt_expiry_in_seconds = JWT_TOKEN_TIME_IN_SECS .try_into() @@ -19,16 +31,17 @@ pub fn set_cookie_response<R>(response: R, token: Secret<String>) -> UserRespons let header_value = create_cookie(token, expiry, max_age) .to_string() .into_masked(); - let header_key = get_cookie_header(); + let header_key = get_set_cookie_header(); let header = vec![(header_key, header_value)]; Ok(ApplicationResponse::JsonWithHeaders((response, header))) } +#[cfg(feature = "olap")] pub fn remove_cookie_response() -> UserResponse<()> { let (expiry, max_age) = get_expiry_and_max_age_from_seconds(0); - let header_key = get_cookie_header(); + let header_key = get_set_cookie_header(); let header_value = create_cookie("".to_string().into(), expiry, max_age) .to_string() .into_masked(); @@ -36,6 +49,19 @@ pub fn remove_cookie_response() -> UserResponse<()> { Ok(ApplicationResponse::JsonWithHeaders(((), header))) } +pub fn parse_cookie(cookies: &str) -> RouterResult<String> { + Cookie::split_parse(cookies) + .find_map(|cookie| { + cookie + .ok() + .filter(|parsed_cookie| parsed_cookie.name() == JWT_TOKEN_COOKIE_NAME) + .map(|parsed_cookie| parsed_cookie.value().to_owned()) + }) + .ok_or(report!(ApiErrorResponse::InvalidCookie)) + .attach_printable("Cookie Parsing Failed") +} + +#[cfg(feature = "olap")] fn create_cookie<'c>( token: Secret<String>, expires: OffsetDateTime, @@ -51,12 +77,18 @@ fn create_cookie<'c>( .build() } +#[cfg(feature = "olap")] fn get_expiry_and_max_age_from_seconds(seconds: i64) -> (OffsetDateTime, Duration) { let max_age = Duration::seconds(seconds); let expiry = OffsetDateTime::now_utc().saturating_add(max_age); (expiry, max_age) } -fn get_cookie_header() -> String { +#[cfg(feature = "olap")] +fn get_set_cookie_header() -> String { actix_http::header::SET_COOKIE.to_string() } + +pub fn get_cookie_header() -> String { + actix_http::header::COOKIE.to_string() +}
feat
Implemented cookie parsing for auth (#4298)
57ac6df8979ea244f5fe3231e1c22e8c0d273c6e
2023-01-03 14:16:45
ItsMeShashank
refactor(router): make payments core utilities public (#226)
false
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 8ca9322c75e..39b99321a5b 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -297,7 +297,7 @@ pub async fn payments_response_for_redirection_flows<'a>( #[allow(clippy::too_many_arguments)] #[instrument(skip_all)] -async fn call_connector_service<F, Op, Req>( +pub async fn call_connector_service<F, Op, Req>( state: &AppState, merchant_account: &storage::MerchantAccount, payment_id: &api::PaymentIdType, @@ -363,7 +363,7 @@ where Ok(response) } -async fn call_multiple_connectors_service<F, Op, Req>( +pub async fn call_multiple_connectors_service<F, Op, Req>( state: &AppState, merchant_account: &storage::MerchantAccount, connectors: Vec<api::ConnectorData>, diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index da0286498b8..63e29ecf8c8 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -1,9 +1,9 @@ -mod authorize_flow; -mod cancel_flow; -mod capture_flow; -mod psync_flow; -mod session_flow; -mod verfiy_flow; +pub mod authorize_flow; +pub mod cancel_flow; +pub mod capture_flow; +pub mod psync_flow; +pub mod session_flow; +pub mod verfiy_flow; use async_trait::async_trait; diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index fbd9e0d6ca6..2daa0993171 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -1,13 +1,13 @@ -mod payment_cancel; -mod payment_capture; -mod payment_confirm; -mod payment_create; -mod payment_method_validate; -mod payment_response; -mod payment_session; -mod payment_start; -mod payment_status; -mod payment_update; +pub mod payment_cancel; +pub mod payment_capture; +pub mod payment_confirm; +pub mod payment_create; +pub mod payment_method_validate; +pub mod payment_response; +pub mod payment_session; +pub mod payment_start; +pub mod payment_status; +pub mod payment_update; use async_trait::async_trait; use error_stack::{report, ResultExt};
refactor
make payments core utilities public (#226)
e3e31f392bc40b5d153d1f4dac6f91decd65b723
2024-06-10 18:25:22
Mani Chandra
refactor(users): Make password nullable in `users` table (#4902)
false
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 15e662fe438..a7d5a8c02bc 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -1223,7 +1223,7 @@ diesel::table! { #[max_length = 255] name -> Varchar, #[max_length = 255] - password -> Varchar, + password -> Nullable<Varchar>, is_verified -> Bool, created_at -> Timestamp, last_modified_at -> Timestamp, diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs index 6a040e41468..b1bbb66256c 100644 --- a/crates/diesel_models/src/user.rs +++ b/crates/diesel_models/src/user.rs @@ -17,7 +17,7 @@ pub struct User { pub user_id: String, pub email: pii::Email, pub name: Secret<String>, - pub password: Secret<String>, + pub password: Option<Secret<String>>, pub is_verified: bool, pub created_at: PrimitiveDateTime, pub last_modified_at: PrimitiveDateTime, @@ -37,7 +37,7 @@ pub struct UserNew { pub user_id: String, pub email: pii::Email, pub name: Secret<String>, - pub password: Secret<String>, + pub password: Option<Secret<String>>, pub is_verified: bool, pub created_at: Option<PrimitiveDateTime>, pub last_modified_at: Option<PrimitiveDateTime>, @@ -76,7 +76,7 @@ pub enum UserUpdate { totp_recovery_codes: Option<Vec<Secret<String>>>, }, PasswordUpdate { - password: Option<Secret<String>>, + password: Secret<String>, }, } @@ -127,7 +127,7 @@ impl From<UserUpdate> for UserUpdateInternal { }, UserUpdate::PasswordUpdate { password } => Self { name: None, - password, + password: Some(password), is_verified: None, last_modified_at, preferred_merchant_id: None, diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs index a4bb4fb4b03..c78f2c8080f 100644 --- a/crates/router/src/core/user.rs +++ b/crates/router/src/core/user.rs @@ -368,7 +368,7 @@ pub async fn change_password( .update_user_by_user_id( user.get_user_id(), diesel_models::user::UserUpdate::PasswordUpdate { - password: Some(new_password_hash), + password: new_password_hash, }, ) .await @@ -459,7 +459,7 @@ pub async fn rotate_password( .update_user_by_user_id( &user_token.user_id, storage_user::UserUpdate::PasswordUpdate { - password: Some(hash_password), + password: hash_password, }, ) .await @@ -510,7 +510,7 @@ pub async fn reset_password_token_only_flow( .get_email() .change_context(UserErrors::InternalServerError)?, storage_user::UserUpdate::PasswordUpdate { - password: Some(hash_password), + password: hash_password, }, ) .await @@ -548,7 +548,7 @@ pub async fn reset_password( .get_email() .change_context(UserErrors::InternalServerError)?, storage_user::UserUpdate::PasswordUpdate { - password: Some(hash_password), + password: hash_password, }, ) .await @@ -838,11 +838,9 @@ async fn handle_new_user_invitation( Ok(InviteMultipleUserResponse { is_email_sent, - password: if cfg!(not(feature = "email")) { - Some(new_user.get_password().get_secret()) - } else { - None - }, + password: new_user + .get_password() + .map(|password| password.get_secret()), email: request.email.clone(), error: None, }) diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs index e8104e3a155..742944bd1e0 100644 --- a/crates/router/src/db/user.rs +++ b/crates/router/src/db/user.rs @@ -244,7 +244,7 @@ impl UserInterface for MockDb { ..user.to_owned() }, storage::UserUpdate::PasswordUpdate { password } => storage::User { - password: password.clone().unwrap_or(user.password.clone()), + password: Some(password.clone()), last_password_modified_at: Some(common_utils::date_time::now()), ..user.to_owned() }, @@ -299,7 +299,7 @@ impl UserInterface for MockDb { ..user.to_owned() }, storage::UserUpdate::PasswordUpdate { password } => storage::User { - password: password.clone().unwrap_or(user.password.clone()), + password: Some(password.clone()), last_password_modified_at: Some(common_utils::date_time::now()), ..user.to_owned() }, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index d9ef736347f..47f26ce04e5 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -1,8 +1,4 @@ -use std::{ - collections::HashSet, - ops::{self, Not}, - str::FromStr, -}; +use std::{collections::HashSet, ops, str::FromStr}; use api_models::{ admin as admin_api, organization as api_org, user as user_api, user_role as user_role_api, @@ -517,9 +513,8 @@ pub struct NewUser { user_id: String, name: UserName, email: UserEmail, - password: UserPassword, + password: Option<UserPassword>, new_merchant: NewUserMerchant, - is_temporary_password: bool, } impl NewUser { @@ -539,7 +534,7 @@ impl NewUser { self.new_merchant.clone() } - pub fn get_password(&self) -> UserPassword { + pub fn get_password(&self) -> Option<UserPassword> { self.password.clone() } @@ -623,7 +618,12 @@ impl TryFrom<NewUser> for storage_user::UserNew { type Error = error_stack::Report<UserErrors>; fn try_from(value: NewUser) -> UserResult<Self> { - let hashed_password = password::generate_password_hash(value.password.get_secret())?; + let hashed_password = value + .password + .as_ref() + .map(|password| password::generate_password_hash(password.get_secret())) + .transpose()?; + let now = common_utils::date_time::now(); Ok(Self { user_id: value.get_user_id(), @@ -637,7 +637,7 @@ impl TryFrom<NewUser> for storage_user::UserNew { totp_status: TotpStatus::NotSet, totp_secret: None, totp_recovery_codes: None, - last_password_modified_at: value.is_temporary_password.not().then_some(now), + last_password_modified_at: value.password.is_some().then_some(now), }) } } @@ -655,10 +655,9 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUser { Ok(Self { name, email, - password, + password: Some(password), user_id, new_merchant, - is_temporary_password: false, }) } } @@ -677,9 +676,8 @@ impl TryFrom<user_api::SignUpRequest> for NewUser { user_id, name, email, - password, + password: Some(password), new_merchant, - is_temporary_password: false, }) } } @@ -691,16 +689,14 @@ impl TryFrom<user_api::ConnectAccountRequest> for NewUser { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.email.clone().try_into()?; let name = UserName::try_from(value.email.clone())?; - let password = UserPassword::new(password::get_temp_password())?; let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self { user_id, name, email, - password, + password: None, new_merchant, - is_temporary_password: true, }) } } @@ -721,9 +717,8 @@ impl TryFrom<(user_api::CreateInternalUserRequest, String)> for NewUser { user_id, name, email, - password, + password: Some(password), new_merchant, - is_temporary_password: false, }) } } @@ -739,11 +734,12 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUser { user_id: user.0.user_id, name: UserName::new(user.0.name)?, email: user.0.email.clone().try_into()?, - password: UserPassword::new_password_without_validation(user.0.password)?, + password: user + .0 + .password + .map(UserPassword::new_password_without_validation) + .transpose()?, new_merchant, - // This is true because we are not creating a user with this request. And if it is set - // to false, last_password_modified_at will be overwritten if this user is inserted. - is_temporary_password: true, }) } } @@ -754,7 +750,8 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser { let user_id = uuid::Uuid::new_v4().to_string(); let email = value.0.email.clone().try_into()?; let name = UserName::new(value.0.name.clone())?; - let password = UserPassword::new(password::get_temp_password())?; + let password = cfg!(not(feature = "email")) + .then_some(UserPassword::new(password::get_temp_password())?); let new_merchant = NewUserMerchant::try_from(value)?; Ok(Self { @@ -763,7 +760,6 @@ impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUser { email, password, new_merchant, - is_temporary_password: true, }) } } @@ -783,10 +779,14 @@ impl UserFromStorage { } pub fn compare_password(&self, candidate: &Secret<String>) -> UserResult<()> { - match password::is_correct_password(candidate, &self.0.password) { - Ok(true) => Ok(()), - Ok(false) => Err(UserErrors::InvalidCredentials.into()), - Err(e) => Err(e), + if let Some(password) = self.0.password.as_ref() { + match password::is_correct_password(candidate, password) { + Ok(true) => Ok(()), + Ok(false) => Err(UserErrors::InvalidCredentials.into()), + Err(e) => Err(e), + } + } else { + Err(UserErrors::InvalidCredentials.into()) } } diff --git a/migrations/2024-06-06-101812_user_optional_password/down.sql b/migrations/2024-06-06-101812_user_optional_password/down.sql new file mode 100644 index 00000000000..acd0b1efca3 --- /dev/null +++ b/migrations/2024-06-06-101812_user_optional_password/down.sql @@ -0,0 +1,2 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE users ALTER COLUMN password SET NOT NULL; diff --git a/migrations/2024-06-06-101812_user_optional_password/up.sql b/migrations/2024-06-06-101812_user_optional_password/up.sql new file mode 100644 index 00000000000..e48b1b751ab --- /dev/null +++ b/migrations/2024-06-06-101812_user_optional_password/up.sql @@ -0,0 +1,2 @@ +-- Your SQL goes here +ALTER TABLE users ALTER COLUMN password DROP NOT NULL;
refactor
Make password nullable in `users` table (#4902)
81cb8da4d47fe2a75330d39c665bb259faa35b00
2023-10-12 11:27:50
Sahal Saad
feat(connector): [Cybersource] Use connector_request_reference_id as reference to the connector (#2512)
false
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index 3558f752841..5a3060f99eb 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -21,6 +21,7 @@ pub struct CybersourcePaymentsRequest { processing_information: ProcessingInformation, payment_information: PaymentInformation, order_information: OrderInformationWithBill, + client_reference_information: ClientReferenceInformation, } #[derive(Default, Debug, Serialize, Eq, PartialEq)] @@ -150,10 +151,15 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for CybersourcePaymentsRequest capture_options: None, }; + let client_reference_information = ClientReferenceInformation { + code: Some(item.connector_request_reference_id.clone()), + }; + Ok(Self { processing_information, payment_information, order_information, + client_reference_information, }) } _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), @@ -179,6 +185,9 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for CybersourcePaymentsRequest { }, ..Default::default() }, + client_reference_information: ClientReferenceInformation { + code: Some(value.connector_request_reference_id.clone()), + }, ..Default::default() }) } @@ -195,6 +204,9 @@ impl TryFrom<&types::RefundExecuteRouterData> for CybersourcePaymentsRequest { }, ..Default::default() }, + client_reference_information: ClientReferenceInformation { + code: Some(value.connector_request_reference_id.clone()), + }, ..Default::default() }) } @@ -278,7 +290,7 @@ pub struct CybersourcePaymentsResponse { client_reference_information: Option<ClientReferenceInformation>, } -#[derive(Default, Debug, Clone, Deserialize, Eq, PartialEq)] +#[derive(Default, Debug, Clone, Serialize, Deserialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct ClientReferenceInformation { code: Option<String>,
feat
[Cybersource] Use connector_request_reference_id as reference to the connector (#2512)
fbff2683efa539a02027f15a8a98024ec097b740
2024-07-26 18:43:49
Sarthak Soni
ci: set code owners for payment methods files (#5453)
false
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 5da3a2f14b9..f1ce4d0f1b8 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -59,6 +59,25 @@ 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/api_models/src/payment_methods.rs @juspay/hyperswitch-routing +crates/router/src/core/payment_methods.rs @juspay/hyperswitch-routing +crates/router/src/routes/payment_methods.rs @juspay/hyperswitch-routing +crates/router/src/types/api/payment_methods.rs @juspay/hyperswitch-routing +crates/router/src/types/storage/payment_method.rs @juspay/hyperswitch-routing +crates/router/src/db/payment_method.rs @juspay/hyperswitch-routing +crates/diesel_models/src/payment_method.rs @juspay/hyperswitch-routing +crates/diesel_models/src/query/payment_method.rs @juspay/hyperswitch-routing +crates/storage_impl/src/payment_method.rs @juspay/hyperswitch-routing +crates/openapi/src/routes/payment_method.rs @juspay/hyperswitch-routing +crates/router/src/core/payment_methods/cards.rs @juspay/hyperswitch-routing +crates/router/src/core/payment_methods/utils.rs @juspay/hyperswitch-routing +crates/router/src/core/payment_methods/transformers.rs @juspay/hyperswitch-routing +crates/router/src/core/payment_methods/vault.rs @juspay/hyperswitch-routing +crates/router/src/core/payment_methods/migration.rs @juspay/hyperswitch-routing +crates/router/src/core/payment_methods/surcharge_decision_configs.rs @juspay/hyperswitch-routing +crates/router/src/workflows/payment_method_status_update.rs @juspay/hyperswitch-routing +crates/router/src/core/payments/tokenization.rs @juspay/hyperswitch-routing + crates/api_models/src/connector_onboarding.rs @juspay/hyperswitch-dashboard crates/api_models/src/user @juspay/hyperswitch-dashboard crates/api_models/src/user.rs @juspay/hyperswitch-dashboard
ci
set code owners for payment methods files (#5453)
928beecdd7fe9e09b38ffe750627ca4af94ffc93
2024-01-17 16:03:46
Kashif
chore(router): remove recon from default features (#3370)
false
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 45702a4ecb0..d1f603f188e 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -8,7 +8,7 @@ readme = "README.md" license.workspace = true [features] -default = ["payouts", "frm", "recon"] +default = ["payouts", "frm"] business_profile_routing = [] connector_choice_bcompat = [] errors = ["dep:actix-web", "dep:reqwest"] diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 0a544e0bd09..8897fdac2c2 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -9,13 +9,13 @@ readme = "README.md" license.workspace = true [features] -default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm", "recon"] +default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "business_profile_routing", "connector_choice_mca_id", "profile_specific_fallback_routing", "retry", "frm"] s3 = ["dep:aws-sdk-s3", "dep:aws-config"] kms = ["external_services/kms", "dep:aws-config"] email = ["external_services/email", "dep:aws-config", "olap"] frm = [] stripe = ["dep:serde_qs"] -release = ["kms", "stripe", "s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen"] +release = ["kms", "stripe", "s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] olap = ["data_models/olap", "storage_impl/olap", "scheduler/olap", "dep:analytics"] oltp = ["storage_impl/oltp"] kv_store = ["scheduler/kv_store"] @@ -30,7 +30,7 @@ connector_choice_mca_id = ["api_models/connector_choice_mca_id", "euclid/connect external_access_dc = ["dummy_connector"] detailed_errors = ["api_models/detailed_errors", "error-stack/serde"] payouts = [] -recon = ["email"] +recon = ["email", "api_models/recon"] retry = [] [dependencies]
chore
remove recon from default features (#3370)
19ee324d373262aea873bb7a120f0e80b918fd84
2023-08-22 12:19:43
Kashif
fix: storage of generic payment methods in permanent locker (#1799)
false
diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index e45b2ad759d..29dd089961b 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -13,6 +13,7 @@ pub mod files; pub mod mandates; pub mod payment_methods; pub mod payments; +#[cfg(feature = "payouts")] pub mod payouts; pub mod refunds; pub mod webhooks; diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs index 711b28057d3..8fbed6bf68d 100644 --- a/crates/api_models/src/payouts.rs +++ b/crates/api_models/src/payouts.rs @@ -1,21 +1,14 @@ -#[cfg(feature = "payouts")] use cards::CardNumber; -#[cfg(feature = "payouts")] use common_utils::{ crypto, pii::{self, Email}, }; -#[cfg(feature = "payouts")] use masking::Secret; -#[cfg(feature = "payouts")] use serde::{Deserialize, Serialize}; -#[cfg(feature = "payouts")] use utoipa::ToSchema; -#[cfg(feature = "payouts")] use crate::{admin, enums as api_enums, payments}; -#[cfg(feature = "payouts")] #[derive(Debug, Deserialize, Serialize, Clone, ToSchema)] pub enum PayoutRequest { PayoutActionRequest(PayoutActionRequest), @@ -23,7 +16,6 @@ pub enum PayoutRequest { PayoutRetrieveRequest(PayoutRetrieveRequest), } -#[cfg(feature = "payouts")] #[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PayoutCreateRequest { @@ -156,7 +148,6 @@ pub struct PayoutCreateRequest { pub payout_token: Option<String>, } -#[cfg(feature = "payouts")] #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodData { @@ -164,14 +155,12 @@ pub enum PayoutMethodData { Bank(Bank), } -#[cfg(feature = "payouts")] impl Default for PayoutMethodData { fn default() -> Self { Self::Card(Card::default()) } } -#[cfg(feature = "payouts")] #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Card { /// The card number @@ -191,7 +180,6 @@ pub struct Card { pub card_holder_name: Secret<String>, } -#[cfg(feature = "payouts")] #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(untagged)] pub enum Bank { @@ -200,7 +188,6 @@ pub enum Bank { Sepa(SepaBankTransfer), } -#[cfg(feature = "payouts")] #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct AchBankTransfer { /// Bank name @@ -224,7 +211,6 @@ pub struct AchBankTransfer { pub bank_routing_number: Secret<String>, } -#[cfg(feature = "payouts")] #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct BacsBankTransfer { /// Bank name @@ -248,7 +234,6 @@ pub struct BacsBankTransfer { pub bank_sort_code: Secret<String>, } -#[cfg(feature = "payouts")] #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] // The SEPA (Single Euro Payments Area) is a pan-European network that allows you to send and receive payments in euros between two cross-border bank accounts in the eurozone. pub struct SepaBankTransfer { @@ -273,7 +258,6 @@ pub struct SepaBankTransfer { pub bic: Option<Secret<String>>, } -#[cfg(feature = "payouts")] #[derive(Debug, ToSchema, Clone, Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutCreateResponse { @@ -394,13 +378,11 @@ pub struct PayoutCreateResponse { pub error_code: Option<String>, } -#[cfg(feature = "payouts")] #[derive(Default, Debug, Clone, Deserialize, ToSchema)] pub struct PayoutRetrieveBody { pub force_sync: Option<bool>, } -#[cfg(feature = "payouts")] #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutRetrieveRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts @@ -419,7 +401,6 @@ pub struct PayoutRetrieveRequest { pub force_sync: Option<bool>, } -#[cfg(feature = "payouts")] #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutActionRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 65d59bf156d..1028c37c25a 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -13,8 +13,6 @@ use api_models::{ }, payments::BankCodeResponse, }; -#[cfg(feature = "payouts")] -use common_utils::ext_traits::ByteSliceExt; use common_utils::{ consts, ext_traits::{AsyncExt, StringExt, ValueExt}, @@ -257,8 +255,20 @@ pub async fn add_card_hs( customer_id: String, merchant_account: &domain::MerchantAccount, ) -> errors::CustomResult<(api::PaymentMethodResponse, bool), errors::VaultError> { - let store_card_payload = - call_to_card_hs(state, &card, None, &customer_id, merchant_account).await?; + let payload = payment_methods::StoreLockerReq::LockerCard(payment_methods::StoreCardReq { + merchant_id: &merchant_account.merchant_id, + merchant_customer_id: customer_id.to_owned(), + card: payment_methods::Card { + card_number: card.card_number.to_owned(), + name_on_card: card.card_holder_name.to_owned(), + card_exp_month: card.card_exp_month.to_owned(), + card_exp_year: card.card_exp_year.to_owned(), + card_brand: None, + card_isin: None, + nick_name: card.nick_name.as_ref().map(masking::Secret::peek).cloned(), + }, + }); + let store_card_payload = call_to_locker_hs(state, &payload, &customer_id).await?; let payment_method_resp = payment_methods::mk_add_card_response_hs( card, @@ -272,6 +282,28 @@ pub async fn add_card_hs( )) } +#[instrument(skip_all)] +pub async fn decode_and_decrypt_locker_data( + key_store: &domain::MerchantKeyStore, + enc_card_data: String, +) -> errors::CustomResult<Secret<String>, errors::VaultError> { + // Fetch key + let key = key_store.key.get_inner().peek(); + // Decode + let decoded_bytes = hex::decode(&enc_card_data) + .into_report() + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Failed to decode hex string into bytes")?; + // Decrypt + decrypt(Some(Encryption::new(decoded_bytes.into())), key) + .await + .change_context(errors::VaultError::FetchPaymentMethodFailed)? + .map_or( + Err(report!(errors::VaultError::FetchPaymentMethodFailed)), + |d| Ok(d.into_inner()), + ) +} + #[instrument(skip_all)] pub async fn get_payment_method_from_hs_locker<'a>( state: &'a routes::AppState, @@ -286,7 +318,7 @@ pub async fn get_payment_method_from_hs_locker<'a>( #[cfg(feature = "kms")] let jwekey = &state.kms_secrets; - if !locker.mock_locker { + let payment_method_data = if !locker.mock_locker { let request = payment_methods::mk_get_card_request_hs( jwekey, locker, @@ -315,44 +347,34 @@ pub async fn get_payment_method_from_hs_locker<'a>( .payload .get_required_value("RetrieveCardRespPayload") .change_context(errors::VaultError::FetchPaymentMethodFailed)?; - retrieve_card_resp + let enc_card_data = retrieve_card_resp .enc_card_data .get_required_value("enc_card_data") - .change_context(errors::VaultError::FetchPaymentMethodFailed) + .change_context(errors::VaultError::FetchPaymentMethodFailed)?; + decode_and_decrypt_locker_data(key_store, enc_card_data.peek().to_string()).await? } else { - let get_card_resp = - mock_get_payment_method(&*state.store, key_store, payment_method_reference).await?; - Ok(get_card_resp.payment_method.payment_method_data) - } + mock_get_payment_method(&*state.store, key_store, payment_method_reference) + .await? + .payment_method + .payment_method_data + }; + Ok(payment_method_data) } #[instrument(skip_all)] -pub async fn call_to_card_hs( +pub async fn call_to_locker_hs<'a>( state: &routes::AppState, - card: &api::CardDetail, - enc_value: Option<&str>, + payload: &payment_methods::StoreLockerReq<'a>, customer_id: &str, - merchant_account: &domain::MerchantAccount, ) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> { let locker = &state.conf.locker; #[cfg(not(feature = "kms"))] let jwekey = &state.conf.jwekey; #[cfg(feature = "kms")] let jwekey = &state.kms_secrets; - let db = &*state.store; - let merchant_id = &merchant_account.merchant_id; - let stored_card_response = if !locker.mock_locker { - let request = payment_methods::mk_add_card_request_hs( - jwekey, - locker, - card, - enc_value, - customer_id, - merchant_id, - ) - .await?; + let request = payment_methods::mk_add_locker_request_hs(jwekey, locker, payload).await?; let response = services::call_connector_api(state, request) .await .change_context(errors::VaultError::SaveCardFailed); @@ -371,7 +393,7 @@ pub async fn call_to_card_hs( stored_card_resp } else { let card_id = generate_id(consts::ID_LENGTH, "card"); - mock_add_card_hs(db, &card_id, card, None, enc_value, None, Some(customer_id)).await? + mock_call_to_locker_hs(db, &card_id, payload, None, None, Some(customer_id)).await? }; let stored_card = stored_card_response @@ -495,31 +517,47 @@ pub async fn delete_card_from_hs_locker<'a>( } ///Mock api for local testing -#[instrument(skip_all)] -pub async fn mock_add_card_hs( +pub async fn mock_call_to_locker_hs<'a>( db: &dyn db::StorageInterface, card_id: &str, - card: &api::CardDetail, + payload: &payment_methods::StoreLockerReq<'a>, card_cvc: Option<String>, - enc_val: Option<&str>, payment_method_id: Option<String>, customer_id: Option<&str>, ) -> errors::CustomResult<payment_methods::StoreCardResp, errors::VaultError> { - let locker_mock_up = storage::LockerMockUpNew { + let mut locker_mock_up = storage::LockerMockUpNew { card_id: card_id.to_string(), external_id: uuid::Uuid::new_v4().to_string(), card_fingerprint: uuid::Uuid::new_v4().to_string(), card_global_fingerprint: uuid::Uuid::new_v4().to_string(), - merchant_id: "mm01".to_string(), - card_number: card.card_number.peek().to_string(), - card_exp_year: card.card_exp_year.peek().to_string(), - card_exp_month: card.card_exp_month.peek().to_string(), + merchant_id: "".to_string(), + card_number: "4111111111111111".to_string(), + card_exp_year: "2099".to_string(), + card_exp_month: "12".to_string(), card_cvc, payment_method_id, customer_id: customer_id.map(str::to_string), - name_on_card: card.card_holder_name.to_owned().expose_option(), - nickname: card.nick_name.to_owned().map(masking::Secret::expose), - enc_card_data: enc_val.map(|e| e.to_string()), + name_on_card: None, + nickname: None, + enc_card_data: None, + }; + locker_mock_up = match payload { + payment_methods::StoreLockerReq::LockerCard(store_card_req) => storage::LockerMockUpNew { + merchant_id: store_card_req.merchant_id.to_string(), + card_number: store_card_req.card.card_number.peek().to_string(), + card_exp_year: store_card_req.card.card_exp_year.peek().to_string(), + card_exp_month: store_card_req.card.card_exp_month.peek().to_string(), + name_on_card: store_card_req.card.name_on_card.to_owned().expose_option(), + nickname: store_card_req.card.nick_name.to_owned(), + ..locker_mock_up + }, + payment_methods::StoreLockerReq::LockerGeneric(store_generic_req) => { + storage::LockerMockUpNew { + merchant_id: store_generic_req.merchant_id.to_string(), + enc_card_data: Some(store_generic_req.enc_data.to_owned()), + ..locker_mock_up + } + } }; let response = db @@ -588,21 +626,7 @@ pub async fn mock_get_payment_method<'a>( .await .change_context(errors::VaultError::FetchPaymentMethodFailed)?; let dec_data = if let Some(e) = locker_mock_up.enc_card_data { - // Fetch key - let key = key_store.key.get_inner().peek(); - // Decode - let decoded_bytes = hex::decode(e) - .into_report() - .change_context(errors::VaultError::ResponseDeserializationFailed) - .attach_printable("Failed to decode hex string into bytes")?; - // Decrypt - async { decrypt(Some(Encryption::new(decoded_bytes.into())), key).await } - .await - .change_context(errors::VaultError::FetchPaymentMethodFailed)? - .map_or( - Err(report!(errors::VaultError::FetchPaymentMethodFailed)), - |d| Ok(d.into_inner()), - ) + decode_and_decrypt_locker_data(key_store, e).await } else { Err(report!(errors::VaultError::FetchPaymentMethodFailed)) }?; @@ -1894,8 +1918,7 @@ pub async fn get_lookup_key_for_payout_method( .attach_printable("Error getting payment method from locker")?; let pm_parsed: api::PayoutMethodData = payment_method .peek() - .as_bytes() - .to_vec() + .to_string() .parse_struct("PayoutMethodData") .change_context(errors::ApiErrorResponse::InternalServerError)?; match &pm_parsed { diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs index 2d8fe43d186..086133ec78a 100644 --- a/crates/router/src/core/payment_methods/transformers.rs +++ b/crates/router/src/core/payment_methods/transformers.rs @@ -15,12 +15,26 @@ use crate::{ utils::{self, OptionExt}, }; +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum StoreLockerReq<'a> { + LockerCard(StoreCardReq<'a>), + LockerGeneric(StoreGenericReq<'a>), +} + #[derive(Debug, Deserialize, Serialize)] pub struct StoreCardReq<'a> { pub merchant_id: &'a str, pub merchant_customer_id: String, pub card: Card, - pub enc_card_data: Option<String>, +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct StoreGenericReq<'a> { + pub merchant_id: &'a str, + pub merchant_customer_id: String, + #[serde(rename = "enc_card_data")] + pub enc_data: String, } #[derive(Debug, Deserialize, Serialize)] @@ -253,32 +267,13 @@ pub async fn mk_basilisk_req( Ok(jwe_body) } -pub async fn mk_add_card_request_hs( +pub async fn mk_add_locker_request_hs<'a>( #[cfg(not(feature = "kms"))] jwekey: &settings::Jwekey, #[cfg(feature = "kms")] jwekey: &settings::ActiveKmsSecrets, locker: &settings::Locker, - card: &api::CardDetail, - enc_value: Option<&str>, - customer_id: &str, - merchant_id: &str, + payload: &StoreLockerReq<'a>, ) -> CustomResult<services::Request, errors::VaultError> { - let merchant_customer_id = customer_id.to_owned(); - let card = Card { - card_number: card.card_number.to_owned(), - name_on_card: card.card_holder_name.to_owned(), - card_exp_month: card.card_exp_month.to_owned(), - card_exp_year: card.card_exp_year.to_owned(), - card_brand: None, - card_isin: None, - nick_name: card.nick_name.to_owned().map(masking::Secret::expose), - }; - let store_card_req = StoreCardReq { - merchant_id, - merchant_customer_id, - card, - enc_card_data: enc_value.map(|e| e.to_string()), - }; - let payload = utils::Encode::<StoreCardReq<'_>>::encode_to_vec(&store_card_req) + let payload = utils::Encode::<StoreCardReq<'_>>::encode_to_vec(&payload) .change_context(errors::VaultError::RequestEncodingFailed)?; #[cfg(feature = "kms")] diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 462e569bb36..6959962a13e 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -1,6 +1,3 @@ -use std::str::FromStr; - -use ::cards::CardNumber; use common_utils::{errors::CustomResult, ext_traits::ValueExt}; use diesel_models::encryption::Encryption; use error_stack::{IntoReport, ResultExt}; @@ -9,7 +6,11 @@ use masking::{ExposeInterface, PeekInterface, Secret}; use crate::{ core::{ errors::{self, RouterResult}, - payment_methods::{cards, vault}, + payment_methods::{ + cards, transformers, + transformers::{StoreCardReq, StoreGenericReq, StoreLockerReq}, + vault, + }, payments::{customers::get_connector_customer_details_if_present, CustomerDetails}, utils as core_utils, }, @@ -125,21 +126,37 @@ pub async fn save_payout_data_to_locker( merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, ) -> RouterResult<()> { - let mut enc_card_data = None; - let (card_details, payment_method_type) = match payout_method_data { - api_models::payouts::PayoutMethodData::Card(card) => ( - api::CardDetail { + let (locker_req, card_details, payment_method_type) = match payout_method_data { + api_models::payouts::PayoutMethodData::Card(card) => { + let card_detail = api::CardDetail { card_number: card.card_number.to_owned(), + card_holder_name: Some(card.card_holder_name.to_owned()), card_exp_month: card.expiry_month.to_owned(), card_exp_year: card.expiry_year.to_owned(), - card_holder_name: Some(card.card_holder_name.to_owned()), nick_name: None, - }, - api_enums::PaymentMethodType::Debit, - ), + }; + let payload = StoreLockerReq::LockerCard(StoreCardReq { + merchant_id: &merchant_account.merchant_id, + merchant_customer_id: payout_attempt.customer_id.to_owned(), + card: transformers::Card { + card_number: card.card_number.to_owned(), + name_on_card: Some(card.card_holder_name.to_owned()), + card_exp_month: card.expiry_month.to_owned(), + card_exp_year: card.expiry_year.to_owned(), + card_brand: None, + card_isin: None, + nick_name: None, + }, + }); + ( + payload, + Some(card_detail), + api_enums::PaymentMethodType::Debit, + ) + } api_models::payouts::PayoutMethodData::Bank(bank) => { let key = key_store.key.get_inner().peek(); - let enc_str = async { + let enc_data = async { serde_json::to_value(payout_method_data.to_owned()) .into_report() .change_context(errors::ApiErrorResponse::InternalServerError) @@ -160,32 +177,22 @@ pub async fn save_payout_data_to_locker( .map_or(Err(errors::ApiErrorResponse::InternalServerError), |e| { Ok(hex::encode(e.peek())) })?; - enc_card_data = Some(enc_str); + let payload = StoreLockerReq::LockerGeneric(StoreGenericReq { + merchant_id: &merchant_account.merchant_id, + merchant_customer_id: payout_attempt.customer_id.to_owned(), + enc_data, + }); ( - api::CardDetail { - card_number: CardNumber::from_str("4111111111111111") - .into_report() - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to form a sample card number")?, - card_exp_month: "12".to_string().into(), - card_exp_year: "99".to_string().into(), - card_holder_name: None, - nick_name: None, - }, + payload, + None, api_enums::PaymentMethodType::foreign_from(bank.to_owned()), ) } }; // Store payout method in locker - let stored_resp = cards::call_to_card_hs( - state, - &card_details, - enc_card_data.as_deref(), - &payout_attempt.customer_id, - merchant_account, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError)?; + let stored_resp = cards::call_to_locker_hs(state, &locker_req, &payout_attempt.customer_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError)?; // Store card_reference in payouts table let db = &*state.store; @@ -208,7 +215,7 @@ pub async fn save_payout_data_to_locker( payment_method_type: Some(payment_method_type), payment_method_issuer: None, payment_method_issuer_code: None, - card: Some(card_details), + card: card_details, metadata: None, customer_id: Some(payout_attempt.customer_id.to_owned()), card_network: None,
fix
storage of generic payment methods in permanent locker (#1799)
46f14191ab7e036539ef3fd58acd9376b6b6b63c
2023-10-12 14:37:18
Kashif
fix: parse allowed_payment_method_types only if there is some value p… (#2161)
false
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 88ea12388db..ee5f34938f9 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1351,9 +1351,11 @@ pub async fn filter_payment_methods( payment_intent .allowed_payment_method_types .clone() - .parse_value("Vec<PaymentMethodType>") - .map_err(|error| logger::error!(%error, "Failed to deserialize PaymentIntent allowed_payment_method_types")) - .ok() + .map(|val| val.parse_value("Vec<PaymentMethodType>")) + .transpose() + .unwrap_or_else(|error| { + logger::error!(%error, "Failed to deserialize PaymentIntent allowed_payment_method_types"); None + }) }); for payment_method_type_info in payment_methods_enabled
fix
parse allowed_payment_method_types only if there is some value p… (#2161)
fb3a49be658c3c4374ca98f9eae5d88dc92a3669
2024-12-12 15:03:20
ShivanshMathurJuspay
refactor(kafka_message): NanoSecond precision for consolidated logs (#6771)
false
diff --git a/crates/router/src/services/kafka/dispute_event.rs b/crates/router/src/services/kafka/dispute_event.rs index 92327c044d7..45e7ff2c798 100644 --- a/crates/router/src/services/kafka/dispute_event.rs +++ b/crates/router/src/services/kafka/dispute_event.rs @@ -20,15 +20,15 @@ pub struct KafkaDisputeEvent<'a> { pub connector_dispute_id: &'a String, pub connector_reason: Option<&'a String>, pub connector_reason_code: Option<&'a String>, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub challenge_required_by: Option<OffsetDateTime>, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub connector_created_at: Option<OffsetDateTime>, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub connector_updated_at: Option<OffsetDateTime>, - #[serde(default, with = "time::serde::timestamp::milliseconds")] + #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, - #[serde(default, with = "time::serde::timestamp::milliseconds")] + #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, pub connector: &'a String, pub evidence: &'a Secret<serde_json::Value>, diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs index 177b211ae89..ec67dc75953 100644 --- a/crates/router/src/services/kafka/payment_attempt_event.rs +++ b/crates/router/src/services/kafka/payment_attempt_event.rs @@ -25,15 +25,15 @@ pub struct KafkaPaymentAttemptEvent<'a> { pub payment_method: Option<storage_enums::PaymentMethod>, pub connector_transaction_id: Option<&'a String>, pub capture_method: Option<storage_enums::CaptureMethod>, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub capture_on: Option<OffsetDateTime>, pub confirm: bool, pub authentication_type: Option<storage_enums::AuthenticationType>, - #[serde(with = "time::serde::timestamp::milliseconds")] + #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, - #[serde(with = "time::serde::timestamp::milliseconds")] + #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub cancellation_reason: Option<&'a String>, pub amount_to_capture: Option<MinorUnit>, diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs index 7509f711620..195b8679d31 100644 --- a/crates/router/src/services/kafka/payment_intent_event.rs +++ b/crates/router/src/services/kafka/payment_intent_event.rs @@ -22,11 +22,11 @@ pub struct KafkaPaymentIntentEvent<'a> { pub connector_id: Option<&'a String>, pub statement_descriptor_name: Option<&'a String>, pub statement_descriptor_suffix: Option<&'a String>, - #[serde(with = "time::serde::timestamp::milliseconds")] + #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, - #[serde(with = "time::serde::timestamp::milliseconds")] + #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, @@ -60,11 +60,11 @@ pub struct KafkaPaymentIntentEvent<'a> { pub return_url: Option<&'a String>, pub metadata: Option<String>, pub statement_descriptor: Option<&'a String>, - #[serde(with = "time::serde::timestamp::milliseconds")] + #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, - #[serde(with = "time::serde::timestamp::milliseconds")] + #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, - #[serde(default, with = "time::serde::timestamp::milliseconds::option")] + #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs index 74278944b04..b9b3db17b58 100644 --- a/crates/router/src/services/kafka/refund_event.rs +++ b/crates/router/src/services/kafka/refund_event.rs @@ -24,9 +24,9 @@ pub struct KafkaRefundEvent<'a> { pub sent_to_gateway: &'a bool, pub refund_error_message: Option<&'a String>, pub refund_arn: Option<&'a String>, - #[serde(default, with = "time::serde::timestamp::milliseconds")] + #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, - #[serde(default, with = "time::serde::timestamp::milliseconds")] + #[serde(default, with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, pub description: Option<&'a String>, pub attempt_id: &'a String,
refactor
NanoSecond precision for consolidated logs (#6771)
70612e4c6fbc8e604c4adb5737a9164e5310c904
2024-05-21 19:04:54
github-actions
chore(version): 2024.05.21.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d6efd3169b..a91002ff43b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,22 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.05.21.1 + +### Features + +- **Cypress:** Add response handler for Connector Testing ([#4624](https://github.com/juspay/hyperswitch/pull/4624)) ([`2e79ee0`](https://github.com/juspay/hyperswitch/commit/2e79ee0615292182111586fda7655dd9a796ef4f)) +- **constraint_graph:** Add visualization functionality to the constraint graph ([#4701](https://github.com/juspay/hyperswitch/pull/4701)) ([`0f53f74`](https://github.com/juspay/hyperswitch/commit/0f53f74d26e829602519998c41a460dc9a4809af)) + +### Refactors + +- **core:** Add support to enable pm_data and pm_id in payments response ([#4711](https://github.com/juspay/hyperswitch/pull/4711)) ([`2cd360e`](https://github.com/juspay/hyperswitch/commit/2cd360e6a9d6bbe4b91f7b501b6013db1f31d898)) +- **router:** Added a new type minor unit to amount ([#4629](https://github.com/juspay/hyperswitch/pull/4629)) ([`443b7e6`](https://github.com/juspay/hyperswitch/commit/443b7e6ea2cf63f35a28a1cd24860399d96b15ba)) + +**Full Changelog:** [`2024.05.21.0...2024.05.21.1`](https://github.com/juspay/hyperswitch/compare/2024.05.21.0...2024.05.21.1) + +- - - + ## 2024.05.21.0 ### Features
chore
2024.05.21.1
5c313656a129362b0e905e5fbf349dbbec57199c
2023-11-16 17:13:26
github-actions
test(postman): update postman collection files
false
diff --git a/postman/collection-json/paypal.postman_collection.json b/postman/collection-json/paypal.postman_collection.json index 4849a27fe05..d9deae47f9a 100644 --- a/postman/collection-json/paypal.postman_collection.json +++ b/postman/collection-json/paypal.postman_collection.json @@ -747,9 +747,9 @@ "// Response body should have value \"requires_confirmation\" for \"status\"", "if (jsonData?.status) {", " pm.test(", - " \"[POST]::/payments - Content check if value for 'status' matches 'requires_capture'\",", + " \"[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'\",", " function () {", - " pm.expect(jsonData.status).to.eql(\"requires_confirmation\");", + " pm.expect(jsonData.status).to.eql(\"requires_payment_method\");", " },", " );", "}", @@ -808,7 +808,7 @@ "language": "json" } }, - "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4012000033330026\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"paypal\"}}" + "raw": "{\"amount\":6540,\"currency\":\"USD\",\"confirm\":false,\"capture_method\":\"manual\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"customer_id\":\"StripeCustomer\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+1\",\"description\":\"Its my first payment request\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://duck.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"PiX\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"routing\":{\"type\":\"single\",\"data\":\"paypal\"}}" }, "url": { "raw": "{{baseUrl}}/payments", @@ -990,7 +990,7 @@ "language": "json" } }, - "raw": "{\"client_secret\":\"{{client_secret}}\",\"surcharge_details\":{\"surcharge_amount\":5,\"tax_amount\":5}}" + "raw": "{\"client_secret\":\"{{client_secret}}\",\"surcharge_details\":{\"surcharge_amount\":5,\"tax_amount\":5},\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4012000033330026\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}}}" }, "url": { "raw": "{{baseUrl}}/payments/:id/confirm",
test
update postman collection files
72968dcecf16c8821a383a826e4e35408b035633
2024-01-04 12:16:24
github-actions
chore(version): v1.106.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index ebd711b2e60..30b7957272c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,38 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.106.0 (2024-01-04) + +### Features + +- **connector:** + - [BOA] Populate merchant_defined_information with metadata ([#3208](https://github.com/juspay/hyperswitch/pull/3208)) ([`18eca7e`](https://github.com/juspay/hyperswitch/commit/18eca7e9fbe6cdc101bd135c4618882b7a5455bf)) + - [CYBERSOURCE] Refactor cybersource ([#3215](https://github.com/juspay/hyperswitch/pull/3215)) ([`e06ba14`](https://github.com/juspay/hyperswitch/commit/e06ba148b666772fe79d7050d0c505dd2f04f87c)) +- **customers:** Add JWT Authentication for `/customers` APIs ([#3179](https://github.com/juspay/hyperswitch/pull/3179)) ([`aefe618`](https://github.com/juspay/hyperswitch/commit/aefe6184ec3e3156877c72988ca0f92454a47e7d)) + +### Bug Fixes + +- **connector:** [Volt] Error handling for auth response ([#3187](https://github.com/juspay/hyperswitch/pull/3187)) ([`a51c54d`](https://github.com/juspay/hyperswitch/commit/a51c54d39d3687c6a06176895435ac66fa194d7b)) +- **core:** Fix recurring mandates flow for cyber source ([#3224](https://github.com/juspay/hyperswitch/pull/3224)) ([`6a1743e`](https://github.com/juspay/hyperswitch/commit/6a1743ebe993d5abb53f2ce1b8b383aa4a9553fb)) +- **middleware:** Add support for logging request-id sent in request ([#3225](https://github.com/juspay/hyperswitch/pull/3225)) ([`0f72b55`](https://github.com/juspay/hyperswitch/commit/0f72b5527aab221b8e69e737e5d19abdd0696150)) + +### Refactors + +- **connector:** [NMI] Include mandatory fields for card 3DS ([#3203](https://github.com/juspay/hyperswitch/pull/3203)) ([`a46b8a7`](https://github.com/juspay/hyperswitch/commit/a46b8a7b05367fbbdbf4fca89d8a6b29110a4e1c)) + +### Testing + +- **postman:** Update postman collection files ([`0248d35`](https://github.com/juspay/hyperswitch/commit/0248d35dd49d2dc7e5e4da6b60a3ee3577c8eac9)) + +### Miscellaneous Tasks + +- Fix channel handling for consumer workflow loop ([#3223](https://github.com/juspay/hyperswitch/pull/3223)) ([`51e1fac`](https://github.com/juspay/hyperswitch/commit/51e1fac556fdd8775e0bbc858b0b3cc50a7e88ec)) + +**Full Changelog:** [`v1.105.0...v1.106.0`](https://github.com/juspay/hyperswitch/compare/v1.105.0...v1.106.0) + +- - - + + ## 1.105.0 (2023-12-23) ### Features
chore
v1.106.0
c50a75306e406e5323ce47efcb25ad98fc11fb77
2023-01-11 14:04:17
Sanchith Hegde
docs(community): move to `docs` directory and add missing community docs (#340)
false
diff --git a/contrib/CONTRIBUTOR_LICENSE_AGREEMENT.md b/contrib/CONTRIBUTOR_LICENSE_AGREEMENT.md deleted file mode 100644 index c2c15d77bcd..00000000000 --- a/contrib/CONTRIBUTOR_LICENSE_AGREEMENT.md +++ /dev/null @@ -1,25 +0,0 @@ -CONTRIBUTOR LICENSE AGREEMENT - -You accept and agree to the following terms and conditions for Your present and future Contributions submitted to Juspay Technologies Private Limited, Except for the license granted herein to Juspay Technologies Private Limited and recipients of software distributed by Juspay Technologies Private Limited, You reserve all right, title, and interest in and to Your Contributions. - -Definitions. -"You" (or "Your") shall mean the copyright owner or legal entity authorized by the copyright owner that is making this Agreement with Juspay Technologies Private Limited. For legal entities, the entity making a Contribution and all other entities that control, are controlled by, or are under common control with that entity are considered to be a single Contributor. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. - -"Contribution" shall mean the code, documentation or other original work of authorship, including any modifications or additions to an existing work, that is intentionally submitted by You to Juspay Technologies Private Limited for inclusion in, or documentation of, any of the products owned or managed by Juspay Technologies Private Limited (the "Work"). For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to Juspay Technologies Private Limited or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, Juspay Technologies Private Limited for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by You as "Not a Contribution." - -Grant of Copyright License. -Subject to the terms and conditions of this Agreement, You hereby grant to Juspay Technologies Private Limited and to recipients of software distributed by Juspay Technologies Private Limited a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, sublicense, and distribute Your Contributions and such derivative works. - -Grant of Patent License. -Subject to the terms and conditions of this Agreement, You hereby grant to Juspay Technologies Private Limited and to recipients of software distributed by Juspay Technologies Private Limited a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by You that are necessarily infringed by Your Contribution(s) alone or by combination of Your Contribution(s) with the Work to which such Contribution(s) was submitted. If any entity institutes patent litigation against You or any other entity (including a cross-claim or counterclaim in a lawsuit) alleging that your Contribution, or the Work to which you have contributed, constitutes direct or contributory patent infringement, then any patent licenses granted to that entity under this Agreement for that Contribution or Work shall terminate as of the date such litigation is filed. - -You represent that You are legally entitled to grant the above license. You represent further that each of Your employees is authorized to submit Contributions on Your behalf, but excluding employees that are designated in writing by You as "Not authorized to submit Contributions on behalf of [name of Your corporation here]." Such designations of exclusion for unauthorized employees are to be submitted via email to Juspay Technologies Private Limited. In case of Individual, if your employer(s) has rights to intellectual property that you create that includes your Contributions, you represent that you have received permission to make Contributions on behalf of that employer, that your employer has waived such rights for your Contributions to Juspay Technologies Private Limited, or that your employer has executed a separate Corporate CLA with Juspay Technologies Private Limited. - -You represent that each of Your Contributions is Your original creation (see section 7 for submissions on behalf of others). You represent that Your Contribution submissions include complete details of any third-party license or other restriction (including, but not limited to, related patents and trademarks) of which you are personally aware and which are associated with any part of Your Contributions. - -You are not expected to provide support for Your Contributions, except to the extent You desire to provide support. You may provide support for free, for a fee, or not at all. Unless required by applicable law or agreed to in writing, You provide Your Contributions on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON- INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. - -Should You wish to submit work that is not Your original creation, You may submit it to Juspay Technologies Private Limited separately from any Contribution, identifying the complete details of its source and of any license or other restriction (including, but not limited to, related patents, trademarks, and license agreements) of which you are personally aware, and conspicuously marking the work as "Submitted on behalf of a third-party: [Juspay Technologies Private Limited]". -You agree to notify Juspay Technologies Private Limited of any facts or circumstances of which you become aware that would make these representations inaccurate in any respect. It is Your responsibility to notify Juspay Technologies Private Limited when any change is required to the list of designated employees excluded from submitting Contributions on Your behalf. Such notification should be sent via email to Juspay Technologies Private Limited. - -This text is licensed to Juspay Technologies Private Limited and the original source is the [Juspay license](/LICENSE). \ No newline at end of file diff --git a/docs/CODE_OF_CONDUCT.md b/docs/CODE_OF_CONDUCT.md new file mode 100644 index 00000000000..84b56f8cc4b --- /dev/null +++ b/docs/CODE_OF_CONDUCT.md @@ -0,0 +1,5 @@ +# Code of Conduct + +The hyperswitch project adheres to the +[Rust Code of Conduct](https://www.rust-lang.org/policies/code-of-conduct). +This describes the minimum behavior expected from all contributors. diff --git a/contrib/CONTRIBUTING.md b/docs/CONTRIBUTING.md similarity index 98% rename from contrib/CONTRIBUTING.md rename to docs/CONTRIBUTING.md index 6d1bc274510..8b21c65d432 100644 --- a/contrib/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -488,10 +488,14 @@ The area label describes the area relevant to this issue or PR. - **A-connector-integration**: This issue/PR concerns connector integrations. - **A-core**: This issue/PR concerns the core flows. - **A-dependencies**: The issue/PR concerns one or more of our dependencies. +- **A-drainer**: The issue/PR concerns the drainer code. - **A-framework**: The issue/PR concerns code to interact with other systems or services such as database, Redis, connector APIs, etc. - **A-infra**: This issue/PR concerns deployments, Dockerfiles, Docker Compose files, etc. +- **A-macros**: This issue/PR concerns the `router_derive` crate. +- **A-payment-methods**: This issue/PR concerns the integration of new or + existing payment methods. - **A-process-tracker**: This issue/PR concerns the process tracker code. ### Category @@ -499,6 +503,7 @@ The area label describes the area relevant to this issue or PR. - **C-bug**: This issue is a bug report or this PR is a bug fix. - **C-doc**: This issue/PR concerns changes to the documentation. - **C-feature**: This issue is a feature request or this PR adds new features. +- **C-refactor**: This issue/PR concerns a refactor of existing behavior. - **C-tracking-issue**: This is a tracking issue for a proposal or for a category of bugs. @@ -536,6 +541,8 @@ The status label provides information about the status of the issue or PR. or the proposed solution raises other questions. - **S-in-progress**: The implementation relevant to this issue/PR is underway. - **S-invalid**: This is an invalid issue. +- **S-needs-conflict-resolution**: This PR requires merge conflicts to be + resolved by the author. - **S-needs-reproduction-steps**: This behavior hasn't been reproduced by the team. - **S-unactionable**: There is not enough information to act on this problem. diff --git a/docs/CONTRIBUTOR_LICENSE_AGREEMENT.md b/docs/CONTRIBUTOR_LICENSE_AGREEMENT.md new file mode 100644 index 00000000000..e1ff2c6abd2 --- /dev/null +++ b/docs/CONTRIBUTOR_LICENSE_AGREEMENT.md @@ -0,0 +1,104 @@ +# Contributor License Agreement + +You accept and agree to the following terms and conditions for Your present and +future Contributions submitted to Juspay Technologies Private Limited, Except +for the license granted herein to Juspay Technologies Private Limited and +recipients of software distributed by Juspay Technologies Private Limited, You +reserve all right, title, and interest in and to Your Contributions. + +1. **Definitions:** + + 1. "You" (or "Your") shall mean the copyright owner or legal entity + authorized by the copyright owner that is making this Agreement with + Juspay Technologies Private Limited. For legal entities, the entity making + a Contribution and all other entities that control, are controlled by, or + are under common control with that entity are considered to be a single + Contributor. For the purposes of this definition, "control" means (i) the + power, direct or indirect, to cause the direction or management of such + entity, whether by contract or otherwise, or (ii) ownership of fifty + percent (50%) or more of the outstanding shares, or (iii) beneficial + ownership of such entity. + + 2. "Contribution" shall mean the code, documentation or other original work + of authorship, including any modifications or additions to an existing + work, that is intentionally submitted by You to Juspay Technologies + Private Limited for inclusion in, or documentation of, any of the products + owned or managed by Juspay Technologies Private Limited (the "Work"). For + the purposes of this definition, "submitted" means any form of electronic, + verbal, or written communication sent to Juspay Technologies Private + Limited or its representatives, including but not limited to communication + on electronic mailing lists, source code control systems, and issue + tracking systems that are managed by, or on behalf of, Juspay Technologies + Private Limited for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by You as "Not a Contribution." + +2. **Grant of Copyright License:** Subject to the terms and conditions of this + Agreement, You hereby grant to Juspay Technologies Private Limited and to + recipients of software distributed by Juspay Technologies Private Limited a + perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare derivative works of, publicly + display, publicly perform, sublicense, and distribute Your Contributions and + such derivative works. + +3. **Grant of Patent License:** Subject to the terms and conditions of this + Agreement, You hereby grant to Juspay Technologies Private Limited and to + recipients of software distributed by Juspay Technologies Private Limited a + perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, use, + offer to sell, sell, import, and otherwise transfer the Work, where such + license applies only to those patent claims licensable by You that are + necessarily infringed by Your Contribution(s) alone or by combination of Your + Contribution(s) with the Work to which such Contribution(s) was submitted. If + any entity institutes patent litigation against You or any other entity + (including a cross-claim or counterclaim in a lawsuit) alleging that your + Contribution, or the Work to which you have contributed, constitutes direct + or contributory patent infringement, then any patent licenses granted to that + entity under this Agreement for that Contribution or Work shall terminate as + of the date such litigation is filed. + +4. You represent that You are legally entitled to grant the above license. You + represent further that each of Your employees is authorized to submit + Contributions on Your behalf, but excluding employees that are designated in + writing by You as "Not authorized to submit Contributions on behalf of [name + of Your corporation here]." Such designations of exclusion for unauthorized + employees are to be submitted via email to Juspay Technologies Private + Limited. In case of Individual, if your employer(s) has rights to + intellectual property that you create that includes your Contributions, you + represent that you have received permission to make Contributions on behalf + of that employer, that your employer has waived such rights for your + Contributions to Juspay Technologies Private Limited, or that your employer + has executed a separate Corporate CLA with Juspay Technologies Private + Limited. + +5. You represent that each of Your Contributions is Your original creation (see + section 7 for submissions on behalf of others). You represent that Your + Contribution submissions include complete details of any third-party license + or other restriction (including, but not limited to, related patents and + trademarks) of which you are personally aware and which are associated with + any part of Your Contributions. + +6. You are not expected to provide support for Your Contributions, except to the + extent You desire to provide support. You may provide support for free, for a + fee, or not at all. Unless required by applicable law or agreed to in + writing, You provide Your Contributions on an "AS IS" BASIS, WITHOUT + WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, + without limitation, any warranties or conditions of TITLE, NON- INFRINGEMENT, + MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. + +7. Should You wish to submit work that is not Your original creation, You may + submit it to Juspay Technologies Private Limited separately from any + Contribution, identifying the complete details of its source and of any + license or other restriction (including, but not limited to, related patents, + trademarks, and license agreements) of which you are personally aware, and + conspicuously marking the work as "Submitted on behalf of a third-party: + [Juspay Technologies Private Limited]". You agree to notify Juspay + Technologies Private Limited of any facts or circumstances of which you + become aware that would make these representations inaccurate in any respect. + It is Your responsibility to notify Juspay Technologies Private Limited when + any change is required to the list of designated employees excluded from + submitting Contributions on Your behalf. Such notification should be sent via + email to Juspay Technologies Private Limited. + +This text is licensed to Juspay Technologies Private Limited and the original +source is the [Juspay license](/LICENSE). diff --git a/docs/SECURITY.md b/docs/SECURITY.md new file mode 100644 index 00000000000..fb033753511 --- /dev/null +++ b/docs/SECURITY.md @@ -0,0 +1,12 @@ +# Security Policy + +## Reporting a security issue + +The hyperswitch project team welcomes security reports and is committed to +providing prompt attention to security issues. +Security issues should be reported privately via the +[advisories page on GitHub][report-vulnerability] or by email at +[[email protected]](mailto:[email protected]). +Security issues should not be reported via the public GitHub Issue tracker. + +[report-vulnerability]: https://github.com/juspay/hyperswitch/security/advisories/new
docs
move to `docs` directory and add missing community docs (#340)
622aac3015e95de55e83abd047b5c680ecd8d662
2024-04-04 18:45:04
Swangi Kumari
refactor(connector): add support for GooglePay recurring payments (#4300)
false
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 19a37ab0fb7..7d1862b2068 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -638,10 +638,11 @@ impl TryFrom<enums::PaymentMethodType> for StripePaymentMethodType { enums::PaymentMethodType::Blik => Ok(Self::Blik), enums::PaymentMethodType::AliPay => Ok(Self::Alipay), enums::PaymentMethodType::Przelewy24 => Ok(Self::Przelewy24), + // Stripe expects PMT as Card for Recurring Mandates Payments + enums::PaymentMethodType::GooglePay => Ok(Self::Card), enums::PaymentMethodType::Boleto | enums::PaymentMethodType::CardRedirect | enums::PaymentMethodType::CryptoCurrency - | enums::PaymentMethodType::GooglePay | enums::PaymentMethodType::Multibanco | enums::PaymentMethodType::OnlineBankingFpx | enums::PaymentMethodType::Paypal
refactor
add support for GooglePay recurring payments (#4300)
2b2c38146dc6dcf8d967dcc557281d3689bf746b
2023-10-25 23:50:25
Sudharsan GS
refactor(connector): [Worldpay] Remove Default Case Handling (#2488)
false
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs index 61d04a8e9f1..d31f4d65e78 100644 --- a/crates/router/src/connector/worldpay/transformers.rs +++ b/crates/router/src/connector/worldpay/transformers.rs @@ -217,7 +217,13 @@ impl From<EventType> for enums::AttemptStatus { EventType::CaptureFailed => Self::CaptureFailed, EventType::Refused => Self::Failure, EventType::Charged | EventType::SentForSettlement => Self::Charged, - _ => Self::Pending, + EventType::Cancelled + | EventType::SentForRefund + | EventType::RefundFailed + | EventType::Refunded + | EventType::Error + | EventType::Expired + | EventType::Unknown => Self::Pending, } } } @@ -227,7 +233,16 @@ impl From<EventType> for enums::RefundStatus { match value { EventType::Refunded => Self::Success, EventType::RefundFailed => Self::Failure, - _ => Self::Pending, + EventType::Authorized + | EventType::Cancelled + | EventType::Charged + | EventType::SentForRefund + | EventType::Refused + | EventType::Error + | EventType::SentForSettlement + | EventType::Expired + | EventType::CaptureFailed + | EventType::Unknown => Self::Pending, } } }
refactor
[Worldpay] Remove Default Case Handling (#2488)
37e34e3bfde9281b3a69b0769c901a887dcf400f
2024-08-02 15:27:59
AkshayaFoiger
fix(router): [Iatapay] make error status and error message optional (#5382)
false
diff --git a/crates/router/src/connector/iatapay.rs b/crates/router/src/connector/iatapay.rs index 8dc74798895..cf4a1d6e16b 100644 --- a/crates/router/src/connector/iatapay.rs +++ b/crates/router/src/connector/iatapay.rs @@ -149,7 +149,9 @@ impl ConnectorCommon for Iatapay { ErrorResponse { status_code: res.status_code, code: response.error, - message: response.message, + message: response + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), reason: response.reason, attempt_status: None, connector_transaction_id: None, diff --git a/crates/router/src/connector/iatapay/transformers.rs b/crates/router/src/connector/iatapay/transformers.rs index 1ce07fb49e3..845e079e136 100644 --- a/crates/router/src/connector/iatapay/transformers.rs +++ b/crates/router/src/connector/iatapay/transformers.rs @@ -581,9 +581,9 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>> #[derive(Debug, Deserialize, Serialize)] pub struct IatapayErrorResponse { - pub status: u16, + pub status: Option<u16>, pub error: String, - pub message: String, + pub message: Option<String>, pub reason: Option<String>, }
fix
[Iatapay] make error status and error message optional (#5382)
e0bde433282a34eb9eb28a2d9c43c2b17b5e65e5
2023-11-24 14:29:29
Vedant Khairnar
docs(README): Updated Community Platform Mentions (#2960)
false
diff --git a/README.md b/README.md index 8c5ad9e03b2..e820b93e63c 100644 --- a/README.md +++ b/README.md @@ -252,7 +252,8 @@ We welcome contributions from the community. Please read through our Included are directions for opening issues, coding standards, and notes on development. -πŸ¦€ **Important note for Rust developers**: We aim for contributions from the community +- We appreciate all types of contributions: code, documentation, demo creation, or something new way you want to contribute to us. We will reward every contribution with a Hyperswitch branded t-shirt. +- πŸ¦€ **Important note for Rust developers**: We aim for contributions from the community across a broad range of tracks. Hence, we have prioritised simplicity and code readability over purely idiomatic code. For example, some of the code in core functions (e.g., `payments_core`) is written to be more readable than @@ -264,10 +265,9 @@ pure-idiomatic. Get updates on Hyperswitch development and chat with the community: -- Read and subscribe to [the official Hyperswitch blog][blog]. -- Join our [Discord server][discord]. -- Join our [Slack workspace][slack]. -- Ask and explore our [GitHub Discussions][github-discussions]. +- [Discord server][discord] for questions related to contributing to hyperswitch, questions about the architecture, components, etc. +- [Slack workspace][slack] for questions related to integrating hyperswitch, integrating a connector in hyperswitch, etc. +- [GitHub Discussions][github-discussions] to drop feature requests or suggest anything payments-related you need for your stack. [blog]: https://hyperswitch.io/blog [discord]: https://discord.gg/wJZ7DVW8mm
docs
Updated Community Platform Mentions (#2960)
57ab8693e26a54cd5fe73b28459c9b03235e5d5b
2025-02-22 00:26:54
Sai Harsha Vardhan
feat(router): add `merchant_configuration_id` in netcetera metadata and make other merchant configurations optional (#7347)
false
diff --git a/crates/connector_configs/src/common_config.rs b/crates/connector_configs/src/common_config.rs index 599d22ae3f6..ebb5870655c 100644 --- a/crates/connector_configs/src/common_config.rs +++ b/crates/connector_configs/src/common_config.rs @@ -107,6 +107,7 @@ pub struct ApiModelMetaData { pub locale: Option<String>, pub card_brands: Option<Vec<String>>, pub merchant_category_code: Option<String>, + pub merchant_configuration_id: Option<String>, } #[serde_with::skip_serializing_none] diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs index 8f1deb02c53..2d1d2e4ede8 100644 --- a/crates/connector_configs/src/connector.rs +++ b/crates/connector_configs/src/connector.rs @@ -118,6 +118,7 @@ pub struct ConfigMetadata { pub locale: Option<InputData>, pub card_brands: Option<InputData>, pub merchant_category_code: Option<InputData>, + pub merchant_configuration_id: Option<InputData>, } #[serde_with::skip_serializing_none] diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml index 266ae918779..ba54730681f 100644 --- a/crates/connector_configs/toml/development.toml +++ b/crates/connector_configs/toml/development.toml @@ -4103,7 +4103,7 @@ private_key="Base64 encoded PEM formatted private key" name="mcc" label="MCC" placeholder="Enter MCC" -required=true +required=false type="Text" [netcetera.metadata.endpoint_prefix] name="endpoint_prefix" @@ -4115,25 +4115,31 @@ type="Text" name="merchant_country_code" label="3 digit numeric country code" placeholder="Enter 3 digit numeric country code" -required=true +required=false type="Text" [netcetera.metadata.merchant_name] name="merchant_name" label="Name of the merchant" placeholder="Enter Name of the merchant" -required=true +required=false type="Text" [netcetera.metadata.three_ds_requestor_name] name="three_ds_requestor_name" label="ThreeDS requestor name" placeholder="Enter ThreeDS requestor name" -required=true +required=false type="Text" [netcetera.metadata.three_ds_requestor_id] name="three_ds_requestor_id" label="ThreeDS request id" placeholder="Enter ThreeDS request id" -required=true +required=false +type="Text" +[netcetera.metadata.merchant_configuration_id] +name="merchant_configuration_id" +label="Merchant Configuration ID" +placeholder="Enter Merchant Configuration ID" +required=false type="Text" [taxjar] diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml index e4c0e70e191..88bba56c820 100644 --- a/crates/connector_configs/toml/production.toml +++ b/crates/connector_configs/toml/production.toml @@ -3041,31 +3041,37 @@ type="Text" name="mcc" label="MCC" placeholder="Enter MCC" -required=true +required=false type="Text" [netcetera.metadata.merchant_country_code] name="merchant_country_code" label="3 digit numeric country code" placeholder="Enter 3 digit numeric country code" -required=true +required=false type="Text" [netcetera.metadata.merchant_name] name="merchant_name" label="Name of the merchant" placeholder="Enter Name of the merchant" -required=true +required=false type="Text" [netcetera.metadata.three_ds_requestor_name] name="three_ds_requestor_name" label="ThreeDS requestor name" placeholder="Enter ThreeDS requestor name" -required=true +required=false type="Text" [netcetera.metadata.three_ds_requestor_id] name="three_ds_requestor_id" label="ThreeDS request id" placeholder="Enter ThreeDS request id" -required=true +required=false +type="Text" +[netcetera.metadata.merchant_configuration_id] +name="merchant_configuration_id" +label="Merchant Configuration ID" +placeholder="Enter Merchant Configuration ID" +required=false type="Text" [taxjar] diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml index b7b57690474..265f06ee749 100644 --- a/crates/connector_configs/toml/sandbox.toml +++ b/crates/connector_configs/toml/sandbox.toml @@ -4045,31 +4045,37 @@ type="Text" name="mcc" label="MCC" placeholder="Enter MCC" -required=true +required=false type="Text" [netcetera.metadata.merchant_country_code] name="merchant_country_code" label="3 digit numeric country code" placeholder="Enter 3 digit numeric country code" -required=true +required=false type="Text" [netcetera.metadata.merchant_name] name="merchant_name" label="Name of the merchant" placeholder="Enter Name of the merchant" -required=true +required=false type="Text" [netcetera.metadata.three_ds_requestor_name] name="three_ds_requestor_name" label="ThreeDS requestor name" placeholder="Enter ThreeDS requestor name" -required=true +required=false type="Text" [netcetera.metadata.three_ds_requestor_id] name="three_ds_requestor_id" label="ThreeDS request id" placeholder="Enter ThreeDS request id" -required=true +required=false +type="Text" +[netcetera.metadata.merchant_configuration_id] +name="merchant_configuration_id" +label="Merchant Configuration ID" +placeholder="Enter Merchant Configuration ID" +required=false type="Text" diff --git a/crates/router/src/connector/netcetera/transformers.rs b/crates/router/src/connector/netcetera/transformers.rs index ab228d95a9e..ab6002ba312 100644 --- a/crates/router/src/connector/netcetera/transformers.rs +++ b/crates/router/src/connector/netcetera/transformers.rs @@ -253,12 +253,13 @@ pub struct NetceteraErrorDetails { #[derive(Debug, Serialize, Deserialize)] pub struct NetceteraMetaData { - pub mcc: String, - pub merchant_country_code: String, - pub merchant_name: String, + pub mcc: Option<String>, + pub merchant_country_code: Option<String>, + pub merchant_name: Option<String>, pub endpoint_prefix: String, - pub three_ds_requestor_name: String, - pub three_ds_requestor_id: String, + pub three_ds_requestor_name: Option<String>, + pub three_ds_requestor_id: Option<String>, + pub merchant_configuration_id: Option<String>, } impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for NetceteraMetaData { @@ -515,13 +516,13 @@ impl TryFrom<&NetceteraRouterData<&types::authentication::ConnectorAuthenticatio .parse_value("NetceteraMetaData") .change_context(errors::ConnectorError::RequestEncodingFailed)?; let merchant_data = netcetera_types::MerchantData { - merchant_configuration_id: None, - mcc: Some(connector_meta_data.mcc), - merchant_country_code: Some(connector_meta_data.merchant_country_code), - merchant_name: Some(connector_meta_data.merchant_name), + merchant_configuration_id: connector_meta_data.merchant_configuration_id, + mcc: connector_meta_data.mcc, + merchant_country_code: connector_meta_data.merchant_country_code, + merchant_name: connector_meta_data.merchant_name, notification_url: request.return_url.clone(), - three_ds_requestor_id: Some(connector_meta_data.three_ds_requestor_id), - three_ds_requestor_name: Some(connector_meta_data.three_ds_requestor_name), + three_ds_requestor_id: connector_meta_data.three_ds_requestor_id, + three_ds_requestor_name: connector_meta_data.three_ds_requestor_name, white_list_status: None, trust_list_status: None, seller_info: None, diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 1803e12f0b2..c995b646ffc 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -6539,7 +6539,7 @@ pub fn validate_mandate_data_and_future_usage( pub enum UnifiedAuthenticationServiceFlow { ClickToPayInitiate, ExternalAuthenticationInitiate { - acquirer_details: authentication::types::AcquirerDetails, + acquirer_details: Option<authentication::types::AcquirerDetails>, card_number: ::cards::CardNumber, token: String, }, @@ -6613,7 +6613,7 @@ pub async fn decide_action_for_unified_authentication_service<F: Clone>( pub enum PaymentExternalAuthenticationFlow { PreAuthenticationFlow { - acquirer_details: authentication::types::AcquirerDetails, + acquirer_details: Option<authentication::types::AcquirerDetails>, card_number: ::cards::CardNumber, token: String, }, @@ -6690,17 +6690,27 @@ pub async fn get_payment_external_authentication_flow_during_confirm<F: Clone>( connector_data.merchant_connector_id.as_ref(), ) .await?; - let acquirer_details: authentication::types::AcquirerDetails = payment_connector_mca + let acquirer_details = payment_connector_mca .get_metadata() - .get_required_value("merchant_connector_account.metadata")? - .peek() .clone() - .parse_value("AcquirerDetails") - .change_context(errors::ApiErrorResponse::PreconditionFailed { - message: - "acquirer_bin and acquirer_merchant_id not found in Payment Connector's Metadata" - .to_string(), - })?; + .and_then(|metadata| { + metadata + .peek() + .clone() + .parse_value::<authentication::types::AcquirerDetails>("AcquirerDetails") + .change_context(errors::ApiErrorResponse::PreconditionFailed { + message: + "acquirer_bin and acquirer_merchant_id not found in Payment Connector's Metadata" + .to_string(), + }) + .inspect_err(|err| { + logger::error!( + "Failed to parse acquirer details from Payment Connector's Metadata: {:?}", + err + ); + }) + .ok() + }); Some(PaymentExternalAuthenticationFlow::PreAuthenticationFlow { card_number, token, diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 6068eba1319..43057855467 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -983,7 +983,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for card_number, token, business_profile, - Some(acquirer_details), + acquirer_details, Some(payment_data.payment_attempt.payment_id.clone()), payment_data.payment_attempt.organization_id.clone(), ) @@ -1267,7 +1267,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for state, pre_auth_response, authentication.clone(), - Some(acquirer_details), + acquirer_details, ).await?; payment_data.authentication = Some(updated_authentication.clone());
feat
add `merchant_configuration_id` in netcetera metadata and make other merchant configurations optional (#7347)
ed2907e141d3ac9c3100ea6d1fccd3fe38a220aa
2023-03-01 23:46:45
bernard-eugine
feat(router): serve OpenAPI docs at `/docs` (#698)
false
diff --git a/Cargo.lock b/Cargo.lock index 02659a51c90..51271d4b794 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1398,6 +1398,26 @@ dependencies = [ "subtle", ] +[[package]] +name = "dirs" +version = "4.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3aa72a6f96ea37bbc5aa912f6788242832f75369bdfdadcb0e38423f100059" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b1d1d91c932ef41c0f2663aa8b0ca0342d444d842c06914aa0a7e352d0bada6" +dependencies = [ + "libc", + "redox_users", + "winapi", +] + [[package]] name = "dlv-list" version = "0.3.0" @@ -2360,6 +2380,16 @@ version = "0.3.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d" +[[package]] +name = "mime_guess" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4192263c238a5f0d0c6bfd21f336a313a4ce1c450542449ca191bb657b4642ef" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -3064,6 +3094,17 @@ dependencies = [ "bitflags", ] +[[package]] +name = "redox_users" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b033d837a7cf162d7993aded9304e30a83213c648b6e389db233191f891e5c2b" +dependencies = [ + "getrandom 0.2.8", + "redox_syscall", + "thiserror", +] + [[package]] name = "regex" version = "1.7.1" @@ -3237,6 +3278,7 @@ dependencies = [ "toml 0.7.2", "url", "utoipa", + "utoipa-swagger-ui", "uuid", "wiremock", ] @@ -3280,6 +3322,41 @@ dependencies = [ "vergen", ] +[[package]] +name = "rust-embed" +version = "6.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "283ffe2f866869428c92e0d61c2f35dfb4355293cdfdc48f49e895c15f1333d1" +dependencies = [ + "rust-embed-impl", + "rust-embed-utils", + "walkdir", +] + +[[package]] +name = "rust-embed-impl" +version = "6.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31ab23d42d71fb9be1b643fe6765d292c5e14d46912d13f3ae2815ca048ea04d" +dependencies = [ + "proc-macro2", + "quote", + "rust-embed-utils", + "shellexpand", + "syn", + "walkdir", +] + +[[package]] +name = "rust-embed-utils" +version = "7.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1669d81dfabd1b5f8e2856b8bbe146c6192b0ba22162edc738ac0a5de18f054" +dependencies = [ + "sha2", + "walkdir", +] + [[package]] name = "rust-ini" version = "0.18.0" @@ -3362,6 +3439,15 @@ version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b4b9743ed687d4b4bcedf9ff5eaa7398495ae14e61cba0a295704edbc7decde" +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + [[package]] name = "schannel" version = "0.1.21" @@ -3612,6 +3698,15 @@ dependencies = [ "lazy_static", ] +[[package]] +name = "shellexpand" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ccc8076840c4da029af4f87e4e8daeb0fca6b87bbb02e10cb60b791450e11e4" +dependencies = [ + "dirs", +] + [[package]] name = "signal-hook" version = "0.3.14" @@ -4248,6 +4343,15 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94" +[[package]] +name = "unicase" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50f37be617794602aabbeee0be4f259dc1778fabe05e2d67ee8f79326d5cb4f6" +dependencies = [ + "version_check", +] + [[package]] name = "unicode-bidi" version = "0.3.8" @@ -4301,9 +4405,9 @@ checksum = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9" [[package]] name = "utoipa" -version = "3.0.1" +version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3920fa753064b1be7842bea26175ffa0dfc4a8f30bcb52b8ff03fddf8889914c" +checksum = "a15f6da6a2b471134ca44b7d18e8a76d73035cf8b3ed24c4dd5ca6a63aa439c5" dependencies = [ "indexmap", "serde", @@ -4313,9 +4417,9 @@ dependencies = [ [[package]] name = "utoipa-gen" -version = "3.0.1" +version = "3.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "720298fac6efca20df9e457e67a1eab41a20d1c3101380b5c4dca1ca60ae0062" +checksum = "6f2e33027986a4707b3f5c37ed01b33d0e5a53da30204b52ff18f80600f1d0ec" dependencies = [ "proc-macro-error", "proc-macro2", @@ -4323,6 +4427,22 @@ dependencies = [ "syn", ] +[[package]] +name = "utoipa-swagger-ui" +version = "3.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae3d4f4da6408f0f20ff58196ed619c94306ab32635aeca3d3fa0768c0bd0de2" +dependencies = [ + "actix-web", + "mime_guess", + "regex", + "rust-embed", + "serde", + "serde_json", + "utoipa", + "zip", +] + [[package]] name = "uuid" version = "1.2.2" @@ -4379,6 +4499,17 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca" +[[package]] +name = "walkdir" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "808cf2735cd4b6866113f648b791c6adc5714537bc222d9347bb203386ffda56" +dependencies = [ + "same-file", + "winapi", + "winapi-util", +] + [[package]] name = "want" version = "0.3.0" @@ -4660,6 +4791,18 @@ version = "1.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c394b5bd0c6f669e7275d9c20aa90ae064cb22e75a1cad54e1b34088034b149f" +[[package]] +name = "zip" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0445d0fbc924bb93539b4316c11afb121ea39296f99a3c4c9edad09e3658cdef" +dependencies = [ + "byteorder", + "crc32fast", + "crossbeam-utils", + "flate2", +] + [[package]] name = "zstd" version = "0.12.2+zstd.1.5.2" diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index c50967e7a92..ed3464b933f 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -17,7 +17,7 @@ serde_json = "1.0.91" strum = { version = "0.24.1", features = ["derive"] } time = { version = "0.3.17", features = ["serde", "serde-well-known", "std"] } url = { version = "2.3.1", features = ["serde"] } -utoipa = { version = "3.0.1", features = ["preserve_order"] } +utoipa = { version = "3.0.3", features = ["preserve_order"] } # First party crates common_utils = { version = "0.1.0", path = "../common_utils" } diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index f9a110ca460..c0f0fd1b9ea 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -10,7 +10,7 @@ license = "Apache-2.0" build = "src/build.rs" [features] -default = ["kv_store", "stripe", "oltp", "olap","accounts_cache"] +default = ["kv_store", "stripe", "oltp", "olap", "accounts_cache"] kms = ["aws-config", "aws-sdk-kms"] basilisk = ["josekit"] stripe = ["dep:serde_qs"] @@ -74,7 +74,8 @@ thiserror = "1.0.38" time = { version = "0.3.17", features = ["serde", "serde-well-known", "std"] } tokio = { version = "1.25.0", features = ["macros", "rt-multi-thread"] } url = { version = "2.3.1", features = ["serde"] } -utoipa = { version = "3.0.1", features = ["preserve_order", "time"] } +utoipa = { version = "3.0.3", features = ["preserve_order", "time"] } +utoipa-swagger-ui = { version = "3.0.2", features = ["actix-web"] } uuid = { version = "1.2.2", features = ["serde", "v4"] } # First party crates diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index f74cd89a192..120e1566cc7 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -78,6 +78,15 @@ pub fn mk_app( > { let mut server_app = get_application_builder(request_body_limit); + #[cfg(feature = "openapi")] + { + use utoipa::OpenApi; + server_app = server_app.service( + utoipa_swagger_ui::SwaggerUi::new("/docs/{_:.*}") + .url("/docs/openapi.json", openapi::ApiDoc::openapi()), + ); + } + #[cfg(any(feature = "olap", feature = "oltp"))] { server_app = server_app diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index 9873b60d558..654abe33bb2 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -57,7 +57,7 @@ Never share your secret api keys. Keep them guarded and secure. (name = "Mandates", description = "Manage mandates"), (name = "Customers", description = "Create and manage customers"), (name = "Payment Methods", description = "Create and manage payment methods of customers"), - (name = "API Key", description = "Create and manage API Keys"), + // (name = "API Key", description = "Create and manage API Keys"), ), paths( crate::routes::refunds::refunds_create, @@ -95,11 +95,11 @@ Never share your secret api keys. Keep them guarded and secure. crate::routes::customers::customers_retrieve, crate::routes::customers::customers_update, crate::routes::customers::customers_delete, - crate::routes::api_keys::api_key_create, - crate::routes::api_keys::api_key_retrieve, - crate::routes::api_keys::api_key_update, - crate::routes::api_keys::api_key_revoke, - crate::routes::api_keys::api_key_list, + // crate::routes::api_keys::api_key_create, + // crate::routes::api_keys::api_key_retrieve, + // crate::routes::api_keys::api_key_update, + // crate::routes::api_keys::api_key_revoke, + // crate::routes::api_keys::api_key_list, ), components(schemas( crate::types::api::refunds::RefundRequest, diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index dc09a2214e0..f40a71374c2 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -8,8 +8,7 @@ use crate::{ types::api::admin, }; -// ### Merchant Account - Create - +/// Merchant Account - Create /// /// Create a new account for a merchant and the merchant could be a seller or retailer or client who likes to receive and send payments. #[utoipa::path( @@ -40,8 +39,7 @@ pub async fn merchant_account_create( .await } -// Merchant Account - Retrieve - +/// Merchant Account - Retrieve /// /// Retrieve a merchant account details. #[utoipa::path( @@ -76,8 +74,7 @@ pub async fn retrieve_merchant_account( .await } -// Merchant Account - Update - +/// Merchant Account - Update /// /// To update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc #[utoipa::path( @@ -111,8 +108,7 @@ pub async fn update_merchant_account( .await } -// Merchant Account - Delete - +/// Merchant Account - Delete /// /// To delete a merchant account #[utoipa::path( @@ -148,8 +144,7 @@ pub async fn delete_merchant_account( .await } -// PaymentsConnectors - Create - +/// PaymentsConnectors - Create /// /// Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[utoipa::path( @@ -182,8 +177,7 @@ pub async fn payment_connector_create( .await } -// Payment Connector - Retrieve - +/// Payment Connector - Retrieve /// /// Retrieve Payment Connector Details #[utoipa::path( @@ -226,8 +220,7 @@ pub async fn payment_connector_retrieve( .await } -// Payment Connector - List - +/// Payment Connector - List /// /// List Payment Connector Details for the merchant #[utoipa::path( @@ -262,8 +255,7 @@ pub async fn payment_connector_list( .await } -// Payment Connector - Update - +/// Payment Connector - Update /// /// To update an existing Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc. #[utoipa::path( @@ -303,8 +295,7 @@ pub async fn payment_connector_update( .await } -// Payment Connector - Delete - +/// Payment Connector - Delete /// /// Delete or Detach a Payment Connector from Merchant Account #[utoipa::path( @@ -347,8 +338,7 @@ pub async fn payment_connector_delete( .await } -// Merchant Account - Toggle KV - +/// Merchant Account - Toggle KV /// /// Toggle KV mode for the Merchant Account #[instrument(skip_all)] @@ -372,8 +362,7 @@ pub async fn merchant_account_toggle_kv( .await } -// Merchant Account - KV Status - +/// Merchant Account - KV Status /// /// Toggle KV mode for the Merchant Account #[instrument(skip_all)] diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index bf7e494c2ac..af5b7b0433f 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -8,8 +8,7 @@ use crate::{ types::api::customers, }; -// Create Customer - +/// Create Customer /// /// Create a customer object and store the customer details to be reused for future payments. Incase the customer already exists in the system, this API will respond with the customer details. #[utoipa::path( @@ -40,8 +39,7 @@ pub async fn customers_create( .await } -// Retrieve Customer - +/// Retrieve Customer /// /// Retrieve a customer's details. #[utoipa::path( @@ -83,8 +81,7 @@ pub async fn customers_retrieve( .await } -// Update Customer - +/// Update Customer /// /// Updates the customer's details in a customer object. #[utoipa::path( @@ -119,8 +116,7 @@ pub async fn customers_update( .await } -// Delete Customer - +/// Delete Customer /// /// Delete a customer record. #[utoipa::path( diff --git a/crates/router/src/routes/mandates.rs b/crates/router/src/routes/mandates.rs index 70643a52f8c..1cf8ff98586 100644 --- a/crates/router/src/routes/mandates.rs +++ b/crates/router/src/routes/mandates.rs @@ -8,8 +8,7 @@ use crate::{ types::api::mandates, }; -// Mandates - Retrieve Mandate - +/// Mandates - Retrieve Mandate /// /// Retrieve a mandate #[utoipa::path( @@ -46,8 +45,7 @@ pub async fn get_mandate( .await } -// Mandates - Revoke Mandate - +/// Mandates - Revoke Mandate /// /// Revoke a mandate #[utoipa::path( diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 6872df9fe92..9df0c9d6ce6 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -8,8 +8,7 @@ use crate::{ types::api::payment_methods::{self, PaymentMethodId}, }; -// PaymentMethods - Create - +/// PaymentMethods - Create /// /// To create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants #[utoipa::path( @@ -42,8 +41,7 @@ pub async fn create_payment_method_api( .await } -// List payment methods for a Merchant - +/// List payment methods for a Merchant /// /// To filter and list the applicable payment methods for a particular Merchant ID #[utoipa::path( @@ -90,8 +88,7 @@ pub async fn list_payment_method_api( .await } -// List payment methods for a Customer - +/// List payment methods for a Customer /// /// To filter and list the applicable payment methods for a particular Customer ID #[utoipa::path( @@ -142,8 +139,7 @@ pub async fn list_customer_payment_method_api( .await } -// Payment Method - Retrieve - +/// Payment Method - Retrieve /// /// To retrieve a payment method #[utoipa::path( @@ -181,8 +177,7 @@ pub async fn payment_method_retrieve_api( .await } -// Payment Method - Update - +/// Payment Method - Update /// /// To update an existing payment method attached to a customer object. This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments #[utoipa::path( @@ -226,8 +221,7 @@ pub async fn payment_method_update_api( .await } -// Payment Method - Delete - +/// Payment Method - Delete /// /// Delete payment method #[utoipa::path( diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index d15674ea9e0..88b8a754d62 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -9,8 +9,7 @@ use crate::{ types::api::{self as api_types, enums as api_enums, payments as payment_types}, }; -// Payments - Create - +/// Payments - Create /// /// To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture #[utoipa::path( @@ -105,8 +104,7 @@ pub async fn payments_start( .await } -// Payments - Retrieve - +/// Payments - Retrieve /// /// To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment #[utoipa::path( @@ -163,8 +161,7 @@ pub async fn payments_retrieve( .await } -// Payments - Update - +/// Payments - Update /// /// To update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created #[utoipa::path( @@ -223,8 +220,7 @@ pub async fn payments_update( .await } -// Payments - Confirm - +/// Payments - Confirm /// /// This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments Create API #[utoipa::path( @@ -284,8 +280,7 @@ pub async fn payments_confirm( .await } -// Payments - Capture - +/// Payments - Capture /// /// To capture the funds for an uncaptured payment #[utoipa::path( @@ -335,8 +330,7 @@ pub async fn payments_capture( .await } -// Payments - Session token - +/// Payments - Session token /// /// To create the session object or to get session token for wallets #[utoipa::path( @@ -434,8 +428,7 @@ pub async fn payments_redirect_response( .await } -// Payments - Cancel - +/// Payments - Cancel /// /// A Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action #[utoipa::path( @@ -484,8 +477,7 @@ pub async fn payments_cancel( .await } -// Payments - List - +/// Payments - List /// /// To list the payments #[utoipa::path( diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs index c8ebcd5d503..c1b60ab43a9 100644 --- a/crates/router/src/routes/refunds.rs +++ b/crates/router/src/routes/refunds.rs @@ -8,8 +8,7 @@ use crate::{ types::api::refunds, }; -// Refunds - Create - +/// Refunds - Create /// /// To create a refund against an already processed payment #[utoipa::path( @@ -41,8 +40,7 @@ pub async fn refunds_create( .await } -// Refunds - Retrieve - +/// Refunds - Retrieve /// /// To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment #[utoipa::path( @@ -80,8 +78,7 @@ pub async fn refunds_retrieve( .await } -// Refunds - Update - +/// Refunds - Update /// /// To update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields #[utoipa::path( @@ -120,8 +117,7 @@ pub async fn refunds_update( .await } -// Refunds - List - +/// Refunds - List /// /// To list the refunds associated with a payment_id or with the merchant, if payment_id is not provided #[utoipa::path( diff --git a/openapi/generated.json b/openapi/generated.json index 00c46988fc4..659dbe5f8fc 100644 --- a/openapi/generated.json +++ b/openapi/generated.json @@ -25,8 +25,8 @@ "tags": [ "Merchant Account" ], - "summary": "", - "description": "\nCreate a new account for a merchant and the merchant could be a seller or retailer or client who likes to receive and send payments.", + "summary": "Merchant Account - Create", + "description": "Merchant Account - Create\n\nCreate a new account for a merchant and the merchant could be a seller or retailer or client who likes to receive and send payments.", "operationId": "Create a Merchant Account", "requestBody": { "content": { @@ -66,8 +66,8 @@ "tags": [ "Merchant Account" ], - "summary": "", - "description": "\nRetrieve a merchant account details.", + "summary": "Merchant Account - Retrieve", + "description": "Merchant Account - Retrieve\n\nRetrieve a merchant account details.", "operationId": "Retrieve a Merchant Account", "parameters": [ { @@ -106,8 +106,8 @@ "tags": [ "Merchant Account" ], - "summary": "", - "description": "\nTo update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc", + "summary": "Merchant Account - Update", + "description": "Merchant Account - Update\n\nTo update an existing merchant account. Helpful in updating merchant details such as email, contact details, or other configuration details like webhook, routing algorithm etc", "operationId": "Update a Merchant Account", "parameters": [ { @@ -156,8 +156,8 @@ "tags": [ "Merchant Account" ], - "summary": "", - "description": "\nTo delete a merchant account", + "summary": "Merchant Account - Delete", + "description": "Merchant Account - Delete\n\nTo delete a merchant account", "operationId": "Delete a Merchant Account", "parameters": [ { @@ -198,8 +198,8 @@ "tags": [ "Merchant Connector Account" ], - "summary": "", - "description": "\nList Payment Connector Details for the merchant", + "summary": "Payment Connector - List", + "description": "Payment Connector - List\n\nList Payment Connector Details for the merchant", "operationId": "List all Merchant Connectors", "parameters": [ { @@ -244,8 +244,8 @@ "tags": [ "Merchant Connector Account" ], - "summary": "", - "description": "\nCreate a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", + "summary": "PaymentsConnectors - Create", + "description": "PaymentsConnectors - Create\n\nCreate a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc.\"", "operationId": "Create a Merchant Connector", "requestBody": { "content": { @@ -285,8 +285,8 @@ "tags": [ "Merchant Connector Account" ], - "summary": "", - "description": "\nRetrieve Payment Connector Details", + "summary": "Payment Connector - Retrieve", + "description": "Payment Connector - Retrieve\n\nRetrieve Payment Connector Details", "operationId": "Retrieve a Merchant Connector", "parameters": [ { @@ -338,8 +338,8 @@ "tags": [ "Merchant Connector Account" ], - "summary": "", - "description": "\nTo update an existing Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc.", + "summary": "Payment Connector - Update", + "description": "Payment Connector - Update\n\nTo update an existing Payment Connector. Helpful in enabling / disabling different payment methods and other settings for the connector etc.", "operationId": "Update a Merchant Connector", "parameters": [ { @@ -401,8 +401,8 @@ "tags": [ "Merchant Connector Account" ], - "summary": "", - "description": "\nDelete or Detach a Payment Connector from Merchant Account", + "summary": "Payment Connector - Delete", + "description": "Payment Connector - Delete\n\nDelete or Detach a Payment Connector from Merchant Account", "operationId": "Delete a Merchant Connector", "parameters": [ { @@ -451,241 +451,13 @@ ] } }, - "/api_keys/{merchant_id)": { - "post": { - "tags": [ - "API Key" - ], - "summary": "API Key - Create", - "description": "API Key - Create\n\nCreate a new API Key for accessing our APIs from your servers. The plaintext API Key will be\ndisplayed only once on creation, so ensure you store it securely.", - "operationId": "Create an API Key", - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateApiKeyRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "API Key created", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/CreateApiKeyResponse" - } - } - } - }, - "400": { - "description": "Invalid data" - } - }, - "deprecated": false, - "security": [ - { - "admin_api_key": [] - } - ] - } - }, - "/api_keys/{merchant_id)/{key_id}": { - "delete": { - "tags": [ - "API Key" - ], - "summary": "API Key - Revoke", - "description": "API Key - Revoke\n\nRevoke the specified API Key. Once revoked, the API Key can no longer be used for\nauthenticating with our APIs.", - "operationId": "Revoke an API Key", - "parameters": [ - { - "name": "key_id", - "in": "path", - "description": "The unique identifier for the API Key", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "API Key revoked", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RevokeApiKeyResponse" - } - } - } - }, - "404": { - "description": "API Key not found" - } - }, - "deprecated": false, - "security": [ - { - "admin_api_key": [] - } - ] - } - }, - "/api_keys/{merchant_id}/list": { - "get": { - "tags": [ - "API Key" - ], - "summary": "API Key - List", - "description": "API Key - List\n\nList all API Keys associated with your merchant account.", - "operationId": "List all API Keys associated with a merchant account", - "parameters": [ - { - "name": "limit", - "in": "query", - "description": "The maximum number of API Keys to include in the response", - "required": false, - "schema": { - "type": "integer", - "format": "int64" - } - }, - { - "name": "skip", - "in": "query", - "description": "The number of API Keys to skip when retrieving the list of API keys.", - "required": false, - "schema": { - "type": "integer", - "format": "int64" - } - } - ], - "responses": { - "200": { - "description": "List of API Keys retrieved successfully", - "content": { - "application/json": { - "schema": { - "type": "array", - "items": { - "$ref": "#/components/schemas/RetrieveApiKeyResponse" - } - } - } - } - } - }, - "deprecated": false, - "security": [ - { - "admin_api_key": [] - } - ] - } - }, - "/api_keys/{merchant_id}/{key_id}": { - "get": { - "tags": [ - "API Key" - ], - "summary": "API Key - Retrieve", - "description": "API Key - Retrieve\n\nRetrieve information about the specified API Key.", - "operationId": "Retrieve an API Key", - "parameters": [ - { - "name": "key_id", - "in": "path", - "description": "The unique identifier for the API Key", - "required": true, - "schema": { - "type": "string" - } - } - ], - "responses": { - "200": { - "description": "API Key retrieved", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RetrieveApiKeyResponse" - } - } - } - }, - "404": { - "description": "API Key not found" - } - }, - "deprecated": false, - "security": [ - { - "admin_api_key": [] - } - ] - }, - "post": { - "tags": [ - "API Key" - ], - "summary": "API Key - Update", - "description": "API Key - Update\n\nUpdate information for the specified API Key.", - "operationId": "Update an API Key", - "parameters": [ - { - "name": "key_id", - "in": "path", - "description": "The unique identifier for the API Key", - "required": true, - "schema": { - "type": "string" - } - } - ], - "requestBody": { - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/UpdateApiKeyRequest" - } - } - }, - "required": true - }, - "responses": { - "200": { - "description": "API Key updated", - "content": { - "application/json": { - "schema": { - "$ref": "#/components/schemas/RetrieveApiKeyResponse" - } - } - } - }, - "404": { - "description": "API Key not found" - } - }, - "deprecated": false, - "security": [ - { - "admin_api_key": [] - } - ] - } - }, "/customers": { "post": { "tags": [ "Customers" ], - "summary": "", - "description": "\nCreate a customer object and store the customer details to be reused for future payments. Incase the customer already exists in the system, this API will respond with the customer details.", + "summary": "Create Customer", + "description": "Create Customer\n\nCreate a customer object and store the customer details to be reused for future payments. Incase the customer already exists in the system, this API will respond with the customer details.", "operationId": "Create a Customer", "requestBody": { "content": { @@ -725,8 +497,8 @@ "tags": [ "Customers" ], - "summary": "", - "description": "\nRetrieve a customer's details.", + "summary": "Retrieve Customer", + "description": "Retrieve Customer\n\nRetrieve a customer's details.", "operationId": "Retrieve a Customer", "parameters": [ { @@ -768,8 +540,8 @@ "tags": [ "Customers" ], - "summary": "", - "description": "\nUpdates the customer's details in a customer object.", + "summary": "Update Customer", + "description": "Update Customer\n\nUpdates the customer's details in a customer object.", "operationId": "Update a Customer", "parameters": [ { @@ -818,8 +590,8 @@ "tags": [ "Customers" ], - "summary": "", - "description": "\nDelete a customer record.", + "summary": "Delete Customer", + "description": "Delete Customer\n\nDelete a customer record.", "operationId": "Delete a Customer", "parameters": [ { @@ -860,8 +632,8 @@ "tags": [ "Mandates" ], - "summary": "", - "description": "\nRevoke a mandate", + "summary": "Mandates - Revoke Mandate", + "description": "Mandates - Revoke Mandate\n\nRevoke a mandate", "operationId": "Revoke a Mandate", "parameters": [ { @@ -902,8 +674,8 @@ "tags": [ "Mandates" ], - "summary": "", - "description": "\nRetrieve a mandate", + "summary": "Mandates - Retrieve Mandate", + "description": "Mandates - Retrieve Mandate\n\nRetrieve a mandate", "operationId": "Retrieve a Mandate", "parameters": [ { @@ -944,8 +716,8 @@ "tags": [ "Payment Methods" ], - "summary": "", - "description": "\nTo create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants", + "summary": "PaymentMethods - Create", + "description": "PaymentMethods - Create\n\nTo create a payment method against a customer object. In case of cards, this API could be used only by PCI compliant merchants", "operationId": "Create a Payment Method", "requestBody": { "content": { @@ -985,8 +757,8 @@ "tags": [ "Payment Methods" ], - "summary": "", - "description": "\nTo filter and list the applicable payment methods for a particular Merchant ID", + "summary": "List payment methods for a Merchant", + "description": "List payment methods for a Merchant\n\nTo filter and list the applicable payment methods for a particular Merchant ID", "operationId": "List all Payment Methods for a Merchant", "parameters": [ { @@ -1095,8 +867,8 @@ "tags": [ "Payment Methods" ], - "summary": "", - "description": "\nTo filter and list the applicable payment methods for a particular Customer ID", + "summary": "List payment methods for a Customer", + "description": "List payment methods for a Customer\n\nTo filter and list the applicable payment methods for a particular Customer ID", "operationId": "List all Payment Methods for a Customer", "parameters": [ { @@ -1205,8 +977,8 @@ "tags": [ "Payment Methods" ], - "summary": "", - "description": "\nTo retrieve a payment method", + "summary": "Payment Method - Retrieve", + "description": "Payment Method - Retrieve\n\nTo retrieve a payment method", "operationId": "Retrieve a Payment method", "parameters": [ { @@ -1245,8 +1017,8 @@ "tags": [ "Payment Methods" ], - "summary": "", - "description": "\nTo update an existing payment method attached to a customer object. This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments", + "summary": "Payment Method - Update", + "description": "Payment Method - Update\n\nTo update an existing payment method attached to a customer object. This API is useful for use cases such as updating the card number for expired cards to prevent discontinuity in recurring payments", "operationId": "Update a Payment method", "parameters": [ { @@ -1295,8 +1067,8 @@ "tags": [ "Payment Methods" ], - "summary": "", - "description": "\nDelete payment method", + "summary": "Payment Method - Delete", + "description": "Payment Method - Delete\n\nDelete payment method", "operationId": "Delete a Payment method", "parameters": [ { @@ -1337,8 +1109,8 @@ "tags": [ "Payments" ], - "summary": "", - "description": "\nTo process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture", + "summary": "Payments - Create", + "description": "Payments - Create\n\nTo process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture", "operationId": "Create a Payment", "requestBody": { "content": { @@ -1378,8 +1150,8 @@ "tags": [ "Payments" ], - "summary": "", - "description": "\nTo list the payments", + "summary": "Payments - List", + "description": "Payments - List\n\nTo list the payments", "operationId": "List all Payments", "parameters": [ { @@ -1491,8 +1263,8 @@ "tags": [ "Payments" ], - "summary": "", - "description": "\nTo create the session object or to get session token for wallets", + "summary": "Payments - Session token", + "description": "Payments - Session token\n\nTo create the session object or to get session token for wallets", "operationId": "Create Session tokens for a Payment", "requestBody": { "content": { @@ -1532,8 +1304,8 @@ "tags": [ "Payments" ], - "summary": "", - "description": "\nTo retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment", + "summary": "Payments - Retrieve", + "description": "Payments - Retrieve\n\nTo retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment", "operationId": "Retrieve a Payment", "parameters": [ { @@ -1585,8 +1357,8 @@ "tags": [ "Payments" ], - "summary": "", - "description": "\nTo update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created", + "summary": "Payments - Update", + "description": "Payments - Update\n\nTo update the properties of a PaymentIntent object. This may include attaching a payment method, or attaching customer object or metadata fields after the Payment is created", "operationId": "Update a Payment", "parameters": [ { @@ -1640,8 +1412,8 @@ "tags": [ "Payments" ], - "summary": "", - "description": "\nA Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action", + "summary": "Payments - Cancel", + "description": "Payments - Cancel\n\nA Payment could can be cancelled when it is in one of these statuses: requires_payment_method, requires_capture, requires_confirmation, requires_customer_action", "operationId": "Cancel a Payment", "parameters": [ { @@ -1685,8 +1457,8 @@ "tags": [ "Payments" ], - "summary": "", - "description": "\nTo capture the funds for an uncaptured payment", + "summary": "Payments - Capture", + "description": "Payments - Capture\n\nTo capture the funds for an uncaptured payment", "operationId": "Capture a Payment", "parameters": [ { @@ -1737,8 +1509,8 @@ "tags": [ "Payments" ], - "summary": "", - "description": "\nThis API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments Create API", + "summary": "Payments - Confirm", + "description": "Payments - Confirm\n\nThis API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments Create API", "operationId": "Confirm a Payment", "parameters": [ { @@ -1792,8 +1564,8 @@ "tags": [ "Refunds" ], - "summary": "", - "description": "\nTo create a refund against an already processed payment", + "summary": "Refunds - Create", + "description": "Refunds - Create\n\nTo create a refund against an already processed payment", "operationId": "Create a Refund", "requestBody": { "content": { @@ -1833,8 +1605,8 @@ "tags": [ "Refunds" ], - "summary": "", - "description": "\nTo list the refunds associated with a payment_id or with the merchant, if payment_id is not provided", + "summary": "Refunds - List", + "description": "Refunds - List\n\nTo list the refunds associated with a payment_id or with the merchant, if payment_id is not provided", "operationId": "List all Refunds", "parameters": [ { @@ -1935,8 +1707,8 @@ "tags": [ "Refunds" ], - "summary": "", - "description": "\nTo retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment", + "summary": "Refunds - Retrieve", + "description": "Refunds - Retrieve\n\nTo retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment", "operationId": "Retrieve a Refund", "parameters": [ { @@ -1975,8 +1747,8 @@ "tags": [ "Refunds" ], - "summary": "", - "description": "\nTo update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields", + "summary": "Refunds - Update", + "description": "Refunds - Update\n\nTo update the properties of a Refund object. This may include attaching a reason for the refund or metadata fields", "operationId": "Update a Refund", "parameters": [ { @@ -2046,9 +1818,9 @@ "list": { "type": "array", "items": { - "type": "string", - "description": "List of countries of the provided type" - } + "type": "string" + }, + "description": "List of countries of the provided type" } } }, @@ -2067,7 +1839,8 @@ "type": "array", "items": { "$ref": "#/components/schemas/Currency" - } + }, + "description": "List of currencies of the provided type" } } }, @@ -2201,16 +1974,16 @@ "merchant_capabilities": { "type": "array", "items": { - "type": "string", - "description": "The list of merchant capabilities(ex: whether capable of 3ds or no-3ds)" - } + "type": "string" + }, + "description": "The list of merchant capabilities(ex: whether capable of 3ds or no-3ds)" }, "supported_networks": { "type": "array", "items": { - "type": "string", - "description": "The list of supported networks" - } + "type": "string" + }, + "description": "The list of supported networks" } } }, @@ -2288,7 +2061,8 @@ ], "properties": { "payment_data": { - "$ref": "#/components/schemas/ApplepayPaymentData" + "type": "string", + "description": "The payment data of Apple pay" }, "payment_method": { "$ref": "#/components/schemas/ApplepayPaymentMethod" @@ -2299,54 +2073,6 @@ } } }, - "ApplepayHeader": { - "type": "object", - "required": [ - "public_key_hash", - "ephemeral_public_key", - "transaction_id" - ], - "properties": { - "public_key_hash": { - "type": "string", - "description": "The public key hash used" - }, - "ephemeral_public_key": { - "type": "string", - "description": "The ephemeral public key used" - }, - "transaction_id": { - "type": "string", - "description": "The unique identifier for the transaction" - } - } - }, - "ApplepayPaymentData": { - "type": "object", - "required": [ - "data", - "signature", - "header", - "version" - ], - "properties": { - "data": { - "type": "string", - "description": "The data of Apple pay payment" - }, - "signature": { - "type": "string", - "description": "A string which represents the properties of a payment" - }, - "header": { - "$ref": "#/components/schemas/ApplepayHeader" - }, - "version": { - "type": "string", - "description": "The Apple Pay version used" - } - } - }, "ApplepayPaymentMethod": { "type": "object", "required": [ @@ -2433,6 +2159,7 @@ "easybank_ag", "erste_bank_und_sparkassen", "hypo_alpeadriabank_international_ag", + "hypo_noe_lb_fur_niederosterreich_u_wien", "hypo_oberosterreich_salzburg_steiermark", "hypo_tirol_bank_ag", "hypo_vorarlberg_bank_ag", @@ -2697,10 +2424,12 @@ "checkout", "cybersource", "dummy", + "bambora", "dlocal", "fiserv", "globalpay", "klarna", + "multisafepay", "nuvei", "payu", "rapyd", @@ -2834,7 +2563,8 @@ "$ref": "#/components/schemas/WebhookDetails" }, "routing_algorithm": { - "type": "object" + "type": "object", + "description": "The routing algorithm to be used for routing payments to desired connectors" }, "sub_merchants_enabled": { "type": "boolean", @@ -2865,7 +2595,8 @@ "example": true }, "metadata": { - "type": "object" + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object." }, "publishable_key": { "type": "string", @@ -2903,12 +2634,18 @@ "$ref": "#/components/schemas/CardDetail" }, "metadata": { - "type": "object" + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object." }, "customer_id": { "type": "string", "description": "The unique identifier of the customer.", "example": "cus_meowerunwiuwiwqw" + }, + "card_network": { + "type": "string", + "description": "The card network", + "example": "Visa" } } }, @@ -2918,6 +2655,7 @@ "AED", "ALL", "AMD", + "ANG", "ARS", "AUD", "AWG", @@ -3121,6 +2859,7 @@ "items": { "$ref": "#/components/schemas/PaymentExperience" }, + "description": "Type of payment experience enabled with the connector", "example": [ "redirect_to_url" ] @@ -3129,7 +2868,8 @@ "$ref": "#/components/schemas/CardDetailFromLocker" }, "metadata": { - "type": "object" + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object." }, "created": { "type": "string", @@ -3180,10 +2920,12 @@ "maxLength": 255 }, "address": { - "type": "object" + "type": "object", + "description": "The address for the customer" }, "metadata": { - "type": "object" + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500\ncharacters long. Metadata is useful for storing additional, structured information on an\nobject." } } }, @@ -3231,7 +2973,8 @@ "maxLength": 255 }, "address": { - "type": "object" + "type": "object", + "description": "The address for the customer" }, "created_at": { "type": "string", @@ -3240,7 +2983,8 @@ "example": "2023-01-18T11:04:09.922Z" }, "metadata": { - "type": "object" + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500\ncharacters long. Metadata is useful for storing additional, structured information on an\nobject." } } }, @@ -3326,16 +3070,16 @@ "allowed_auth_methods": { "type": "array", "items": { - "type": "string", - "description": "The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc)" - } + "type": "string" + }, + "description": "The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc)" }, "allowed_card_networks": { "type": "array", "items": { - "type": "string", - "description": "The list of allowed card networks (ex: AMEX,JCB etc)" - } + "type": "string" + }, + "description": "The list of allowed card networks (ex: AMEX,JCB etc)" } } }, @@ -3403,7 +3147,8 @@ "type": "array", "items": { "$ref": "#/components/schemas/GpayAllowedPaymentMethods" - } + }, + "description": "List of the allowed payment meythods" }, "transaction_info": { "$ref": "#/components/schemas/GpayTransactionInfo" @@ -3546,31 +3291,15 @@ "ListCustomerPaymentMethodsResponse": { "type": "object", "required": [ - "enabled_payment_methods", "customer_payment_methods" ], "properties": { - "enabled_payment_methods": { - "type": "array", - "items": { - "$ref": "#/components/schemas/ListPaymentMethod" - }, - "example": [ - { - "payment_experience": null, - "payment_method": "wallet", - "payment_method_issuers": [ - "labore magna ipsum", - "aute" - ] - } - ] - }, "customer_payment_methods": { "type": "array", "items": { "$ref": "#/components/schemas/CustomerPaymentMethod" - } + }, + "description": "List of payment methods for customer" } } }, @@ -3588,6 +3317,7 @@ "items": { "$ref": "#/components/schemas/PaymentMethodType" }, + "description": "This is a sub-category of payment method.", "example": [ "credit" ] @@ -3610,6 +3340,7 @@ "items": { "$ref": "#/components/schemas/ListPaymentMethod" }, + "description": "Information about the payment method", "example": [ { "payment_experience": null, @@ -3852,7 +3583,8 @@ "example": "AH3423bkjbkjdsfbkj" }, "metadata": { - "type": "object" + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object." }, "locker_id": { "type": "string", @@ -3935,7 +3667,8 @@ "Metadata": { "allOf": [ { - "type": "object" + "type": "object", + "description": "Any other metadata that is to be provided" }, { "type": "object", @@ -4133,7 +3866,8 @@ "example": "mca_5apGeP94tMts6rg3U3kR" }, "connector_account_details": { - "type": "object" + "type": "object", + "description": "Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object." }, "test_mode": { "type": "boolean", @@ -4152,6 +3886,7 @@ "items": { "$ref": "#/components/schemas/PaymentMethodsEnabled" }, + "description": "Refers to the Parent Merchant ID if the merchant being created is a sub-merchant", "example": [ { "accepted_countries": { @@ -4190,7 +3925,8 @@ ] }, "metadata": { - "type": "object" + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object." } } }, @@ -4316,7 +4052,8 @@ "enum": [ "card", "pay_later", - "wallet" + "wallet", + "bank_redirect" ] }, "PaymentMethodData": { @@ -4431,12 +4168,14 @@ "items": { "$ref": "#/components/schemas/PaymentExperience" }, + "description": "Type of payment experience enabled with the connector", "example": [ "redirect_to_url" ] }, "metadata": { - "type": "object" + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object." }, "created": { "type": "string", @@ -4478,6 +4217,7 @@ "items": { "$ref": "#/components/schemas/PaymentMethodType" }, + "description": "Subtype of payment method", "example": [ "credit" ] @@ -4687,7 +4427,8 @@ "maxLength": 255 }, "browser_info": { - "type": "object" + "type": "object", + "description": "Additional details required by 3DS 2.0" }, "payment_experience": { "$ref": "#/components/schemas/PaymentExperience" @@ -4776,7 +4517,8 @@ "type": "array", "items": { "$ref": "#/components/schemas/RefundResponse" - } + }, + "description": "List of refund that happened on this intent" }, "mandate_id": { "type": "string", @@ -4822,7 +4564,8 @@ "$ref": "#/components/schemas/Address" }, "metadata": { - "type": "object" + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object." }, "email": { "type": "string", @@ -4935,7 +4678,8 @@ "type": "array", "items": { "$ref": "#/components/schemas/SupportedWallets" - } + }, + "description": "The list of the supported wallets" } } }, @@ -4959,7 +4703,8 @@ "type": "array", "items": { "$ref": "#/components/schemas/SessionToken" - } + }, + "description": "The list of session token object" } } }, @@ -5064,7 +4809,8 @@ "type": "array", "items": { "$ref": "#/components/schemas/RefundResponse" - } + }, + "description": "The list of refund response" } } }, @@ -5111,7 +4857,8 @@ "$ref": "#/components/schemas/RefundType" }, "metadata": { - "type": "object" + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object." } } }, @@ -5150,7 +4897,8 @@ "$ref": "#/components/schemas/RefundStatus" }, "metadata": { - "type": "object" + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object" }, "error_message": { "type": "string", @@ -5199,7 +4947,8 @@ "maxLength": 255 }, "metadata": { - "type": "object" + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object." } } }, @@ -5415,8 +5164,12 @@ "card": { "$ref": "#/components/schemas/CardDetail" }, + "card_network": { + "$ref": "#/components/schemas/CardNetwork" + }, "metadata": { - "type": "object" + "type": "object", + "description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object." } } }, @@ -5567,10 +5320,6 @@ { "name": "Payment Methods", "description": "Create and manage payment methods of customers" - }, - { - "name": "API Key", - "description": "Create and manage API Keys" } ] } \ No newline at end of file
feat
serve OpenAPI docs at `/docs` (#698)
4138c8f5431dea4fe400b47c919c68b7c8f7b402
2023-10-27 17:35:44
Hangsaai
refactor(connector): [Airwallex] Remove default case handling (#2703)
false
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs index 51258643c64..031a8276bb0 100644 --- a/crates/router/src/connector/airwallex/transformers.rs +++ b/crates/router/src/connector/airwallex/transformers.rs @@ -186,8 +186,18 @@ impl TryFrom<&AirwallexRouterData<&types::PaymentsAuthorizeRouterData>> })) } api::PaymentMethodData::Wallet(ref wallet_data) => get_wallet_details(wallet_data), - _ => Err(errors::ConnectorError::NotImplemented( - "Unknown payment method".to_string(), + api::PaymentMethodData::PayLater(_) + | api::PaymentMethodData::BankRedirect(_) + | api::PaymentMethodData::BankDebit(_) + | api::PaymentMethodData::BankTransfer(_) + | api::PaymentMethodData::CardRedirect(_) + | api::PaymentMethodData::Crypto(_) + | api::PaymentMethodData::MandatePayment + | api::PaymentMethodData::Reward + | api::PaymentMethodData::Upi(_) + | api::PaymentMethodData::Voucher(_) + | api::PaymentMethodData::GiftCard(_) => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("airwallex"), )), }?; @@ -215,9 +225,35 @@ fn get_wallet_details( payment_method_type: AirwallexPaymentType::Googlepay, })) } - _ => Err(errors::ConnectorError::NotImplemented( - "Payment method".to_string(), - ))?, + api_models::payments::WalletData::AliPayQr(_) + | api_models::payments::WalletData::AliPayRedirect(_) + | api_models::payments::WalletData::AliPayHkRedirect(_) + | api_models::payments::WalletData::MomoRedirect(_) + | api_models::payments::WalletData::KakaoPayRedirect(_) + | api_models::payments::WalletData::GoPayRedirect(_) + | api_models::payments::WalletData::GcashRedirect(_) + | api_models::payments::WalletData::ApplePay(_) + | api_models::payments::WalletData::ApplePayRedirect(_) + | api_models::payments::WalletData::ApplePayThirdPartySdk(_) + | api_models::payments::WalletData::DanaRedirect {} + | api_models::payments::WalletData::GooglePayRedirect(_) + | api_models::payments::WalletData::GooglePayThirdPartySdk(_) + | api_models::payments::WalletData::MbWayRedirect(_) + | api_models::payments::WalletData::MobilePayRedirect(_) + | api_models::payments::WalletData::PaypalRedirect(_) + | api_models::payments::WalletData::PaypalSdk(_) + | api_models::payments::WalletData::SamsungPay(_) + | api_models::payments::WalletData::TwintRedirect {} + | api_models::payments::WalletData::VippsRedirect {} + | api_models::payments::WalletData::TouchNGoRedirect(_) + | api_models::payments::WalletData::WeChatPayRedirect(_) + | api_models::payments::WalletData::WeChatPayQr(_) + | api_models::payments::WalletData::CashappQr(_) + | api_models::payments::WalletData::SwishQr(_) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("airwallex"), + ))? + } }; Ok(wallet_details) }
refactor
[Airwallex] Remove default case handling (#2703)
295d41abba3ff02d7942534163ebc24ae57adf44
2023-06-28 18:56:55
Sakil Mostak
test(connector): [Bambora] Add tests for 3DS (#1254)
false
diff --git a/crates/router/tests/connectors/bambora_ui.rs b/crates/router/tests/connectors/bambora_ui.rs new file mode 100644 index 00000000000..86b2f22352d --- /dev/null +++ b/crates/router/tests/connectors/bambora_ui.rs @@ -0,0 +1,38 @@ +use serial_test::serial; +use thirtyfour::{prelude::*, WebDriver}; + +use crate::{selenium::*, tester}; + +struct BamboraSeleniumTest; + +impl SeleniumTest for BamboraSeleniumTest { + fn get_connector_name(&self) -> String { + "bambora".to_string() + } +} + +async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> { + let mycon = BamboraSeleniumTest {}; + mycon + .make_redirection_payment( + c, + vec![ + Event::Trigger(Trigger::Goto(&format!("{CHEKOUT_BASE_URL}/saved/33"))), + Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))), + Event::Trigger(Trigger::Click(By::Id("continue-transaction"))), + Event::Assert(Assert::IsPresent("Google")), + Event::Assert(Assert::Contains( + Selector::QueryParamStr, + "status=succeeded", + )), + ], + ) + .await?; + Ok(()) +} + +#[test] +#[serial] +fn should_make_3ds_payment_test() { + tester!(should_make_3ds_payment); +} diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs index 30c526d3576..bce32484151 100644 --- a/crates/router/tests/connectors/main.rs +++ b/crates/router/tests/connectors/main.rs @@ -11,6 +11,7 @@ mod adyen_uk_ui; mod airwallex; mod authorizedotnet; mod bambora; +mod bambora_ui; mod bitpay; mod bluesnap; mod cashtocode;
test
[Bambora] Add tests for 3DS (#1254)
449c9cfe557b3540e4ad25e48e012b531eb232fd
2024-11-05 13:11:10
Tommy shu
fix(refunds): remove to schema from refund aggregate response and exclude it from open api documentation (#6405)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 0c467902603..4c1559fe099 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -17045,22 +17045,6 @@ } } }, - "RefundAggregateResponse": { - "type": "object", - "required": [ - "status_with_count" - ], - "properties": { - "status_with_count": { - "type": "object", - "description": "The list of refund status with their count", - "additionalProperties": { - "type": "integer", - "format": "int64" - } - } - } - }, "RefundErrorDetails": { "type": "object", "required": [ diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index 9d92c28d55f..f86664d459f 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -21824,22 +21824,6 @@ } } }, - "RefundAggregateResponse": { - "type": "object", - "required": [ - "status_with_count" - ], - "properties": { - "status_with_count": { - "type": "object", - "description": "The list of refund status with their count", - "additionalProperties": { - "type": "integer", - "format": "int64" - } - } - } - }, "RefundListRequest": { "allOf": [ { diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs index f42eb8095b4..ac5e5cb4618 100644 --- a/crates/api_models/src/refunds.rs +++ b/crates/api_models/src/refunds.rs @@ -346,7 +346,7 @@ pub struct RefundListFilters { pub refund_status: Vec<enums::RefundStatus>, } -#[derive(Clone, Debug, serde::Serialize, ToSchema)] +#[derive(Clone, Debug, serde::Serialize)] pub struct RefundAggregateResponse { /// The list of refund status with their count pub status_with_count: HashMap<enums::RefundStatus, i64>, diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index 15845667999..75d1bb9f275 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -491,7 +491,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodCollectLinkResponse, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, - api_models::refunds::RefundAggregateResponse, api_models::payments::AmountFilter, api_models::mandates::MandateRevokedResponse, api_models::mandates::MandateResponse, diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs index dacaedd9763..40f694b80a2 100644 --- a/crates/openapi/src/openapi_v2.rs +++ b/crates/openapi/src/openapi_v2.rs @@ -433,7 +433,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payment_methods::PaymentMethodCollectLinkResponse, api_models::refunds::RefundListRequest, api_models::refunds::RefundListResponse, - api_models::refunds::RefundAggregateResponse, api_models::payments::AmountFilter, api_models::mandates::MandateRevokedResponse, api_models::mandates::MandateResponse,
fix
remove to schema from refund aggregate response and exclude it from open api documentation (#6405)
3606723a9baf2ea8b61909bd5c801bde7aead5bc
2023-05-16 16:23:25
Sanchith Hegde
ci: specify cache key for commit message and migration verification checks (#1153)
false
diff --git a/.github/workflows/conventional-commit-check.yml b/.github/workflows/conventional-commit-check.yml index 1e9e17f40e9..aeb6e405a24 100644 --- a/.github/workflows/conventional-commit-check.yml +++ b/.github/workflows/conventional-commit-check.yml @@ -1,12 +1,20 @@ name: Conventional Commit Message Check on: - pull_request: + # This is a dangerous event trigger as it causes the workflow to run in the + # context of the target repository. + # Avoid checking out the head of the pull request or building code from the + # pull request whenever this trigger is used. + # Since we only label pull requests, do not have a checkout step in this + # workflow, and restrict permissions on the token, this is an acceptable + # use of this trigger. + pull_request_target: types: - opened - edited - reopened - ready_for_review + - synchronize merge_group: types: @@ -14,7 +22,7 @@ on: permissions: # Reference: https://github.com/cli/cli/issues/6274 - repository-projects: write + repository-projects: read pull-requests: write env: @@ -39,7 +47,12 @@ jobs: - uses: Swatinem/[email protected] with: - key: "pr_title_check" + # We can use a single cache entry for all runs of this check, as only cocogitto needs to be cached + shared-key: "pr_title_check" + # We don't build any crates in this repository, no need to cache target directories + cache-targets: "false" + # Save cache even if commit message verification fails. + # Only failure not considered is failures in installing cocogitto itself. cache-on-failure: "true" - name: Install cocogitto @@ -51,7 +64,7 @@ jobs: if: ${{ github.event_name == 'pull_request' }} shell: bash continue-on-error: true - run: cog verify "${{ github.event.pull_request.title }}" + run: cog verify '${{ github.event.pull_request.title }}' - name: Verify commit message follows conventional commit standards id: commit_message_check @@ -59,7 +72,7 @@ jobs: shell: bash # Fail on error, we don't have context about PR information to update labels continue-on-error: false - run: cog verify "${{ github.event.merge_group.head_commit.message }}" + run: cog verify '${{ github.event.merge_group.head_commit.message }}' # GitHub CLI returns a successful error code even if the PR has the label already attached - name: Attach 'S-conventions-not-followed' label if PR title check failed diff --git a/.github/workflows/migration-check.yaml b/.github/workflows/migration-check.yaml index b913949d6c8..81d9f42188b 100644 --- a/.github/workflows/migration-check.yaml +++ b/.github/workflows/migration-check.yaml @@ -48,6 +48,14 @@ jobs: toolchain: stable - uses: Swatinem/[email protected] + with: + # We can use a single cache entry for all runs of this check, as only diesel CLI needs to be cached + shared-key: "migration_verify" + # We don't build any crates in this repository, no need to cache target directories + cache-targets: "false" + # Save cache even if migration verification fails. + # Only failure not considered is failures in installing diesel CLI itself. + cache-on-failure: "true" - name: Install diesel_cli shell: bash
ci
specify cache key for commit message and migration verification checks (#1153)
248d3c79f00a257dab759d15776de1887445cf07
2024-01-31 05:49:11
github-actions
chore(version): 2024.01.31.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index dd32d16d596..00cfdc5a015 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,29 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.01.31.0 + +### Features + +- **connector:** [noon] add revoke mandate ([#3487](https://github.com/juspay/hyperswitch/pull/3487)) ([`b5bc8c4`](https://github.com/juspay/hyperswitch/commit/b5bc8c4e7cfdde8251ed0e2e3835ed5e3f1435c4)) + +### Bug Fixes + +- **connector:** [BOA/Cybersource] Handle Invalid Api Secret ([#3485](https://github.com/juspay/hyperswitch/pull/3485)) ([`224c1cf`](https://github.com/juspay/hyperswitch/commit/224c1cf2a421441433097618cc1dd3db224d5915)) +- **user:** Change permission for sample data ([#3462](https://github.com/juspay/hyperswitch/pull/3462)) ([`610c1c5`](https://github.com/juspay/hyperswitch/commit/610c1c575253ddf7a1a31ef941efaae2dd676b48)) + +### Refactors + +- **core:** Restrict requires_customer_action in confirm ([#3235](https://github.com/juspay/hyperswitch/pull/3235)) ([`d2accde`](https://github.com/juspay/hyperswitch/commit/d2accdef410319733d6174057bdca468bde1ae83)) + +### Miscellaneous Tasks + +- **config:** [ADYEN] Add configs for PIX in WASM ([#3498](https://github.com/juspay/hyperswitch/pull/3498)) ([`9821935`](https://github.com/juspay/hyperswitch/commit/9821935933e178765b3b0d0bcbfdf4ab041c3bc2)) + +**Full Changelog:** [`2024.01.30.1...2024.01.31.0`](https://github.com/juspay/hyperswitch/compare/2024.01.30.1...2024.01.31.0) + +- - - + ## 2024.01.30.1 ### Features
chore
2024.01.31.0
5d8895c06412ff05d5abbfefaaa4933db853eb13
2023-06-05 18:39:14
Sampras Lopes
docs(CONTRIBUTING): update commit guidelines (#1351)
false
diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index 388c795ff10..40d5eb052b7 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -174,11 +174,19 @@ There is no limit to the number of commits any single Pull Request may have, and many contributors find it easier to review changes that are split across multiple commits. -That said, if you have a number of commits that are "checkpoints" and don't -represent a single logical change, please squash those together. +Please adhere to the general guideline that you should never force push to a +publicly shared branch. +Once you have opened your pull request, you should consider your branch publicly shared. +Instead of force pushing you can just add incremental commits; +this is generally easier on your reviewers. +If you need to pick up changes from main, you can merge main into your branch. + +A reviewer might ask you to rebase a long-running pull request +in which case force pushing is okay for that request. + +Note that squashing at the end of the review process should also not be done, +that can be done when the pull request is integrated via GitHub. -Note that multiple commits often get squashed when they are landed (see the -notes about [commit squashing](#commit-squashing)). #### Commit message guidelines
docs
update commit guidelines (#1351)
d0c1f96d7c994a2dbc90cb2d2abcb403f6f2b2c0
2023-01-19 19:25:06
ItsMeShashank
fix(router): update basilisk card save format when fetching from legacy locker (#429)
false
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index aac70e5c69c..9922af121c4 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -18,7 +18,7 @@ use crate::{ storage::{self, enums}, transformers::ForeignInto, }, - utils::{BytesExt, ConnectorResponseExt, OptionExt}, + utils::{self, BytesExt, ConnectorResponseExt, OptionExt}, }; #[instrument(skip_all)] @@ -699,24 +699,72 @@ impl BasiliskCardSupport { .clone() .expose_option() .unwrap_or_default(); - let card_detail = api::CardDetail { - card_number: card_number.into(), - card_exp_month: card_exp_month.into(), - card_exp_year: card_exp_year.into(), - card_holder_name: Some(card_holder_name.into()), - }; - let db = &*state.store; - mock_add_card( - db, - payment_token, - &card_detail, + let value1 = payment_methods::mk_card_value1( + card_number, + card_exp_year, + card_exp_month, + Some(card_holder_name), + None, + None, + None, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Error getting Value1 for locker")?; + let value2 = payment_methods::mk_card_value2( + None, None, + None, + Some(pm.customer_id.to_string()), Some(pm.payment_method_id.to_string()), - Some(&pm.customer_id), ) - .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Add Card Failed")?; + .attach_printable("Error getting Value2 for locker")?; + + let value1 = vault::VaultPaymentMethod::Card(value1); + let value2 = vault::VaultPaymentMethod::Card(value2); + + let value1 = utils::Encode::<vault::VaultPaymentMethod>::encode_to_string_of_json(&value1) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Wrapped value1 construction failed when saving card to locker")?; + + let value2 = utils::Encode::<vault::VaultPaymentMethod>::encode_to_string_of_json(&value2) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Wrapped value2 construction failed when saving card to locker")?; + + let db_value = vault::MockTokenizeDBValue { value1, value2 }; + + let value_string = + utils::Encode::<vault::MockTokenizeDBValue>::encode_to_string_of_json(&db_value) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable( + "Mock tokenize value construction failed when saving card to locker", + )?; + + let db = &*state.store; + + let already_present = db.find_config_by_key(payment_token).await; + + if already_present.is_err() { + let config = storage::ConfigNew { + key: payment_token.to_string(), + config: value_string, + }; + + db.insert_config(config) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Mock tokenization save to db failed")?; + } else { + let config_update = storage::ConfigUpdate::Update { + config: Some(value_string), + }; + + db.update_config_by_key(payment_token, config_update) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Mock tokenization db update failed")?; + } + Ok(card) } } @@ -775,6 +823,18 @@ impl BasiliskCardSupport { ) .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error getting Value2 for locker")?; + + let value1 = vault::VaultPaymentMethod::Card(value1); + let value2 = vault::VaultPaymentMethod::Card(value2); + + let value1 = utils::Encode::<vault::VaultPaymentMethod>::encode_to_string_of_json(&value1) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Wrapped value1 construction failed when saving card to locker")?; + + let value2 = utils::Encode::<vault::VaultPaymentMethod>::encode_to_string_of_json(&value2) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Wrapped value2 construction failed when saving card to locker")?; + vault::create_tokenize(state, value1, Some(value2), payment_token.to_string()).await?; Ok(card) }
fix
update basilisk card save format when fetching from legacy locker (#429)
b46a921ccb05dc194253659c12991d9df7abe71e
2025-01-08 13:19:14
Kashif
chore(dynamic-fields): [Worldpay] update dynamic fields for payments (#7002)
false
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 9e42aec4a51..4f6327d74b7 100644 --- a/crates/router/src/configs/defaults/payment_connector_required_fields.rs +++ b/crates/router/src/configs/defaults/payment_connector_required_fields.rs @@ -3224,7 +3224,8 @@ impl Default for settings::RequiredFields { enums::Connector::Worldpay, RequiredFieldFinal { mandate: HashMap::new(), - non_mandate: { + non_mandate: HashMap::new(), + common: { let mut pmd_fields = HashMap::from([ ( "payment_method_data.card.card_number".to_string(), @@ -3257,7 +3258,6 @@ impl Default for settings::RequiredFields { pmd_fields.extend(get_worldpay_billing_required_fields()); pmd_fields }, - common: HashMap::new(), } ), ( @@ -6420,7 +6420,8 @@ impl Default for settings::RequiredFields { enums::Connector::Worldpay, RequiredFieldFinal { mandate: HashMap::new(), - non_mandate: { + non_mandate: HashMap::new(), + common: { let mut pmd_fields = HashMap::from([ ( "payment_method_data.card.card_number".to_string(), @@ -6453,7 +6454,6 @@ impl Default for settings::RequiredFields { pmd_fields.extend(get_worldpay_billing_required_fields()); pmd_fields }, - common: HashMap::new(), } ), ( @@ -12840,18 +12840,18 @@ impl Default for settings::RequiredFields { pub fn get_worldpay_billing_required_fields() -> HashMap<String, RequiredFieldInfo> { HashMap::from([ ( - "billing.address.zip".to_string(), + "billing.address.line1".to_string(), RequiredFieldInfo { - required_field: "billing.address.zip".to_string(), - display_name: "zip".to_string(), - field_type: enums::FieldType::UserAddressPincode, + required_field: "payment_method_data.billing.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserAddressLine1, value: None, }, ), ( "billing.address.country".to_string(), RequiredFieldInfo { - required_field: "billing.address.country".to_string(), + required_field: "payment_method_data.billing.address.country".to_string(), display_name: "country".to_string(), field_type: enums::FieldType::UserAddressCountry { options: vec![ @@ -12994,5 +12994,14 @@ pub fn get_worldpay_billing_required_fields() -> HashMap<String, RequiredFieldIn value: None, }, ), + ( + "billing.address.city".to_string(), + RequiredFieldInfo { + required_field: "payment_method_data.billing.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserAddressCity, + value: None, + }, + ), ]) }
chore
[Worldpay] update dynamic fields for payments (#7002)
537630f00482939d4c0b49c643dee3763fe0e046
2024-08-01 19:14:21
Sanchith Hegde
feat(business_profile): introduce domain models for business profile v1 and v2 APIs (#5497)
false
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index b6b6f219bd8..f829d2e48fe 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -17,13 +17,14 @@ frm = [] olap = [] openapi = ["common_enums/openapi", "olap", "recon", "dummy_connector", "olap"] recon = [] -v1 =[] +v1 = [] v2 = [] -routing_v2 = [] -merchant_connector_account_v2 = [] +business_profile_v2 = [] customer_v2 = [] merchant_account_v2 = [] +merchant_connector_account_v2 = [] payment_v2 = [] +routing_v2 = [] [dependencies] actix-web = { version = "4.5.1", optional = true } diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 985f7451c28..6ec400ec81c 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -3054,3 +3054,24 @@ pub enum PayoutRetryType { SingleConnector, MultiConnector, } + +#[derive( + Clone, + Copy, + Debug, + Eq, + PartialEq, + serde::Deserialize, + serde::Serialize, + strum::Display, + strum::EnumString, + ToSchema, + Hash, +)] +#[router_derive::diesel_enum(storage_type = "db_enum")] +#[serde(rename_all = "snake_case")] +#[strum(serialize_all = "snake_case")] +pub enum OrderFulfillmentTimeOrigin { + Create, + Confirm, +} diff --git a/crates/diesel_models/Cargo.toml b/crates/diesel_models/Cargo.toml index d021ccfff37..6b63f76cdaa 100644 --- a/crates/diesel_models/Cargo.toml +++ b/crates/diesel_models/Cargo.toml @@ -8,10 +8,11 @@ readme = "README.md" license.workspace = true [features] -default = ["kv_store", "v1"] +default = ["kv_store", "v1"] kv_store = [] v1 =[] v2 = [] +business_profile_v2 = [] customer_v2 = [] merchant_account_v2 = [] merchant_connector_account_v2 = [] diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs index 30f6780e360..cc4dbe6b605 100644 --- a/crates/diesel_models/src/business_profile.rs +++ b/crates/diesel_models/src/business_profile.rs @@ -1,8 +1,25 @@ +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +use common_enums::OrderFulfillmentTimeOrigin; use common_utils::{encryption::Encryption, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] use crate::schema::business_profile; +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +use crate::schema_v2::business_profile; +/// Note: The order of fields in the struct is important. +/// This should be in the same order as the fields in the schema.rs file, otherwise the code will +/// not compile +/// If two adjacent columns have the same type, then the compiler will not throw any error, but the +/// fields read / written will be interchanged +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] #[derive( Clone, Debug, @@ -46,6 +63,10 @@ pub struct BusinessProfile { pub outgoing_webhook_custom_http_headers: Option<Encryption>, } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] #[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile, primary_key(profile_id))] pub struct BusinessProfileNew { @@ -80,11 +101,15 @@ pub struct BusinessProfileNew { pub outgoing_webhook_custom_http_headers: Option<Encryption>, } -#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)] +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] #[diesel(table_name = business_profile)] pub struct BusinessProfileUpdateInternal { pub profile_name: Option<String>, - pub modified_at: Option<time::PrimitiveDateTime>, + pub modified_at: time::PrimitiveDateTime, pub return_url: Option<String>, pub enable_payment_response_hash: Option<bool>, pub payment_response_hash_key: Option<String>, @@ -111,11 +136,14 @@ pub struct BusinessProfileUpdateInternal { pub outgoing_webhook_custom_http_headers: Option<Encryption>, } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub enum BusinessProfileUpdate { Update { profile_name: Option<String>, - modified_at: Option<time::PrimitiveDateTime>, return_url: Option<String>, enable_payment_response_hash: Option<bool>, payment_response_hash_key: Option<String>, @@ -139,6 +167,10 @@ pub enum BusinessProfileUpdate { is_connector_agnostic_mit_enabled: Option<bool>, outgoing_webhook_custom_http_headers: Option<Encryption>, }, + RoutingAlgorithmUpdate { + routing_algorithm: Option<serde_json::Value>, + payout_routing_algorithm: Option<serde_json::Value>, + }, ExtendedCardInfoUpdate { is_extended_card_info_enabled: Option<bool>, }, @@ -147,12 +179,17 @@ pub enum BusinessProfileUpdate { }, } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { fn from(business_profile_update: BusinessProfileUpdate) -> Self { + let now = common_utils::date_time::now(); + match business_profile_update { BusinessProfileUpdate::Update { profile_name, - modified_at, return_url, enable_payment_response_hash, payment_response_hash_key, @@ -177,7 +214,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { outgoing_webhook_custom_http_headers, } => Self { profile_name, - modified_at, + modified_at: now, return_url, enable_payment_response_hash, payment_response_hash_key, @@ -194,30 +231,113 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { session_expiry, authentication_connector_details, payout_link_config, + is_extended_card_info_enabled: None, extended_card_info_config, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector, is_connector_agnostic_mit_enabled, outgoing_webhook_custom_http_headers, - ..Default::default() + }, + BusinessProfileUpdate::RoutingAlgorithmUpdate { + routing_algorithm, + payout_routing_algorithm, + } => Self { + profile_name: None, + modified_at: now, + return_url: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + webhook_details: None, + metadata: None, + routing_algorithm, + intent_fulfillment_time: None, + frm_routing_algorithm: None, + payout_routing_algorithm, + is_recon_enabled: None, + applepay_verified_domains: None, + payment_link_config: None, + session_expiry: None, + authentication_connector_details: None, + payout_link_config: None, + is_extended_card_info_enabled: None, + extended_card_info_config: None, + is_connector_agnostic_mit_enabled: None, + use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, + outgoing_webhook_custom_http_headers: None, }, BusinessProfileUpdate::ExtendedCardInfoUpdate { is_extended_card_info_enabled, } => Self { + profile_name: None, + modified_at: now, + return_url: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + webhook_details: None, + metadata: None, + routing_algorithm: None, + intent_fulfillment_time: None, + frm_routing_algorithm: None, + payout_routing_algorithm: None, + is_recon_enabled: None, + applepay_verified_domains: None, + payment_link_config: None, + session_expiry: None, + authentication_connector_details: None, + payout_link_config: None, is_extended_card_info_enabled, - ..Default::default() + extended_card_info_config: None, + is_connector_agnostic_mit_enabled: None, + use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, + outgoing_webhook_custom_http_headers: None, }, BusinessProfileUpdate::ConnectorAgnosticMitUpdate { is_connector_agnostic_mit_enabled, } => Self { + profile_name: None, + modified_at: now, + return_url: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + webhook_details: None, + metadata: None, + routing_algorithm: None, + intent_fulfillment_time: None, + frm_routing_algorithm: None, + payout_routing_algorithm: None, + is_recon_enabled: None, + applepay_verified_domains: None, + payment_link_config: None, + session_expiry: None, + authentication_connector_details: None, + payout_link_config: None, + is_extended_card_info_enabled: None, + extended_card_info_config: None, is_connector_agnostic_mit_enabled, - ..Default::default() + use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, + outgoing_webhook_custom_http_headers: None, }, } } } +// This is being used only in the `BusinessProfileInterface` implementation for `MockDb`. +// This can be removed once the `BusinessProfileInterface` trait has been updated to use the domain +// model instead. +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] impl From<BusinessProfileNew> for BusinessProfile { fn from(new: BusinessProfileNew) -> Self { Self { @@ -255,11 +375,15 @@ impl From<BusinessProfileNew> for BusinessProfile { } } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] impl BusinessProfileUpdate { pub fn apply_changeset(self, source: BusinessProfile) -> BusinessProfile { let BusinessProfileUpdateInternal { profile_name, - modified_at: _, + modified_at, return_url, enable_payment_response_hash, payment_response_hash_key, @@ -285,34 +409,497 @@ impl BusinessProfileUpdate { outgoing_webhook_custom_http_headers, } = self.into(); BusinessProfile { + profile_id: source.profile_id, + merchant_id: source.merchant_id, profile_name: profile_name.unwrap_or(source.profile_name), - modified_at: common_utils::date_time::now(), - return_url, + created_at: source.created_at, + modified_at, + return_url: return_url.or(source.return_url), enable_payment_response_hash: enable_payment_response_hash .unwrap_or(source.enable_payment_response_hash), - payment_response_hash_key, + payment_response_hash_key: payment_response_hash_key + .or(source.payment_response_hash_key), redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post .unwrap_or(source.redirect_to_merchant_with_http_post), + webhook_details: webhook_details.or(source.webhook_details), + metadata: metadata.or(source.metadata), + routing_algorithm: routing_algorithm.or(source.routing_algorithm), + intent_fulfillment_time: intent_fulfillment_time.or(source.intent_fulfillment_time), + frm_routing_algorithm: frm_routing_algorithm.or(source.frm_routing_algorithm), + payout_routing_algorithm: payout_routing_algorithm.or(source.payout_routing_algorithm), + is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled), + applepay_verified_domains: applepay_verified_domains + .or(source.applepay_verified_domains), + payment_link_config: payment_link_config.or(source.payment_link_config), + session_expiry: session_expiry.or(source.session_expiry), + authentication_connector_details: authentication_connector_details + .or(source.authentication_connector_details), + payout_link_config: payout_link_config.or(source.payout_link_config), + is_extended_card_info_enabled: is_extended_card_info_enabled + .or(source.is_extended_card_info_enabled), + is_connector_agnostic_mit_enabled: is_connector_agnostic_mit_enabled + .or(source.is_connector_agnostic_mit_enabled), + extended_card_info_config: extended_card_info_config + .or(source.extended_card_info_config), + use_billing_as_payment_method_billing: use_billing_as_payment_method_billing + .or(source.use_billing_as_payment_method_billing), + collect_shipping_details_from_wallet_connector: + collect_shipping_details_from_wallet_connector + .or(source.collect_shipping_details_from_wallet_connector), + collect_billing_details_from_wallet_connector: + collect_billing_details_from_wallet_connector + .or(source.collect_billing_details_from_wallet_connector), + outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers + .or(source.outgoing_webhook_custom_http_headers), + } + } +} + +/// Note: The order of fields in the struct is important. +/// This should be in the same order as the fields in the schema.rs file, otherwise the code will +/// not compile +/// If two adjacent columns have the same type, then the compiler will not throw any error, but the +/// fields read / written will be interchanged +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +#[derive( + Clone, + Debug, + serde::Deserialize, + serde::Serialize, + Identifiable, + Queryable, + Selectable, + router_derive::DebugAsDisplay, +)] +#[diesel(table_name = business_profile, primary_key(profile_id), check_for_backend(diesel::pg::Pg))] +pub struct BusinessProfile { + pub profile_id: String, + pub merchant_id: common_utils::id_type::MerchantId, + pub profile_name: String, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, + pub return_url: Option<String>, + pub enable_payment_response_hash: bool, + pub payment_response_hash_key: Option<String>, + pub redirect_to_merchant_with_http_post: bool, + pub webhook_details: Option<pii::SecretSerdeValue>, + pub metadata: Option<pii::SecretSerdeValue>, + pub is_recon_enabled: bool, + #[diesel(deserialize_as = super::OptionalDieselArray<String>)] + pub applepay_verified_domains: Option<Vec<String>>, + pub payment_link_config: Option<pii::SecretSerdeValue>, + pub session_expiry: Option<i64>, + pub authentication_connector_details: Option<pii::SecretSerdeValue>, + pub payout_link_config: Option<pii::SecretSerdeValue>, + pub is_extended_card_info_enabled: Option<bool>, + pub extended_card_info_config: Option<pii::SecretSerdeValue>, + pub is_connector_agnostic_mit_enabled: Option<bool>, + pub use_billing_as_payment_method_billing: Option<bool>, + pub collect_shipping_details_from_wallet_connector: Option<bool>, + pub collect_billing_details_from_wallet_connector: Option<bool>, + pub outgoing_webhook_custom_http_headers: Option<Encryption>, + pub routing_algorithm_id: Option<String>, + pub order_fulfillment_time: Option<i64>, + pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>, + pub frm_routing_algorithm_id: Option<String>, + pub payout_routing_algorithm_id: Option<String>, + pub default_fallback_routing: Option<pii::SecretSerdeValue>, +} + +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)] +#[diesel(table_name = business_profile, primary_key(profile_id))] +pub struct BusinessProfileNew { + pub profile_id: String, + pub merchant_id: common_utils::id_type::MerchantId, + pub profile_name: String, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, + pub return_url: Option<String>, + pub enable_payment_response_hash: bool, + pub payment_response_hash_key: Option<String>, + pub redirect_to_merchant_with_http_post: bool, + pub webhook_details: Option<pii::SecretSerdeValue>, + pub metadata: Option<pii::SecretSerdeValue>, + pub is_recon_enabled: bool, + #[diesel(deserialize_as = super::OptionalDieselArray<String>)] + pub applepay_verified_domains: Option<Vec<String>>, + pub payment_link_config: Option<pii::SecretSerdeValue>, + pub session_expiry: Option<i64>, + pub authentication_connector_details: Option<pii::SecretSerdeValue>, + pub payout_link_config: Option<pii::SecretSerdeValue>, + pub is_extended_card_info_enabled: Option<bool>, + pub extended_card_info_config: Option<pii::SecretSerdeValue>, + pub is_connector_agnostic_mit_enabled: Option<bool>, + pub use_billing_as_payment_method_billing: Option<bool>, + pub collect_shipping_details_from_wallet_connector: Option<bool>, + pub collect_billing_details_from_wallet_connector: Option<bool>, + pub outgoing_webhook_custom_http_headers: Option<Encryption>, + pub routing_algorithm_id: Option<String>, + pub order_fulfillment_time: Option<i64>, + pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>, + pub frm_routing_algorithm_id: Option<String>, + pub payout_routing_algorithm_id: Option<String>, + pub default_fallback_routing: Option<pii::SecretSerdeValue>, +} + +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)] +#[diesel(table_name = business_profile)] +pub struct BusinessProfileUpdateInternal { + pub profile_name: Option<String>, + pub modified_at: time::PrimitiveDateTime, + pub return_url: Option<String>, + pub enable_payment_response_hash: Option<bool>, + pub payment_response_hash_key: Option<String>, + pub redirect_to_merchant_with_http_post: Option<bool>, + pub webhook_details: Option<pii::SecretSerdeValue>, + pub metadata: Option<pii::SecretSerdeValue>, + pub is_recon_enabled: Option<bool>, + #[diesel(deserialize_as = super::OptionalDieselArray<String>)] + pub applepay_verified_domains: Option<Vec<String>>, + pub payment_link_config: Option<pii::SecretSerdeValue>, + pub session_expiry: Option<i64>, + pub authentication_connector_details: Option<pii::SecretSerdeValue>, + pub payout_link_config: Option<pii::SecretSerdeValue>, + pub is_extended_card_info_enabled: Option<bool>, + pub extended_card_info_config: Option<pii::SecretSerdeValue>, + pub is_connector_agnostic_mit_enabled: Option<bool>, + pub use_billing_as_payment_method_billing: Option<bool>, + pub collect_shipping_details_from_wallet_connector: Option<bool>, + pub collect_billing_details_from_wallet_connector: Option<bool>, + pub outgoing_webhook_custom_http_headers: Option<Encryption>, + pub routing_algorithm_id: Option<String>, + pub order_fulfillment_time: Option<i64>, + pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>, + pub frm_routing_algorithm_id: Option<String>, + pub payout_routing_algorithm_id: Option<String>, + pub default_fallback_routing: Option<pii::SecretSerdeValue>, +} + +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub enum BusinessProfileUpdate { + Update { + profile_name: Option<String>, + return_url: Option<String>, + enable_payment_response_hash: Option<bool>, + payment_response_hash_key: Option<String>, + redirect_to_merchant_with_http_post: Option<bool>, + webhook_details: Option<pii::SecretSerdeValue>, + metadata: Option<pii::SecretSerdeValue>, + is_recon_enabled: Option<bool>, + applepay_verified_domains: Option<Vec<String>>, + payment_link_config: Option<pii::SecretSerdeValue>, + session_expiry: Option<i64>, + authentication_connector_details: Option<pii::SecretSerdeValue>, + payout_link_config: Option<pii::SecretSerdeValue>, + extended_card_info_config: Option<pii::SecretSerdeValue>, + use_billing_as_payment_method_billing: Option<bool>, + collect_shipping_details_from_wallet_connector: Option<bool>, + collect_billing_details_from_wallet_connector: Option<bool>, + is_connector_agnostic_mit_enabled: Option<bool>, + outgoing_webhook_custom_http_headers: Option<Encryption>, + routing_algorithm_id: Option<String>, + order_fulfillment_time: Option<i64>, + order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>, + frm_routing_algorithm_id: Option<String>, + payout_routing_algorithm_id: Option<String>, + default_fallback_routing: Option<pii::SecretSerdeValue>, + }, + RoutingAlgorithmUpdate { + routing_algorithm_id: Option<String>, + payout_routing_algorithm_id: Option<String>, + }, + ExtendedCardInfoUpdate { + is_extended_card_info_enabled: Option<bool>, + }, + ConnectorAgnosticMitUpdate { + is_connector_agnostic_mit_enabled: Option<bool>, + }, +} + +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { + fn from(business_profile_update: BusinessProfileUpdate) -> Self { + let now = common_utils::date_time::now(); + + match business_profile_update { + BusinessProfileUpdate::Update { + profile_name, + return_url, + enable_payment_response_hash, + payment_response_hash_key, + redirect_to_merchant_with_http_post, + webhook_details, + metadata, + is_recon_enabled, + applepay_verified_domains, + payment_link_config, + session_expiry, + authentication_connector_details, + payout_link_config, + extended_card_info_config, + use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector, + is_connector_agnostic_mit_enabled, + outgoing_webhook_custom_http_headers, + routing_algorithm_id, + order_fulfillment_time, + order_fulfillment_time_origin, + frm_routing_algorithm_id, + payout_routing_algorithm_id, + default_fallback_routing, + } => Self { + profile_name, + modified_at: now, + return_url, + enable_payment_response_hash, + payment_response_hash_key, + redirect_to_merchant_with_http_post, + webhook_details, + metadata, + is_recon_enabled, + applepay_verified_domains, + payment_link_config, + session_expiry, + authentication_connector_details, + payout_link_config, + is_extended_card_info_enabled: None, + extended_card_info_config, + use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector, + is_connector_agnostic_mit_enabled, + outgoing_webhook_custom_http_headers, + routing_algorithm_id, + order_fulfillment_time, + order_fulfillment_time_origin, + frm_routing_algorithm_id, + payout_routing_algorithm_id, + default_fallback_routing, + }, + BusinessProfileUpdate::RoutingAlgorithmUpdate { + routing_algorithm_id, + payout_routing_algorithm_id, + } => Self { + profile_name: None, + modified_at: now, + return_url: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + webhook_details: None, + metadata: None, + is_recon_enabled: None, + applepay_verified_domains: None, + payment_link_config: None, + session_expiry: None, + authentication_connector_details: None, + payout_link_config: None, + is_extended_card_info_enabled: None, + extended_card_info_config: None, + is_connector_agnostic_mit_enabled: None, + use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, + outgoing_webhook_custom_http_headers: None, + routing_algorithm_id, + order_fulfillment_time: None, + order_fulfillment_time_origin: None, + frm_routing_algorithm_id: None, + payout_routing_algorithm_id, + default_fallback_routing: None, + }, + BusinessProfileUpdate::ExtendedCardInfoUpdate { + is_extended_card_info_enabled, + } => Self { + profile_name: None, + modified_at: now, + return_url: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + webhook_details: None, + metadata: None, + is_recon_enabled: None, + applepay_verified_domains: None, + payment_link_config: None, + session_expiry: None, + authentication_connector_details: None, + payout_link_config: None, + is_extended_card_info_enabled, + extended_card_info_config: None, + is_connector_agnostic_mit_enabled: None, + use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, + outgoing_webhook_custom_http_headers: None, + routing_algorithm_id: None, + order_fulfillment_time: None, + order_fulfillment_time_origin: None, + frm_routing_algorithm_id: None, + payout_routing_algorithm_id: None, + default_fallback_routing: None, + }, + BusinessProfileUpdate::ConnectorAgnosticMitUpdate { + is_connector_agnostic_mit_enabled, + } => Self { + profile_name: None, + modified_at: now, + return_url: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + webhook_details: None, + metadata: None, + is_recon_enabled: None, + applepay_verified_domains: None, + payment_link_config: None, + session_expiry: None, + authentication_connector_details: None, + payout_link_config: None, + is_extended_card_info_enabled: None, + extended_card_info_config: None, + is_connector_agnostic_mit_enabled, + use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, + outgoing_webhook_custom_http_headers: None, + routing_algorithm_id: None, + order_fulfillment_time: None, + order_fulfillment_time_origin: None, + frm_routing_algorithm_id: None, + payout_routing_algorithm_id: None, + default_fallback_routing: None, + }, + } + } +} + +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +impl BusinessProfileUpdate { + pub fn apply_changeset(self, source: BusinessProfile) -> BusinessProfile { + let BusinessProfileUpdateInternal { + profile_name, + modified_at, + return_url, + enable_payment_response_hash, + payment_response_hash_key, + redirect_to_merchant_with_http_post, webhook_details, metadata, - routing_algorithm, - intent_fulfillment_time, - frm_routing_algorithm, - payout_routing_algorithm, - is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled), + is_recon_enabled, applepay_verified_domains, payment_link_config, session_expiry, authentication_connector_details, payout_link_config, is_extended_card_info_enabled, - is_connector_agnostic_mit_enabled, extended_card_info_config, + is_connector_agnostic_mit_enabled, use_billing_as_payment_method_billing, collect_shipping_details_from_wallet_connector, collect_billing_details_from_wallet_connector, outgoing_webhook_custom_http_headers, - ..source + routing_algorithm_id, + order_fulfillment_time, + order_fulfillment_time_origin, + frm_routing_algorithm_id, + payout_routing_algorithm_id, + default_fallback_routing, + } = self.into(); + BusinessProfile { + profile_id: source.profile_id, + merchant_id: source.merchant_id, + profile_name: profile_name.unwrap_or(source.profile_name), + created_at: source.created_at, + modified_at, + return_url: return_url.or(source.return_url), + enable_payment_response_hash: enable_payment_response_hash + .unwrap_or(source.enable_payment_response_hash), + payment_response_hash_key: payment_response_hash_key + .or(source.payment_response_hash_key), + redirect_to_merchant_with_http_post: redirect_to_merchant_with_http_post + .unwrap_or(source.redirect_to_merchant_with_http_post), + webhook_details: webhook_details.or(source.webhook_details), + metadata: metadata.or(source.metadata), + is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled), + applepay_verified_domains: applepay_verified_domains + .or(source.applepay_verified_domains), + payment_link_config: payment_link_config.or(source.payment_link_config), + session_expiry: session_expiry.or(source.session_expiry), + authentication_connector_details: authentication_connector_details + .or(source.authentication_connector_details), + payout_link_config: payout_link_config.or(source.payout_link_config), + is_extended_card_info_enabled: is_extended_card_info_enabled + .or(source.is_extended_card_info_enabled), + is_connector_agnostic_mit_enabled: is_connector_agnostic_mit_enabled + .or(source.is_connector_agnostic_mit_enabled), + extended_card_info_config: extended_card_info_config + .or(source.extended_card_info_config), + use_billing_as_payment_method_billing: use_billing_as_payment_method_billing + .or(source.use_billing_as_payment_method_billing), + collect_shipping_details_from_wallet_connector: + collect_shipping_details_from_wallet_connector + .or(source.collect_shipping_details_from_wallet_connector), + collect_billing_details_from_wallet_connector: + collect_billing_details_from_wallet_connector + .or(source.collect_billing_details_from_wallet_connector), + outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers + .or(source.outgoing_webhook_custom_http_headers), + routing_algorithm_id: routing_algorithm_id.or(source.routing_algorithm_id), + order_fulfillment_time: order_fulfillment_time.or(source.order_fulfillment_time), + order_fulfillment_time_origin: order_fulfillment_time_origin + .or(source.order_fulfillment_time_origin), + frm_routing_algorithm_id: frm_routing_algorithm_id.or(source.frm_routing_algorithm_id), + payout_routing_algorithm_id: payout_routing_algorithm_id + .or(source.payout_routing_algorithm_id), + default_fallback_routing: default_fallback_routing.or(source.default_fallback_routing), + } + } +} + +// This is being used only in the `BusinessProfileInterface` implementation for `MockDb`. +// This can be removed once the `BusinessProfileInterface` trait has been updated to use the domain +// model instead. +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +impl From<BusinessProfileNew> for BusinessProfile { + fn from(new: BusinessProfileNew) -> Self { + Self { + profile_id: new.profile_id, + merchant_id: new.merchant_id, + profile_name: new.profile_name, + created_at: new.created_at, + modified_at: new.modified_at, + return_url: new.return_url, + enable_payment_response_hash: new.enable_payment_response_hash, + payment_response_hash_key: new.payment_response_hash_key, + redirect_to_merchant_with_http_post: new.redirect_to_merchant_with_http_post, + webhook_details: new.webhook_details, + metadata: new.metadata, + is_recon_enabled: new.is_recon_enabled, + applepay_verified_domains: new.applepay_verified_domains, + payment_link_config: new.payment_link_config, + session_expiry: new.session_expiry, + authentication_connector_details: new.authentication_connector_details, + payout_link_config: new.payout_link_config, + is_connector_agnostic_mit_enabled: new.is_connector_agnostic_mit_enabled, + is_extended_card_info_enabled: new.is_extended_card_info_enabled, + extended_card_info_config: new.extended_card_info_config, + use_billing_as_payment_method_billing: new.use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector: new + .collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector: new + .collect_billing_details_from_wallet_connector, + outgoing_webhook_custom_http_headers: new.outgoing_webhook_custom_http_headers, + routing_algorithm_id: new.routing_algorithm_id, + order_fulfillment_time: new.order_fulfillment_time, + order_fulfillment_time_origin: new.order_fulfillment_time_origin, + frm_routing_algorithm_id: new.frm_routing_algorithm_id, + payout_routing_algorithm_id: new.payout_routing_algorithm_id, + default_fallback_routing: new.default_fallback_routing, } } } diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs index f0059994cb6..55bfa9f2f23 100644 --- a/crates/diesel_models/src/enums.rs +++ b/crates/diesel_models/src/enums.rs @@ -12,6 +12,7 @@ pub mod diesel_exports { DbFutureUsage as FutureUsage, DbGenericLinkType as GenericLinkType, DbIntentStatus as IntentStatus, DbMandateStatus as MandateStatus, DbMandateType as MandateType, DbMerchantStorageScheme as MerchantStorageScheme, + DbOrderFulfillmentTimeOrigin as OrderFulfillmentTimeOrigin, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode, DbPaymentSource as PaymentSource, DbPaymentType as PaymentType, DbPayoutStatus as PayoutStatus, DbPayoutType as PayoutType, DbProcessTrackerStatus as ProcessTrackerStatus, DbReconStatus as ReconStatus, diff --git a/crates/diesel_models/src/query/business_profile.rs b/crates/diesel_models/src/query/business_profile.rs index e716e45c650..1b8e54e0180 100644 --- a/crates/diesel_models/src/query/business_profile.rs +++ b/crates/diesel_models/src/query/business_profile.rs @@ -1,13 +1,18 @@ use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table}; use super::generics; +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] +use crate::schema::business_profile::dsl; +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +use crate::schema_v2::business_profile::dsl; use crate::{ business_profile::{ BusinessProfile, BusinessProfileNew, BusinessProfileUpdate, BusinessProfileUpdateInternal, }, - errors, - schema::business_profile::dsl, - PgPooledConn, StorageResult, + errors, PgPooledConn, StorageResult, }; impl BusinessProfileNew { diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index 648e6e44652..23f9dff31ea 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -188,10 +188,6 @@ diesel::table! { redirect_to_merchant_with_http_post -> Bool, webhook_details -> Nullable<Json>, metadata -> Nullable<Json>, - routing_algorithm -> Nullable<Json>, - intent_fulfillment_time -> Nullable<Int8>, - frm_routing_algorithm -> Nullable<Jsonb>, - payout_routing_algorithm -> Nullable<Jsonb>, is_recon_enabled -> Bool, applepay_verified_domains -> Nullable<Array<Nullable<Text>>>, payment_link_config -> Nullable<Jsonb>, @@ -205,6 +201,15 @@ diesel::table! { collect_shipping_details_from_wallet_connector -> Nullable<Bool>, collect_billing_details_from_wallet_connector -> Nullable<Bool>, outgoing_webhook_custom_http_headers -> Nullable<Bytea>, + #[max_length = 64] + routing_algorithm_id -> Nullable<Varchar>, + order_fulfillment_time -> Nullable<Int8>, + order_fulfillment_time_origin -> Nullable<OrderFulfillmentTimeOrigin>, + #[max_length = 64] + frm_routing_algorithm_id -> Nullable<Varchar>, + #[max_length = 64] + payout_routing_algorithm_id -> Nullable<Varchar>, + default_fallback_routing -> Nullable<Jsonb>, } } diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml index 662cfcff65d..16ab18b68df 100644 --- a/crates/hyperswitch_domain_models/Cargo.toml +++ b/crates/hyperswitch_domain_models/Cargo.toml @@ -15,6 +15,7 @@ payouts = ["api_models/payouts"] frm = ["api_models/frm"] v2 = ["api_models/v2", "diesel_models/v2"] v1 = ["api_models/v1", "diesel_models/v1"] +business_profile_v2 = ["api_models/business_profile_v2", "diesel_models/business_profile_v2"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2"] merchant_account_v2 = ["api_models/merchant_account_v2", "diesel_models/merchant_account_v2"] merchant_connector_account_v2 = ["api_models/merchant_connector_account_v2", "diesel_models/merchant_connector_account_v2"] diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs new file mode 100644 index 00000000000..e6b2bcbe5b1 --- /dev/null +++ b/crates/hyperswitch_domain_models/src/business_profile.rs @@ -0,0 +1,763 @@ +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +use common_enums::OrderFulfillmentTimeOrigin; +use common_utils::{ + crypto::OptionalEncryptableValue, + date_time, + encryption::Encryption, + errors::{CustomResult, ValidationError}, + pii, + types::keymanager, +}; +use diesel_models::business_profile::BusinessProfileUpdateInternal; +use error_stack::ResultExt; +use masking::{PeekInterface, Secret}; + +use crate::type_encryption::{decrypt_optional, AsyncLift}; + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] +#[derive(Clone, Debug)] +pub struct BusinessProfile { + pub profile_id: String, + pub merchant_id: common_utils::id_type::MerchantId, + pub profile_name: String, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, + pub return_url: Option<String>, + pub enable_payment_response_hash: bool, + pub payment_response_hash_key: Option<String>, + pub redirect_to_merchant_with_http_post: bool, + pub webhook_details: Option<serde_json::Value>, + pub metadata: Option<pii::SecretSerdeValue>, + pub routing_algorithm: Option<serde_json::Value>, + pub intent_fulfillment_time: Option<i64>, + pub frm_routing_algorithm: Option<serde_json::Value>, + pub payout_routing_algorithm: Option<serde_json::Value>, + pub is_recon_enabled: bool, + pub applepay_verified_domains: Option<Vec<String>>, + pub payment_link_config: Option<serde_json::Value>, + pub session_expiry: Option<i64>, + pub authentication_connector_details: Option<serde_json::Value>, + pub payout_link_config: Option<serde_json::Value>, + pub is_extended_card_info_enabled: Option<bool>, + pub extended_card_info_config: Option<pii::SecretSerdeValue>, + pub is_connector_agnostic_mit_enabled: Option<bool>, + pub use_billing_as_payment_method_billing: Option<bool>, + pub collect_shipping_details_from_wallet_connector: Option<bool>, + pub collect_billing_details_from_wallet_connector: Option<bool>, + pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue, +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] +#[derive(Debug)] +pub enum BusinessProfileUpdate { + Update { + profile_name: Option<String>, + return_url: Option<String>, + enable_payment_response_hash: Option<bool>, + payment_response_hash_key: Option<String>, + redirect_to_merchant_with_http_post: Option<bool>, + webhook_details: Option<serde_json::Value>, + metadata: Option<pii::SecretSerdeValue>, + routing_algorithm: Option<serde_json::Value>, + intent_fulfillment_time: Option<i64>, + frm_routing_algorithm: Option<serde_json::Value>, + payout_routing_algorithm: Option<serde_json::Value>, + is_recon_enabled: Option<bool>, + applepay_verified_domains: Option<Vec<String>>, + payment_link_config: Option<serde_json::Value>, + session_expiry: Option<i64>, + authentication_connector_details: Option<serde_json::Value>, + payout_link_config: Option<serde_json::Value>, + extended_card_info_config: Option<pii::SecretSerdeValue>, + use_billing_as_payment_method_billing: Option<bool>, + collect_shipping_details_from_wallet_connector: Option<bool>, + collect_billing_details_from_wallet_connector: Option<bool>, + is_connector_agnostic_mit_enabled: Option<bool>, + outgoing_webhook_custom_http_headers: OptionalEncryptableValue, + }, + RoutingAlgorithmUpdate { + routing_algorithm: Option<serde_json::Value>, + payout_routing_algorithm: Option<serde_json::Value>, + }, + ExtendedCardInfoUpdate { + is_extended_card_info_enabled: Option<bool>, + }, + ConnectorAgnosticMitUpdate { + is_connector_agnostic_mit_enabled: Option<bool>, + }, +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] +impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { + fn from(business_profile_update: BusinessProfileUpdate) -> Self { + let now = date_time::now(); + + match business_profile_update { + BusinessProfileUpdate::Update { + profile_name, + return_url, + enable_payment_response_hash, + payment_response_hash_key, + redirect_to_merchant_with_http_post, + webhook_details, + metadata, + routing_algorithm, + intent_fulfillment_time, + frm_routing_algorithm, + payout_routing_algorithm, + is_recon_enabled, + applepay_verified_domains, + payment_link_config, + session_expiry, + authentication_connector_details, + payout_link_config, + extended_card_info_config, + use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector, + is_connector_agnostic_mit_enabled, + outgoing_webhook_custom_http_headers, + } => Self { + profile_name, + modified_at: now, + return_url, + enable_payment_response_hash, + payment_response_hash_key, + redirect_to_merchant_with_http_post, + webhook_details, + metadata, + routing_algorithm, + intent_fulfillment_time, + frm_routing_algorithm, + payout_routing_algorithm, + is_recon_enabled, + applepay_verified_domains, + payment_link_config, + session_expiry, + authentication_connector_details, + payout_link_config, + is_extended_card_info_enabled: None, + extended_card_info_config, + is_connector_agnostic_mit_enabled, + use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector, + outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers + .map(Encryption::from), + }, + BusinessProfileUpdate::RoutingAlgorithmUpdate { + routing_algorithm, + payout_routing_algorithm, + } => Self { + profile_name: None, + modified_at: now, + return_url: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + webhook_details: None, + metadata: None, + routing_algorithm, + intent_fulfillment_time: None, + frm_routing_algorithm: None, + payout_routing_algorithm, + is_recon_enabled: None, + applepay_verified_domains: None, + payment_link_config: None, + session_expiry: None, + authentication_connector_details: None, + payout_link_config: None, + is_extended_card_info_enabled: None, + extended_card_info_config: None, + is_connector_agnostic_mit_enabled: None, + use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, + outgoing_webhook_custom_http_headers: None, + }, + BusinessProfileUpdate::ExtendedCardInfoUpdate { + is_extended_card_info_enabled, + } => Self { + profile_name: None, + modified_at: now, + return_url: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + webhook_details: None, + metadata: None, + routing_algorithm: None, + intent_fulfillment_time: None, + frm_routing_algorithm: None, + payout_routing_algorithm: None, + is_recon_enabled: None, + applepay_verified_domains: None, + payment_link_config: None, + session_expiry: None, + authentication_connector_details: None, + payout_link_config: None, + is_extended_card_info_enabled, + extended_card_info_config: None, + is_connector_agnostic_mit_enabled: None, + use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, + outgoing_webhook_custom_http_headers: None, + }, + BusinessProfileUpdate::ConnectorAgnosticMitUpdate { + is_connector_agnostic_mit_enabled, + } => Self { + profile_name: None, + modified_at: now, + return_url: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + webhook_details: None, + metadata: None, + routing_algorithm: None, + intent_fulfillment_time: None, + frm_routing_algorithm: None, + payout_routing_algorithm: None, + is_recon_enabled: None, + applepay_verified_domains: None, + payment_link_config: None, + session_expiry: None, + authentication_connector_details: None, + payout_link_config: None, + is_extended_card_info_enabled: None, + extended_card_info_config: None, + is_connector_agnostic_mit_enabled, + use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, + outgoing_webhook_custom_http_headers: None, + }, + } + } +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "business_profile_v2") +))] +#[async_trait::async_trait] +impl super::behaviour::Conversion for BusinessProfile { + type DstType = diesel_models::business_profile::BusinessProfile; + type NewDstType = diesel_models::business_profile::BusinessProfileNew; + + async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + Ok(diesel_models::business_profile::BusinessProfile { + profile_id: self.profile_id, + merchant_id: self.merchant_id, + profile_name: self.profile_name, + created_at: self.created_at, + modified_at: self.modified_at, + return_url: self.return_url, + enable_payment_response_hash: self.enable_payment_response_hash, + payment_response_hash_key: self.payment_response_hash_key, + redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, + webhook_details: self.webhook_details, + metadata: self.metadata, + routing_algorithm: self.routing_algorithm, + intent_fulfillment_time: self.intent_fulfillment_time, + frm_routing_algorithm: self.frm_routing_algorithm, + payout_routing_algorithm: self.payout_routing_algorithm, + is_recon_enabled: self.is_recon_enabled, + applepay_verified_domains: self.applepay_verified_domains, + payment_link_config: self.payment_link_config, + session_expiry: self.session_expiry, + authentication_connector_details: self.authentication_connector_details, + payout_link_config: self.payout_link_config, + is_extended_card_info_enabled: self.is_extended_card_info_enabled, + extended_card_info_config: self.extended_card_info_config, + is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, + use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector: self + .collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector: self + .collect_billing_details_from_wallet_connector, + outgoing_webhook_custom_http_headers: self + .outgoing_webhook_custom_http_headers + .map(Encryption::from), + }) + } + + async fn convert_back( + state: &keymanager::KeyManagerState, + item: Self::DstType, + key: &Secret<Vec<u8>>, + key_manager_identifier: keymanager::Identifier, + ) -> CustomResult<Self, ValidationError> + where + Self: Sized, + { + async { + Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { + profile_id: item.profile_id, + merchant_id: item.merchant_id, + profile_name: item.profile_name, + created_at: item.created_at, + modified_at: item.modified_at, + return_url: item.return_url, + enable_payment_response_hash: item.enable_payment_response_hash, + payment_response_hash_key: item.payment_response_hash_key, + redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, + webhook_details: item.webhook_details, + metadata: item.metadata, + routing_algorithm: item.routing_algorithm, + intent_fulfillment_time: item.intent_fulfillment_time, + frm_routing_algorithm: item.frm_routing_algorithm, + payout_routing_algorithm: item.payout_routing_algorithm, + is_recon_enabled: item.is_recon_enabled, + applepay_verified_domains: item.applepay_verified_domains, + payment_link_config: item.payment_link_config, + session_expiry: item.session_expiry, + authentication_connector_details: item.authentication_connector_details, + payout_link_config: item.payout_link_config, + is_extended_card_info_enabled: item.is_extended_card_info_enabled, + extended_card_info_config: item.extended_card_info_config, + is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled, + use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector: item + .collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector: item + .collect_billing_details_from_wallet_connector, + outgoing_webhook_custom_http_headers: item + .outgoing_webhook_custom_http_headers + .async_lift(|inner| { + decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek()) + }) + .await?, + }) + } + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting business profile data".to_string(), + }) + } + + async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + Ok(diesel_models::business_profile::BusinessProfileNew { + profile_id: self.profile_id, + merchant_id: self.merchant_id, + profile_name: self.profile_name, + created_at: self.created_at, + modified_at: self.modified_at, + return_url: self.return_url, + enable_payment_response_hash: self.enable_payment_response_hash, + payment_response_hash_key: self.payment_response_hash_key, + redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, + webhook_details: self.webhook_details, + metadata: self.metadata, + routing_algorithm: self.routing_algorithm, + intent_fulfillment_time: self.intent_fulfillment_time, + frm_routing_algorithm: self.frm_routing_algorithm, + payout_routing_algorithm: self.payout_routing_algorithm, + is_recon_enabled: self.is_recon_enabled, + applepay_verified_domains: self.applepay_verified_domains, + payment_link_config: self.payment_link_config, + session_expiry: self.session_expiry, + authentication_connector_details: self.authentication_connector_details, + payout_link_config: self.payout_link_config, + is_extended_card_info_enabled: self.is_extended_card_info_enabled, + extended_card_info_config: self.extended_card_info_config, + is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, + use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector: self + .collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector: self + .collect_billing_details_from_wallet_connector, + outgoing_webhook_custom_http_headers: self + .outgoing_webhook_custom_http_headers + .map(Encryption::from), + }) + } +} + +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +#[derive(Clone, Debug)] +pub struct BusinessProfile { + pub profile_id: String, + pub merchant_id: common_utils::id_type::MerchantId, + pub profile_name: String, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, + pub return_url: Option<String>, + pub enable_payment_response_hash: bool, + pub payment_response_hash_key: Option<String>, + pub redirect_to_merchant_with_http_post: bool, + pub webhook_details: Option<pii::SecretSerdeValue>, + pub metadata: Option<pii::SecretSerdeValue>, + pub is_recon_enabled: bool, + pub applepay_verified_domains: Option<Vec<String>>, + pub payment_link_config: Option<pii::SecretSerdeValue>, + pub session_expiry: Option<i64>, + pub authentication_connector_details: Option<pii::SecretSerdeValue>, + pub payout_link_config: Option<pii::SecretSerdeValue>, + pub is_extended_card_info_enabled: Option<bool>, + pub extended_card_info_config: Option<pii::SecretSerdeValue>, + pub is_connector_agnostic_mit_enabled: Option<bool>, + pub use_billing_as_payment_method_billing: Option<bool>, + pub collect_shipping_details_from_wallet_connector: Option<bool>, + pub collect_billing_details_from_wallet_connector: Option<bool>, + pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue, + pub routing_algorithm_id: Option<String>, + pub order_fulfillment_time: Option<i64>, + pub order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>, + pub frm_routing_algorithm_id: Option<String>, + pub payout_routing_algorithm_id: Option<String>, + pub default_fallback_routing: Option<pii::SecretSerdeValue>, +} + +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +#[derive(Debug)] +pub enum BusinessProfileUpdate { + Update { + profile_name: Option<String>, + return_url: Option<String>, + enable_payment_response_hash: Option<bool>, + payment_response_hash_key: Option<String>, + redirect_to_merchant_with_http_post: Option<bool>, + webhook_details: Option<pii::SecretSerdeValue>, + metadata: Option<pii::SecretSerdeValue>, + is_recon_enabled: Option<bool>, + applepay_verified_domains: Option<Vec<String>>, + payment_link_config: Option<pii::SecretSerdeValue>, + session_expiry: Option<i64>, + authentication_connector_details: Option<pii::SecretSerdeValue>, + payout_link_config: Option<pii::SecretSerdeValue>, + extended_card_info_config: Option<pii::SecretSerdeValue>, + use_billing_as_payment_method_billing: Option<bool>, + collect_shipping_details_from_wallet_connector: Option<bool>, + collect_billing_details_from_wallet_connector: Option<bool>, + is_connector_agnostic_mit_enabled: Option<bool>, + outgoing_webhook_custom_http_headers: OptionalEncryptableValue, + routing_algorithm_id: Option<String>, + order_fulfillment_time: Option<i64>, + order_fulfillment_time_origin: Option<OrderFulfillmentTimeOrigin>, + frm_routing_algorithm_id: Option<String>, + payout_routing_algorithm_id: Option<String>, + default_fallback_routing: Option<pii::SecretSerdeValue>, + }, + RoutingAlgorithmUpdate { + routing_algorithm_id: Option<String>, + payout_routing_algorithm_id: Option<String>, + }, + ExtendedCardInfoUpdate { + is_extended_card_info_enabled: Option<bool>, + }, + ConnectorAgnosticMitUpdate { + is_connector_agnostic_mit_enabled: Option<bool>, + }, +} + +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal { + fn from(business_profile_update: BusinessProfileUpdate) -> Self { + let now = date_time::now(); + + match business_profile_update { + BusinessProfileUpdate::Update { + profile_name, + return_url, + enable_payment_response_hash, + payment_response_hash_key, + redirect_to_merchant_with_http_post, + webhook_details, + metadata, + is_recon_enabled, + applepay_verified_domains, + payment_link_config, + session_expiry, + authentication_connector_details, + payout_link_config, + extended_card_info_config, + use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector, + is_connector_agnostic_mit_enabled, + outgoing_webhook_custom_http_headers, + routing_algorithm_id, + order_fulfillment_time, + order_fulfillment_time_origin, + frm_routing_algorithm_id, + payout_routing_algorithm_id, + default_fallback_routing, + } => Self { + profile_name, + modified_at: now, + return_url, + enable_payment_response_hash, + payment_response_hash_key, + redirect_to_merchant_with_http_post, + webhook_details, + metadata, + is_recon_enabled, + applepay_verified_domains, + payment_link_config, + session_expiry, + authentication_connector_details, + payout_link_config, + is_extended_card_info_enabled: None, + extended_card_info_config, + is_connector_agnostic_mit_enabled, + use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector, + outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers + .map(Encryption::from), + routing_algorithm_id, + order_fulfillment_time, + order_fulfillment_time_origin, + frm_routing_algorithm_id, + payout_routing_algorithm_id, + default_fallback_routing, + }, + BusinessProfileUpdate::RoutingAlgorithmUpdate { + routing_algorithm_id, + payout_routing_algorithm_id, + } => Self { + profile_name: None, + modified_at: now, + return_url: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + webhook_details: None, + metadata: None, + is_recon_enabled: None, + applepay_verified_domains: None, + payment_link_config: None, + session_expiry: None, + authentication_connector_details: None, + payout_link_config: None, + is_extended_card_info_enabled: None, + extended_card_info_config: None, + is_connector_agnostic_mit_enabled: None, + use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, + outgoing_webhook_custom_http_headers: None, + routing_algorithm_id, + order_fulfillment_time: None, + order_fulfillment_time_origin: None, + frm_routing_algorithm_id: None, + payout_routing_algorithm_id, + default_fallback_routing: None, + }, + BusinessProfileUpdate::ExtendedCardInfoUpdate { + is_extended_card_info_enabled, + } => Self { + profile_name: None, + modified_at: now, + return_url: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + webhook_details: None, + metadata: None, + is_recon_enabled: None, + applepay_verified_domains: None, + payment_link_config: None, + session_expiry: None, + authentication_connector_details: None, + payout_link_config: None, + is_extended_card_info_enabled, + extended_card_info_config: None, + is_connector_agnostic_mit_enabled: None, + use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, + outgoing_webhook_custom_http_headers: None, + routing_algorithm_id: None, + order_fulfillment_time: None, + order_fulfillment_time_origin: None, + frm_routing_algorithm_id: None, + payout_routing_algorithm_id: None, + default_fallback_routing: None, + }, + BusinessProfileUpdate::ConnectorAgnosticMitUpdate { + is_connector_agnostic_mit_enabled, + } => Self { + profile_name: None, + modified_at: now, + return_url: None, + enable_payment_response_hash: None, + payment_response_hash_key: None, + redirect_to_merchant_with_http_post: None, + webhook_details: None, + metadata: None, + is_recon_enabled: None, + applepay_verified_domains: None, + payment_link_config: None, + session_expiry: None, + authentication_connector_details: None, + payout_link_config: None, + is_extended_card_info_enabled: None, + extended_card_info_config: None, + is_connector_agnostic_mit_enabled, + use_billing_as_payment_method_billing: None, + collect_shipping_details_from_wallet_connector: None, + collect_billing_details_from_wallet_connector: None, + outgoing_webhook_custom_http_headers: None, + routing_algorithm_id: None, + order_fulfillment_time: None, + order_fulfillment_time_origin: None, + frm_routing_algorithm_id: None, + payout_routing_algorithm_id: None, + default_fallback_routing: None, + }, + } + } +} + +#[cfg(all(feature = "v2", feature = "business_profile_v2"))] +#[async_trait::async_trait] +impl super::behaviour::Conversion for BusinessProfile { + type DstType = diesel_models::business_profile::BusinessProfile; + type NewDstType = diesel_models::business_profile::BusinessProfileNew; + + async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { + Ok(diesel_models::business_profile::BusinessProfile { + profile_id: self.profile_id, + merchant_id: self.merchant_id, + profile_name: self.profile_name, + created_at: self.created_at, + modified_at: self.modified_at, + return_url: self.return_url, + enable_payment_response_hash: self.enable_payment_response_hash, + payment_response_hash_key: self.payment_response_hash_key, + redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, + webhook_details: self.webhook_details, + metadata: self.metadata, + is_recon_enabled: self.is_recon_enabled, + applepay_verified_domains: self.applepay_verified_domains, + payment_link_config: self.payment_link_config, + session_expiry: self.session_expiry, + authentication_connector_details: self.authentication_connector_details, + payout_link_config: self.payout_link_config, + is_extended_card_info_enabled: self.is_extended_card_info_enabled, + extended_card_info_config: self.extended_card_info_config, + is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, + use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector: self + .collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector: self + .collect_billing_details_from_wallet_connector, + outgoing_webhook_custom_http_headers: self + .outgoing_webhook_custom_http_headers + .map(Encryption::from), + routing_algorithm_id: self.routing_algorithm_id, + order_fulfillment_time: self.order_fulfillment_time, + order_fulfillment_time_origin: self.order_fulfillment_time_origin, + frm_routing_algorithm_id: self.frm_routing_algorithm_id, + payout_routing_algorithm_id: self.payout_routing_algorithm_id, + default_fallback_routing: self.default_fallback_routing, + }) + } + + async fn convert_back( + state: &keymanager::KeyManagerState, + item: Self::DstType, + key: &Secret<Vec<u8>>, + key_manager_identifier: keymanager::Identifier, + ) -> CustomResult<Self, ValidationError> + where + Self: Sized, + { + async { + Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { + profile_id: item.profile_id, + merchant_id: item.merchant_id, + profile_name: item.profile_name, + created_at: item.created_at, + modified_at: item.modified_at, + return_url: item.return_url, + enable_payment_response_hash: item.enable_payment_response_hash, + payment_response_hash_key: item.payment_response_hash_key, + redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post, + webhook_details: item.webhook_details, + metadata: item.metadata, + is_recon_enabled: item.is_recon_enabled, + applepay_verified_domains: item.applepay_verified_domains, + payment_link_config: item.payment_link_config, + session_expiry: item.session_expiry, + authentication_connector_details: item.authentication_connector_details, + payout_link_config: item.payout_link_config, + is_extended_card_info_enabled: item.is_extended_card_info_enabled, + extended_card_info_config: item.extended_card_info_config, + is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled, + use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector: item + .collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector: item + .collect_billing_details_from_wallet_connector, + outgoing_webhook_custom_http_headers: item + .outgoing_webhook_custom_http_headers + .async_lift(|inner| { + decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek()) + }) + .await?, + routing_algorithm_id: item.routing_algorithm_id, + order_fulfillment_time: item.order_fulfillment_time, + order_fulfillment_time_origin: item.order_fulfillment_time_origin, + frm_routing_algorithm_id: item.frm_routing_algorithm_id, + payout_routing_algorithm_id: item.payout_routing_algorithm_id, + default_fallback_routing: item.default_fallback_routing, + }) + } + .await + .change_context(ValidationError::InvalidValue { + message: "Failed while decrypting business profile data".to_string(), + }) + } + + async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> { + Ok(diesel_models::business_profile::BusinessProfileNew { + profile_id: self.profile_id, + merchant_id: self.merchant_id, + profile_name: self.profile_name, + created_at: self.created_at, + modified_at: self.modified_at, + return_url: self.return_url, + enable_payment_response_hash: self.enable_payment_response_hash, + payment_response_hash_key: self.payment_response_hash_key, + redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post, + webhook_details: self.webhook_details, + metadata: self.metadata, + is_recon_enabled: self.is_recon_enabled, + applepay_verified_domains: self.applepay_verified_domains, + payment_link_config: self.payment_link_config, + session_expiry: self.session_expiry, + authentication_connector_details: self.authentication_connector_details, + payout_link_config: self.payout_link_config, + is_extended_card_info_enabled: self.is_extended_card_info_enabled, + extended_card_info_config: self.extended_card_info_config, + is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled, + use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing, + collect_shipping_details_from_wallet_connector: self + .collect_shipping_details_from_wallet_connector, + collect_billing_details_from_wallet_connector: self + .collect_billing_details_from_wallet_connector, + outgoing_webhook_custom_http_headers: self + .outgoing_webhook_custom_http_headers + .map(Encryption::from), + routing_algorithm_id: self.routing_algorithm_id, + order_fulfillment_time: self.order_fulfillment_time, + order_fulfillment_time_origin: self.order_fulfillment_time_origin, + frm_routing_algorithm_id: self.frm_routing_algorithm_id, + payout_routing_algorithm_id: self.payout_routing_algorithm_id, + default_fallback_routing: self.default_fallback_routing, + }) + } +} diff --git a/crates/hyperswitch_domain_models/src/lib.rs b/crates/hyperswitch_domain_models/src/lib.rs index e7ad703f927..cabeda2ccc2 100644 --- a/crates/hyperswitch_domain_models/src/lib.rs +++ b/crates/hyperswitch_domain_models/src/lib.rs @@ -1,5 +1,6 @@ pub mod api; pub mod behaviour; +pub mod business_profile; pub mod customer; pub mod errors; pub mod mandates; diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 398e9143cfc..3e6f470d80e 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -33,6 +33,7 @@ recon = ["email", "api_models/recon"] retry = [] v2 = ["api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2"] v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1", "kgraph_utils/v1"] +# business_profile_v2 = ["api_models/business_profile_v2", "diesel_models/business_profile_v2", "hyperswitch_domain_models/business_profile_v2"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2"] merchant_account_v2 = ["api_models/merchant_account_v2", "diesel_models/merchant_account_v2", "hyperswitch_domain_models/merchant_account_v2"] payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2"] diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 26afafd7ad5..23d4b704cf3 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -3272,7 +3272,6 @@ pub async fn update_business_profile( let business_profile_update = storage::business_profile::BusinessProfileUpdate::Update { profile_name: request.profile_name, - modified_at: Some(date_time::now()), return_url: request.return_url.map(|return_url| return_url.to_string()), enable_payment_response_hash: request.enable_payment_response_hash, payment_response_hash_key: request.payment_response_hash_key, diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs index 6ef66883950..f550c7e501f 100644 --- a/crates/router/src/core/routing/helpers.rs +++ b/crates/router/src/core/routing/helpers.rs @@ -200,31 +200,9 @@ pub async fn update_business_profile_active_algorithm_ref( storage::enums::TransactionType::Payout => (None, Some(ref_val)), }; - let business_profile_update = BusinessProfileUpdate::Update { - profile_name: None, - return_url: None, - enable_payment_response_hash: None, - payment_response_hash_key: None, - redirect_to_merchant_with_http_post: None, - webhook_details: None, - metadata: None, + let business_profile_update = BusinessProfileUpdate::RoutingAlgorithmUpdate { routing_algorithm, - intent_fulfillment_time: None, - frm_routing_algorithm: None, payout_routing_algorithm, - applepay_verified_domains: None, - modified_at: None, - is_recon_enabled: None, - payment_link_config: None, - session_expiry: None, - authentication_connector_details: None, - payout_link_config: None, - extended_card_info_config: None, - use_billing_as_payment_method_billing: None, - collect_shipping_details_from_wallet_connector: None, - collect_billing_details_from_wallet_connector: None, - is_connector_agnostic_mit_enabled: None, - outgoing_webhook_custom_http_headers: None, }; db.update_business_profile_by_profile_id(current_business_profile, business_profile_update) diff --git a/justfile b/justfile index 228653a007a..1823c1ec19e 100644 --- a/justfile +++ b/justfile @@ -14,7 +14,7 @@ alias c := check # Check compilation of Rust code and catch common mistakes # We cannot run --all-features because v1 and v2 are mutually exclusive features -# Create a list of features by excluding certain features +# Create a list of features by excluding certain features clippy *FLAGS: #! /usr/bin/env bash set -euo pipefail @@ -120,9 +120,9 @@ euclid-wasm features='dummy_connector': precommit: fmt clippy # Check compilation of v2 feature on base dependencies -v2_intermediate_features := "merchant_account_v2,payment_v2,customer_v2" +v2_intermediate_features := "merchant_account_v2,payment_v2,customer_v2,business_profile_v2" hack_v2: - cargo hack clippy --feature-powerset --ignore-unknown-features --at-least-one-of "v2 " --include-features "v2" --include-features {{ v2_intermediate_features }} --package "hyperswitch_domain_models" --package "diesel_models" --package "api_models" + cargo hack clippy --feature-powerset --depth 2 --ignore-unknown-features --at-least-one-of "v2 " --include-features "v2" --include-features {{ v2_intermediate_features }} --package "hyperswitch_domain_models" --package "diesel_models" --package "api_models" cargo hack clippy --features "v2,payment_v2" -p storage_impl # Use the env variables if present, or fallback to default values @@ -174,7 +174,7 @@ migrate_v2 operation=default_operation *args='': set -euo pipefail EXIT_CODE=0 - just copy_migrations + just copy_migrations just run_migration {{ operation }} {{ resultant_dir }} {{ v2_config_file_dir }} {{ database_url }} {{ args }} || EXIT_CODE=$? just delete_dir_if_exists exit $EXIT_CODE @@ -186,5 +186,3 @@ resurrect: ci_hack: scripts/ci-checks.sh - - diff --git a/scripts/ci-checks.sh b/scripts/ci-checks.sh index 51089955728..5a37d2f2621 100755 --- a/scripts/ci-checks.sh +++ b/scripts/ci-checks.sh @@ -77,7 +77,7 @@ crates_with_v1_feature="$( --null-input \ '$crates_with_features[] | select( IN("v1"; .features[])) # Select crates with `v1` feature - | { name, features: (.features - ["v1", "v2", "default", "payment_v2", "merchant_account_v2","customer_v2", "merchant_connector_account_v2"]) } # Remove specific features to generate feature combinations + | { name, features: ( .features | del( .[] | select( any( . ; test("(([a-z_]+)_)?v2|v1|default") ) ) ) ) } # Remove specific features to generate feature combinations | { name, features: ( .features | map([., "v1"] | join(",")) ) } # Add `v1` to remaining features and join them by comma | .name as $name | .features[] | { $name, features: . } # Expand nested features object to have package - features combinations | "\(.name) \(.features)" # Print out package name and features separated by space' diff --git a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql new file mode 100644 index 00000000000..5645d4c7399 --- /dev/null +++ b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/down.sql @@ -0,0 +1,18 @@ +-- This adds back dropped columns in `up.sql`. +-- However, if the old columns were dropped, then we won't have data previously +-- stored in these columns. +ALTER TABLE business_profile + ADD COLUMN routing_algorithm JSON DEFAULT NULL, + ADD COLUMN intent_fulfillment_time BIGINT DEFAULT NULL, + ADD COLUMN frm_routing_algorithm JSONB DEFAULT NULL, + ADD COLUMN payout_routing_algorithm JSONB DEFAULT NULL; + +ALTER TABLE business_profile + DROP COLUMN routing_algorithm_id, + DROP COLUMN order_fulfillment_time, + DROP COLUMN order_fulfillment_time_origin, + DROP COLUMN frm_routing_algorithm_id, + DROP COLUMN payout_routing_algorithm_id, + DROP COLUMN default_fallback_routing; + +DROP TYPE "OrderFulfillmentTimeOrigin"; diff --git a/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql new file mode 100644 index 00000000000..f1cff174468 --- /dev/null +++ b/v2_migrations/2024-07-31-100300_business_profile_add_v2_columns_drop_v1_columns/up.sql @@ -0,0 +1,17 @@ +CREATE TYPE "OrderFulfillmentTimeOrigin" AS ENUM ('create', 'confirm'); + +ALTER TABLE business_profile + ADD COLUMN routing_algorithm_id VARCHAR(64) DEFAULT NULL, + ADD COLUMN order_fulfillment_time BIGINT DEFAULT NULL, + ADD COLUMN order_fulfillment_time_origin "OrderFulfillmentTimeOrigin" DEFAULT NULL, + ADD COLUMN frm_routing_algorithm_id VARCHAR(64) DEFAULT NULL, + ADD COLUMN payout_routing_algorithm_id VARCHAR(64) DEFAULT NULL, + ADD COLUMN default_fallback_routing JSONB DEFAULT NULL; + +-- Note: This query should not be run on higher environments as this leads to data loss. +-- The application will work fine even without these queries being run. +ALTER TABLE business_profile + DROP COLUMN routing_algorithm, + DROP COLUMN intent_fulfillment_time, + DROP COLUMN frm_routing_algorithm, + DROP COLUMN payout_routing_algorithm;
feat
introduce domain models for business profile v1 and v2 APIs (#5497)
32b731d9591ff4921b7d80556c7ebe050b53121f
2023-08-10 12:55:02
Sampras Lopes
refactor(storage): Add a separate crate to represent store implementations (#1853)
false
diff --git a/Cargo.lock b/Cargo.lock index c020039a10e..31b4934e316 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -99,12 +99,12 @@ dependencies = [ [[package]] name = "actix-macros" -version = "0.2.3" +version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "465a6172cf69b960917811022d8f29bc0b7fa1398bc4f78b3c466673db1213b6" +checksum = "e01ed3140b2f8d422c68afa1ed2e85d996ea619c988ac834d255db32138655cb" dependencies = [ "quote", - "syn 1.0.109", + "syn 2.0.28", ] [[package]] @@ -264,7 +264,7 @@ dependencies = [ "serde_urlencoded", "smallvec", "socket2", - "time 0.3.22", + "time 0.3.23", "url", ] @@ -291,12 +291,27 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "addr2line" +version = "0.20.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4fa78e18c64fce05e902adecd7a5eed15a5e0a3439f7b0e169f0252214865e3" +dependencies = [ + "gimli", +] + [[package]] name = "adler" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe" +[[package]] +name = "adler32" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aae1277d39aeec15cb388266ecc24b11c80469deae6067e17a1a7aa9e5c1f234" + [[package]] name = "ahash" version = "0.7.6" @@ -361,15 +376,15 @@ dependencies = [ [[package]] name = "anstyle" -version = "1.0.0" +version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "41ed9a86bf92ae6580e0a31281f65a1b1d867c0cc68d5346e2ae128dddfa6a7d" +checksum = "3a30da5c5f2d5e72842e00bcb57657162cdabef0931f40e2deb9b4140440cecd" [[package]] name = "anyhow" -version = "1.0.71" +version = "1.0.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8" +checksum = "3b13c32d80ecc7ab747b80c3784bce54ee8a7a0cc4fbda9bf4cda2cf6fe90854" [[package]] name = "api_models" @@ -379,16 +394,15 @@ dependencies = [ "cards", "common_enums", "common_utils", - "frunk", - "frunk_core", + "error-stack", "masking", "mime", "reqwest", "router_derive", "serde", "serde_json", - "strum", - "time 0.3.22", + "strum 0.24.1", + "time 0.3.23", "url", "utoipa", ] @@ -413,9 +427,9 @@ checksum = "6b4930d2cb77ce62f89ee5d5289b4ac049559b1c45539271f5ed4fdc7db34545" [[package]] name = "arrayvec" -version = "0.7.3" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8868f09ff8cea88b079da74ae569d9b8c62a23c68c746240b704ee6f7525c89c" +checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" [[package]] name = "assert-json-diff" @@ -452,9 +466,9 @@ dependencies = [ [[package]] name = "async-compression" -version = "0.4.0" +version = "0.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b0122885821398cc923ece939e24d1056a2384ee719432397fa9db87230ff11" +checksum = "62b74f44609f0f91493e3082d3734d98497e094777144380ea4db9f9905dd5b6" dependencies = [ "flate2", "futures-core", @@ -477,7 +491,7 @@ dependencies = [ "log", "parking", "polling", - "rustix", + "rustix 0.37.23", "slab", "socket2", "waker-fn", @@ -511,18 +525,18 @@ checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] name = "async-trait" -version = "0.1.68" +version = "0.1.72" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b9ccdd8f2a161be9bd5c023df56f1b2a0bd1d83872ae53b71a84a12c9bf6e842" +checksum = "cc6dde6e4ed435a4c1ee4e73592f5ba9da2151af10076cc04858746af9352d09" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] @@ -595,12 +609,12 @@ dependencies = [ "aws-smithy-types", "aws-types", "bytes", - "fastrand", + "fastrand 1.9.0", "hex", "http", "hyper", "ring", - "time 0.3.22", + "time 0.3.23", "tokio", "tower", "tracing", @@ -615,7 +629,7 @@ checksum = "1fcdb2f7acbc076ff5ad05e7864bdb191ca70a6fd07668dc3a1a8bcd051de5ae" dependencies = [ "aws-smithy-async", "aws-smithy-types", - "fastrand", + "fastrand 1.9.0", "tokio", "tracing", "zeroize", @@ -820,7 +834,7 @@ dependencies = [ "percent-encoding", "regex", "sha2", - "time 0.3.22", + "time 0.3.23", "tracing", ] @@ -868,7 +882,7 @@ dependencies = [ "aws-smithy-http-tower", "aws-smithy-types", "bytes", - "fastrand", + "fastrand 1.9.0", "http", "http-body", "hyper", @@ -960,7 +974,7 @@ dependencies = [ "itoa", "num-integer", "ryu", - "time 0.3.22", + "time 0.3.23", ] [[package]] @@ -990,9 +1004,9 @@ dependencies = [ [[package]] name = "axum" -version = "0.6.18" +version = "0.6.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f8175979259124331c1d7bf6586ee7e0da434155e4b2d48ec2c8386281d8df39" +checksum = "3b829e4e32b91e643de6eafe82b1d90675f5874230191a4ffbc1b336dec4d6bf" dependencies = [ "async-trait", "axum-core", @@ -1033,6 +1047,21 @@ dependencies = [ "tower-service", ] +[[package]] +name = "backtrace" +version = "0.3.68" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4319208da049c43661739c5fade2ba182f09d1dc2299b32298d3a31692b17e12" +dependencies = [ + "addr2line", + "cc", + "cfg-if", + "libc", + "miniz_oxide 0.7.1", + "object", + "rustc-demangle", +] + [[package]] name = "base64" version = "0.13.1" @@ -1100,9 +1129,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.3.2" +version = "2.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6dbe3c979c178231552ecba20214a8272df4e09f232a87aef4320cf06539aded" +checksum = "630be753d4e58660abd17930c71b647fe46c27ea6b63cc59e1e3851406972e42" [[package]] name = "blake3" @@ -1160,6 +1189,12 @@ version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c676a478f63e9fa2dd5368a42f28bba0d6c560b775f38583c8bbaa7fcd67c9c" +[[package]] +name = "bytemuck" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17febce684fd15d89027105661fec94afb475cb995fbc59d2865198446ba2eea" + [[package]] name = "byteorder" version = "1.4.3" @@ -1193,9 +1228,9 @@ dependencies = [ [[package]] name = "camino" -version = "1.1.4" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c530edf18f37068ac2d977409ed5cd50d53d73bc653c7647b48eb78976ac9ae2" +checksum = "c59e92b5a388f549b863a7bea62612c09f24c8393560709a54558a9abdfb3b9c" dependencies = [ "serde", ] @@ -1211,14 +1246,14 @@ dependencies = [ "serde", "serde_json", "thiserror", - "time 0.3.22", + "time 0.3.23", ] [[package]] name = "cargo-platform" -version = "0.1.2" +version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbdb825da8a5df079a43676dbe042702f1707b1109f713a01420fbb4cc71fa27" +checksum = "2cfa25e60aea747ec7e1124f238816749faa93759c6ff5b31f1ccdda137f4479" dependencies = [ "serde", ] @@ -1252,11 +1287,12 @@ dependencies = [ [[package]] name = "cc" -version = "1.0.79" +version = "1.0.82" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f" +checksum = "305fe645edc1442a0fa8b6726ba61d422798d37a52e12eaecf4b022ebbb88f01" dependencies = [ "jobserver", + "libc", ] [[package]] @@ -1276,6 +1312,12 @@ version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" +[[package]] +name = "checked_int_cast" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17cc5e6b5ab06331c33589842070416baa137e8b0eb912b008cfd4a78ada7919" + [[package]] name = "chrono" version = "0.4.26" @@ -1294,9 +1336,9 @@ dependencies = [ [[package]] name = "clap" -version = "4.3.4" +version = "4.3.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "80672091db20273a15cf9fdd4e47ed43b5091ec9841bf4c6145c9dfbbcae09ed" +checksum = "c27cdf28c0f604ba3f512b0c9a409f8de8513e4816705deb0498b627e7c3a3fd" dependencies = [ "clap_builder", "clap_derive", @@ -1305,25 +1347,24 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.3.4" +version = "4.3.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1458a1df40e1e2afebb7ab60ce55c1fa8f431146205aa5f4887e0b111c27636" +checksum = "08a9f1ab5e9f01a9b81f202e8562eb9a10de70abf9eaeac1be465c28b75aa4aa" dependencies = [ "anstyle", - "bitflags 1.3.2", "clap_lex", ] [[package]] name = "clap_derive" -version = "4.3.2" +version = "4.3.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8cd2b2a819ad6eec39e8f1d6b53001af1e5469f8c177579cdaeb313115b825f" +checksum = "54a9bb5758fc5dfe728d1019941681eccaf0cf8a4189b692a0ee2f2ecf90a050" dependencies = [ "heck", "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] @@ -1332,15 +1373,23 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b" +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + [[package]] name = "common_enums" version = "0.1.0" dependencies = [ + "common_utils", "diesel", "router_derive", "serde", "serde_json", - "strum", + "strum 0.25.0", + "time 0.3.23", "utoipa", ] @@ -1373,7 +1422,7 @@ dependencies = [ "signal-hook-tokio", "test-case", "thiserror", - "time 0.3.22", + "time 0.3.23", "tokio", ] @@ -1424,7 +1473,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb" dependencies = [ "percent-encoding", - "time 0.3.22", + "time 0.3.23", "version_check", ] @@ -1452,9 +1501,9 @@ checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" [[package]] name = "cpufeatures" -version = "0.2.7" +version = "0.2.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e4c1eaa2012c47becbbad2ab175484c2a84d1185b566fb2cc5b8707343dfe58" +checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" dependencies = [ "libc", ] @@ -1467,9 +1516,9 @@ checksum = "338089f42c427b86394a5ee60ff321da23a5c89c9d89514c829687b26359fcff" [[package]] name = "crc32c" -version = "0.6.3" +version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3dfea2db42e9927a3845fb268a10a72faed6d416065f77873f05e411457c363e" +checksum = "d8f48d60e5b4d2c53d5c2b1d8a58c849a70ae5e5509b08a48d047e3b65714a74" dependencies = [ "rustc_version", ] @@ -1493,6 +1542,17 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "crossbeam-deque" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6fd6f855243022dcecf8702fef0c297d4338e226845fe067f6341ad9fa0cef" +dependencies = [ + "cfg-if", + "crossbeam-epoch", + "crossbeam-utils", +] + [[package]] name = "crossbeam-epoch" version = "0.9.15" @@ -1537,12 +1597,12 @@ dependencies = [ [[package]] name = "darling" -version = "0.20.1" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0558d22a7b463ed0241e993f76f09f30b126687447751a8638587b864e4b3944" +checksum = "0209d94da627ab5605dcccf08bb18afa5009cfbef48d8a8b7d7bdbc79be25c5e" dependencies = [ - "darling_core 0.20.1", - "darling_macro 0.20.1", + "darling_core 0.20.3", + "darling_macro 0.20.3", ] [[package]] @@ -1561,16 +1621,16 @@ dependencies = [ [[package]] name = "darling_core" -version = "0.20.1" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab8bfa2e259f8ee1ce5e97824a3c55ec4404a0d772ca7fa96bf19f0752a046eb" +checksum = "177e3443818124b357d8e76f53be906d60937f0d3a90773a664fa63fa253e621" dependencies = [ "fnv", "ident_case", "proc-macro2", "quote", "strsim", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] @@ -1586,23 +1646,23 @@ dependencies = [ [[package]] name = "darling_macro" -version = "0.20.1" +version = "0.20.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "29a358ff9f12ec09c3e61fef9b5a9902623a695a46a917b07f269bff1445611a" +checksum = "836a9bbc7ad63342d6d6e7b815ccab164bc77a2d95d84bc3117a8c0d5c98e2d5" dependencies = [ - "darling_core 0.20.1", + "darling_core 0.20.3", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] name = "dashmap" -version = "5.4.0" +version = "5.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "907076dfda823b0b36d2a1bb5f90c96660a5bbcd7729e10727f07858f22c4edc" +checksum = "6943ae99c34386c84a470c499d3414f66502a41340aa895406e0d2e4a207b91d" dependencies = [ "cfg-if", - "hashbrown 0.12.3", + "hashbrown 0.14.0", "lock_api", "once_cell", "parking_lot_core", @@ -1627,6 +1687,16 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eaa37046cc0f6c3cc6090fbdbf73ef0b8ef4cfcc37f6befc0020f63e8cf121e1" +[[package]] +name = "deflate" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73770f8e1fe7d64df17ca66ad28994a0a623ea497fa69486e14984e715c5d174" +dependencies = [ + "adler32", + "byteorder", +] + [[package]] name = "derive_deref" version = "1.1.1" @@ -1657,14 +1727,14 @@ version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f7a532c1f99a0f596f6960a60d1e119e91582b24b39e2d83a190e61262c3ef0c" dependencies = [ - "bitflags 2.3.2", + "bitflags 2.3.3", "byteorder", "diesel_derives", "itoa", "pq-sys", "r2d2", "serde_json", - "time 0.3.22", + "time 0.3.23", ] [[package]] @@ -1676,7 +1746,28 @@ dependencies = [ "diesel_table_macro_syntax", "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", +] + +[[package]] +name = "diesel_models" +version = "0.1.0" +dependencies = [ + "async-bb8-diesel", + "common_enums", + "common_utils", + "diesel", + "error-stack", + "frunk", + "frunk_core", + "masking", + "router_derive", + "router_env", + "serde", + "serde_json", + "strum 0.24.1", + "thiserror", + "time 0.3.23", ] [[package]] @@ -1685,7 +1776,7 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc5557efc453706fed5e4fa85006fe9817c224c3f480a34c7e5959fd700921c5" dependencies = [ - "syn 2.0.18", + "syn 2.0.28", ] [[package]] @@ -1741,6 +1832,7 @@ dependencies = [ "common_utils", "config", "diesel", + "diesel_models", "error-stack", "external_services", "masking", @@ -1750,22 +1842,21 @@ dependencies = [ "serde", "serde_json", "serde_path_to_error", - "storage_models", "thiserror", "tokio", ] [[package]] name = "dyn-clone" -version = "1.0.11" +version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68b0cf012f1230e43cd00ebb729c6bb58707ecfa8ad08b52ef3a4ccd2697fc30" +checksum = "304e6508efa593091e97a9abbc10f90aa7ca635b6d2784feff3c89d41dd12272" [[package]] name = "either" -version = "1.8.1" +version = "1.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91" +checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07" [[package]] name = "encoding_rs" @@ -1797,13 +1888,13 @@ checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" [[package]] name = "errno" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a" +checksum = "6b30f669a7961ef1631673d2766cc92f52d64f7ef354d4fe0ddfd30ed52f0f4f" dependencies = [ "errno-dragonfly", "libc", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -1889,7 +1980,7 @@ dependencies = [ "mime", "serde", "serde_json", - "time 0.3.22", + "time 0.3.23", "tokio", "url", "webdriver", @@ -1904,6 +1995,12 @@ dependencies = [ "instant", ] +[[package]] +name = "fastrand" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6999dc1837253364c2ebb0704ba97994bd874e8f195d665c50b7548f6ea92764" + [[package]] name = "flate2" version = "1.0.26" @@ -1911,7 +2008,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3b9429470923de8e8cbd4d2dc513535400b4b3fef0319fb5c4e1f520a7bef743" dependencies = [ "crc32fast", - "miniz_oxide", + "miniz_oxide 0.7.1", ] [[package]] @@ -1985,9 +2082,9 @@ dependencies = [ [[package]] name = "frunk" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a89c703bf50009f383a0873845357cc400a95fc535f836feddfe015d7df6e1e0" +checksum = "11a351b59e12f97b4176ee78497dff72e4276fb1ceb13e19056aca7fa0206287" dependencies = [ "frunk_core", "frunk_derives", @@ -1996,55 +2093,43 @@ dependencies = [ [[package]] name = "frunk_core" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2a446d01a558301dca28ef43222864a9fa2bd9a2e71370f769d5d5d5ec9f3537" +checksum = "af2469fab0bd07e64ccf0ad57a1438f63160c69b2e57f04a439653d68eb558d6" [[package]] name = "frunk_derives" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b83164912bb4c97cfe0772913c7af7387ee2e00cb6d4636fb65a35b3d0c8f173" +checksum = "b0fa992f1656e1707946bbba340ad244f0814009ef8c0118eb7b658395f19a2e" dependencies = [ "frunk_proc_macro_helpers", "quote", - "syn 1.0.109", + "syn 2.0.28", ] [[package]] name = "frunk_proc_macro_helpers" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "015425591bbeb0f5b8a75593340f1789af428e9f887a4f1e36c0c471f067ef50" +checksum = "35b54add839292b743aeda6ebedbd8b11e93404f902c56223e51b9ec18a13d2c" dependencies = [ "frunk_core", "proc-macro2", "quote", - "syn 1.0.109", + "syn 2.0.28", ] [[package]] name = "frunk_proc_macros" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea01524f285deab48affffb342b97f186e657b119c3f1821ac531780e0fbfae0" -dependencies = [ - "frunk_core", - "frunk_proc_macros_impl", - "proc-macro-hack", -] - -[[package]] -name = "frunk_proc_macros_impl" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a802d974cc18ee7fe1a7868fc9ce31086294fd96ba62f8da64ecb44e92a2653" +checksum = "71b85a1d4a9a6b300b41c05e8e13ef2feca03e0334127f29eca9506a7fe13a93" dependencies = [ "frunk_core", "frunk_proc_macro_helpers", - "proc-macro-hack", "quote", - "syn 1.0.109", + "syn 2.0.28", ] [[package]] @@ -2101,7 +2186,7 @@ version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "49a9d51ce47660b1e808d3c990b4709f2f415d928835a17dfd16991515c46bce" dependencies = [ - "fastrand", + "fastrand 1.9.0", "futures-core", "futures-io", "memchr", @@ -2118,7 +2203,7 @@ checksum = "89ca545a94061b6365f2c7355b4b32bd20df3ff95f02da9329b34ccc3bd6ee72" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] @@ -2199,6 +2284,22 @@ dependencies = [ "wasi 0.11.0+wasi-snapshot-preview1", ] +[[package]] +name = "gif" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3edd93c6756b4dfaf2709eafcc345ba2636565295c198a9cfbf75fa5e3e00b06" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "gimli" +version = "0.27.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c80984affa11d98d1b88b66ac8853f143217b399d3c74116778ff8fdb4ed2e" + [[package]] name = "git2" version = "0.17.2" @@ -2220,9 +2321,9 @@ checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" [[package]] name = "h2" -version = "0.3.19" +version = "0.3.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d357c7ae988e7d2182f7d7871d0b963962420b0678b0997ce7de72001aeab782" +checksum = "97ec8491ebaf99c8eaa73058b045fe58073cd6be7f596ac993ced0b0a0c01049" dependencies = [ "bytes", "fnv", @@ -2269,18 +2370,9 @@ dependencies = [ [[package]] name = "hermit-abi" -version = "0.2.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" -dependencies = [ - "libc", -] - -[[package]] -name = "hermit-abi" -version = "0.3.1" +version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286" +checksum = "443144c8cdadd93ebf52ddb4056d257f5b52c04d3c804e657d19eb73fc33668b" [[package]] name = "hex" @@ -2363,9 +2455,9 @@ dependencies = [ [[package]] name = "hyper" -version = "0.14.26" +version = "0.14.27" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ab302d72a6f11a3b910431ff93aae7e773078c769f0a3ef15fb9ec692ed147d4" +checksum = "ffb1cfd654a8219eaef89881fdb3bb3b1cdc5fa75ded05d6933b2b382e395468" dependencies = [ "bytes", "futures-channel", @@ -2464,6 +2556,25 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "image" +version = "0.23.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24ffcb7e7244a9bf19d35bf2883b9c080c4ced3c07a9895572178cdb8f13f6a1" +dependencies = [ + "bytemuck", + "byteorder", + "color_quant", + "gif", + "jpeg-decoder", + "num-iter", + "num-rational", + "num-traits", + "png", + "scoped_threadpool", + "tiff", +] + [[package]] name = "indexmap" version = "1.9.3" @@ -2483,6 +2594,7 @@ checksum = "d5477fe2230a79769d8dc68e0eabf5437907c0457a5614a9e8dddb67f65eb65d" dependencies = [ "equivalent", "hashbrown 0.14.0", + "serde", ] [[package]] @@ -2515,16 +2627,16 @@ version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" dependencies = [ - "hermit-abi 0.3.1", + "hermit-abi 0.3.2", "libc", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] name = "ipnet" -version = "2.7.2" +version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12b6ee2129af8d4fb011108c73d99a1b83a85977f23b82460c0ae2e25bb4b57f" +checksum = "28b29a3cd74f0f4598934efe3aeba42bae0eb4680554128851ebbecb02af14e6" [[package]] name = "itertools" @@ -2537,9 +2649,9 @@ dependencies = [ [[package]] name = "itoa" -version = "1.0.6" +version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6" +checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" [[package]] name = "jobserver" @@ -2565,7 +2677,16 @@ dependencies = [ "serde", "serde_json", "thiserror", - "time 0.3.22", + "time 0.3.23", +] + +[[package]] +name = "jpeg-decoder" +version = "0.1.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229d53d58899083193af11e15917b5640cd40b29ff475a1fe4ef725deb02d0f2" +dependencies = [ + "rayon", ] [[package]] @@ -2616,9 +2737,9 @@ checksum = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" [[package]] name = "libc" -version = "0.2.146" +version = "0.2.147" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b" +checksum = "b4668fb0ea861c1df094127ac5f1da3409a82116a4ba74fca2e58ef927159bb3" [[package]] name = "libgit2-sys" @@ -2650,9 +2771,9 @@ dependencies = [ [[package]] name = "libz-sys" -version = "1.1.9" +version = "1.1.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "56ee889ecc9568871456d42f603d6a0ce59ff328d291063a45cbdf0036baf6db" +checksum = "d97137b25e321a73eef1418d1d5d2eda4d77e12813f8e6dead84bc52c5870a7b" dependencies = [ "cc", "libc", @@ -2672,6 +2793,12 @@ version = "0.3.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519" +[[package]] +name = "linux-raw-sys" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57bcfdad1b858c2db7c38303a6d2ad4dfaf5eb53dfeb0910128b2c26d6158503" + [[package]] name = "literally" version = "0.1.3" @@ -2757,14 +2884,14 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8263075bb86c5a1b1427b5ae862e8889656f126e9f77c484496e8b47cf5c5558" dependencies = [ - "regex-automata", + "regex-automata 0.1.10", ] [[package]] name = "matchit" -version = "0.7.0" +version = "0.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b87248edafb776e59e6ee64a79086f65890d3510f2c656c000bf2a7e8a0aea40" +checksum = "ed1202b2a6f884ae56f04cff409ab315c5ce26b5e58d7412e484f01fd52f52ef" [[package]] name = "maud" @@ -2851,6 +2978,25 @@ version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" +[[package]] +name = "miniz_oxide" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791daaae1ed6889560f8c4359194f56648355540573244a5448a83ba1ecc7435" +dependencies = [ + "adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a92518e98c078586bc6c934028adcca4c92a53d6a958196de835170a01d84e4b" +dependencies = [ + "adler", + "autocfg", +] + [[package]] name = "miniz_oxide" version = "0.7.1" @@ -2869,14 +3015,14 @@ dependencies = [ "libc", "log", "wasi 0.11.0+wasi-snapshot-preview1", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] name = "moka" -version = "0.11.2" +version = "0.11.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "206bf83f415b0579fd885fe0804eb828e727636657dc1bf73d80d2f1218e14a1" +checksum = "fa6e72583bf6830c956235bff0d5afec8cf2952f579ebad18ae7821a917d950f" dependencies = [ "async-io", "async-lock", @@ -2965,11 +3111,33 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-iter" +version = "0.1.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d03e6c028c5dc5cac6e2dec0efda81fc887605bb3d884578bb6d6bf7514e252" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12ac428b1cb17fce6f731001d307d351ec70a6d202fc2e60f7d4c5e42d8f4f07" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" -version = "0.2.15" +version = "0.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "578ede34cf02f8924ab9447f50c28075b4d3e5b269972345e7e0372b38c6cdcd" +checksum = "f30b0abd723be7e2ffca1272140fac1a2f084c77ec3e123c192b66af1ee9e6c2" dependencies = [ "autocfg", "libm", @@ -2977,14 +3145,32 @@ dependencies = [ [[package]] name = "num_cpus" -version = "1.15.0" +version = "1.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" +checksum = "4161fcb6d602d4d2081af7c3a45852d875a03dd337a6bfdd6e06407b61342a43" dependencies = [ - "hermit-abi 0.2.6", + "hermit-abi 0.3.2", "libc", ] +[[package]] +name = "num_threads" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44" +dependencies = [ + "libc", +] + +[[package]] +name = "object" +version = "0.31.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8bda667d9f2b5051b8833f59f3bf748b28ef54f850f4fcb389a252aa383866d1" +dependencies = [ + "memchr", +] + [[package]] name = "once_cell" version = "1.18.0" @@ -2999,9 +3185,9 @@ checksum = "44d11de466f4a3006fe8a5e7ec84e93b79c70cb992ae0aa0eb631ad2df8abfe2" [[package]] name = "openssl" -version = "0.10.55" +version = "0.10.56" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "345df152bc43501c5eb9e4654ff05f794effb78d4efe3d53abc158baddc0703d" +checksum = "729b745ad4a5575dd06a3e1af1414bd330ee561c01b3899eb584baeaa8def17e" dependencies = [ "bitflags 1.3.2", "cfg-if", @@ -3020,7 +3206,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] @@ -3031,9 +3217,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf" [[package]] name = "openssl-sys" -version = "0.9.90" +version = "0.9.91" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "374533b0e45f3a7ced10fcaeccca020e66656bc03dac384f852e4e5a7a8104a6" +checksum = "866b5f16f90776b9bb8dc1e1802ac6f0513de3a7a7465867bfbc563dc737faac" dependencies = [ "cc", "libc", @@ -3179,9 +3365,9 @@ checksum = "944553dd59c802559559161f9816429058b869003836120e262e8caec061b7ae" [[package]] name = "paste" -version = "1.0.12" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f746c4065a8fa3fe23974dd82f15431cc8d40779821001404d10d2e79ca7d79" +checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" [[package]] name = "pathdiff" @@ -3206,9 +3392,9 @@ checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" [[package]] name = "pest" -version = "2.6.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e68e84bfb01f0507134eac1e9b410a12ba379d064eab48c50ba4ce329a527b70" +checksum = "1acb4a4365a13f749a93f1a094a7805e5cfa0955373a9de860d962eaa3a5fe5a" dependencies = [ "thiserror", "ucd-trie", @@ -3216,9 +3402,9 @@ dependencies = [ [[package]] name = "pest_derive" -version = "2.6.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6b79d4c71c865a25a4322296122e3924d30bc8ee0834c8bfc8b95f7f054afbfb" +checksum = "666d00490d4ac815001da55838c500eafb0320019bbaa44444137c48b443a853" dependencies = [ "pest", "pest_generator", @@ -3226,22 +3412,22 @@ dependencies = [ [[package]] name = "pest_generator" -version = "2.6.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c435bf1076437b851ebc8edc3a18442796b30f1728ffea6262d59bbe28b077e" +checksum = "68ca01446f50dbda87c1786af8770d535423fa8a53aec03b8f4e3d7eb10e0929" dependencies = [ "pest", "pest_meta", "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] name = "pest_meta" -version = "2.6.0" +version = "2.7.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "745a452f8eb71e39ffd8ee32b3c5f51d03845f99786fa9b68db6ff509c505411" +checksum = "56af0a30af74d0445c0bf6d9d051c979b516a1a5af790d251daee76005420a48" dependencies = [ "once_cell", "pest", @@ -3270,29 +3456,29 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.1.0" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c95a7476719eab1e366eaf73d0260af3021184f18177925b07f54b30089ceead" +checksum = "fda4ed1c6c173e3fc7a83629421152e01d7b1f9b7f65fb301e490e8cfc656422" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.0" +version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39407670928234ebc5e6e580247dd567ad73a3578460c5990f9503df207e8f07" +checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] name = "pin-project-lite" -version = "0.2.9" +version = "0.2.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" +checksum = "2c516611246607d0c04186886dbb3a754368ef82c79e9827a802c6d836dd111c" [[package]] name = "pin-utils" @@ -3306,6 +3492,18 @@ version = "0.3.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964" +[[package]] +name = "png" +version = "0.16.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c3287920cb847dee3de33d301c463fba14dda99db24214ddf93f83d3021f4c6" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "deflate", + "miniz_oxide 0.3.7", +] + [[package]] name = "polling" version = "2.8.0" @@ -3319,7 +3517,7 @@ dependencies = [ "libc", "log", "pin-project-lite", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -3371,17 +3569,11 @@ dependencies = [ "version_check", ] -[[package]] -name = "proc-macro-hack" -version = "0.5.20+deprecated" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" - [[package]] name = "proc-macro2" -version = "1.0.60" +version = "1.0.66" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dec2b086b7a862cf4de201096214fa870344cf922b2b30c167badb3af3195406" +checksum = "18fb31db3f9bddb2ea821cde30a9f70117e3f119938b5ee630b7403aa6e2ead9" dependencies = [ "unicode-ident", ] @@ -3440,6 +3632,16 @@ dependencies = [ "unicase", ] +[[package]] +name = "qrcode" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16d2f1455f3630c6e5107b4f2b94e74d76dea80736de0981fd27644216cff57f" +dependencies = [ + "checked_int_cast", + "image", +] + [[package]] name = "quanta" version = "0.11.1" @@ -3474,9 +3676,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.28" +version = "1.0.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488" +checksum = "50f3b39ccfb720540debaa0164757101c08ecb8d326b15358ce76a62c7e85965" dependencies = [ "proc-macro2", ] @@ -3581,6 +3783,28 @@ dependencies = [ "bitflags 1.3.2", ] +[[package]] +name = "rayon" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d2df5196e37bcc87abebc0053e20787d73847bb33134a69841207dd0a47f03b" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b8f95bd6966f5c87776639160a66bd8ab9895d9d4ab01ddba9fc60661aebe8d" +dependencies = [ + "crossbeam-channel", + "crossbeam-deque", + "crossbeam-utils", + "num_cpus", +] + [[package]] name = "redis-protocol" version = "4.1.0" @@ -3640,13 +3864,14 @@ dependencies = [ [[package]] name = "regex" -version = "1.8.4" +version = "1.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0ab3ca65655bb1e41f2a8c8cd662eb4fb035e67c3f78da1d61dffe89d07300f" +checksum = "81bc1d4caf89fac26a70747fe603c130093b53c773888797a6329091246d651a" dependencies = [ "aho-corasick", "memchr", - "regex-syntax 0.7.2", + "regex-automata 0.3.6", + "regex-syntax 0.7.4", ] [[package]] @@ -3658,6 +3883,17 @@ dependencies = [ "regex-syntax 0.6.29", ] +[[package]] +name = "regex-automata" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fed1ceff11a1dddaee50c9dc8e4938bd106e9d89ae372f192311e7da498e3b69" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax 0.7.4", +] + [[package]] name = "regex-cache" version = "0.2.1" @@ -3678,9 +3914,9 @@ checksum = "f162c6dd7b008981e4d40210aca20b4bd0f9b60ca9271061b07f78537722f2e1" [[package]] name = "regex-syntax" -version = "0.7.2" +version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "436b050e76ed2903236f032a59761c1eb99e1b0aead2c257922771dab1fc8c78" +checksum = "e5ea92a5b6195c6ef2a0295ea818b312502c6fc94dde986c5553242e18fd4ce2" [[package]] name = "reqwest" @@ -3781,15 +4017,15 @@ dependencies = [ "crc32fast", "derive_deref", "diesel", + "diesel_models", "dyn-clone", "encoding_rs", "error-stack", "external_services", - "frunk", - "frunk_core", "futures", "hex", "http", + "image", "infer 0.13.0", "josekit", "jsonwebtoken", @@ -3802,6 +4038,7 @@ dependencies = [ "nanoid", "num_cpus", "once_cell", + "qrcode", "rand 0.8.5", "redis_interface", "regex", @@ -3819,14 +4056,14 @@ dependencies = [ "serial_test", "signal-hook", "signal-hook-tokio", - "storage_models", - "strum", + "storage_impl", + "strum 0.24.1", "test_utils", "thirtyfour", "thiserror", - "time 0.3.22", + "time 0.3.23", "tokio", - "toml 0.7.4", + "toml 0.7.6", "url", "utoipa", "utoipa-swagger-ui", @@ -3845,7 +4082,7 @@ dependencies = [ "quote", "serde", "serde_json", - "strum", + "strum 0.24.1", "syn 1.0.109", ] @@ -3863,8 +4100,8 @@ dependencies = [ "serde", "serde_json", "serde_path_to_error", - "strum", - "time 0.3.22", + "strum 0.24.1", + "time 0.3.23", "tokio", "tracing", "tracing-actix-web", @@ -3886,9 +4123,9 @@ dependencies = [ [[package]] name = "rust-embed" -version = "6.7.0" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b73e721f488c353141288f223b599b4ae9303ecf3e62923f40a492f0634a4dc3" +checksum = "a36224c3276f8c4ebc8c20f158eca7ca4359c8db89991c4925132aaaf6702661" dependencies = [ "rust-embed-impl", "rust-embed-utils", @@ -3897,23 +4134,23 @@ dependencies = [ [[package]] name = "rust-embed-impl" -version = "6.6.0" +version = "6.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e22ce362f5561923889196595504317a4372b84210e6e335da529a65ea5452b5" +checksum = "49b94b81e5b2c284684141a2fb9e2a31be90638caf040bf9afbc5a0416afe1ac" dependencies = [ "proc-macro2", "quote", "rust-embed-utils", "shellexpand", - "syn 2.0.18", + "syn 2.0.28", "walkdir", ] [[package]] name = "rust-embed-utils" -version = "7.5.0" +version = "7.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "512b0ab6853f7e14e3c8754acb43d6f748bb9ced66aa5915a6553ac8213f7731" +checksum = "9d38ff6bf570dc3bb7100fce9f7b60c33fa71d80e88da3f2580df4ff2bdded74" dependencies = [ "sha2", "walkdir", @@ -3929,6 +4166,12 @@ dependencies = [ "ordered-multimap", ] +[[package]] +name = "rustc-demangle" +version = "0.1.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d626bb9dae77e28219937af045c257c28bfd3f69333c512553507f5f9798cb76" + [[package]] name = "rustc-hash" version = "1.1.0" @@ -3946,16 +4189,29 @@ dependencies = [ [[package]] name = "rustix" -version = "0.37.20" +version = "0.37.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b96e891d04aa506a6d1f318d2771bcb1c7dfda84e126660ace067c9b474bb2c0" +checksum = "4d69718bf81c6127a49dc64e44a742e8bb9213c0ff8869a22c308f84c1d4ab06" dependencies = [ "bitflags 1.3.2", "errno", "io-lifetimes", "libc", - "linux-raw-sys", - "windows-sys 0.48.0", + "linux-raw-sys 0.3.8", + "windows-sys", +] + +[[package]] +name = "rustix" +version = "0.38.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "172891ebdceb05aa0005f533a6cbfca599ddd7d966f6f5d4d9b2e70478e70399" +dependencies = [ + "bitflags 2.3.3", + "errno", + "libc", + "linux-raw-sys 0.4.5", + "windows-sys", ] [[package]] @@ -3984,18 +4240,18 @@ dependencies = [ [[package]] name = "rustls-pemfile" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d194b56d58803a43635bdc398cd17e383d6f71f9182b9a192c127ca42494a59b" +checksum = "2d3987094b1d07b653b7dfdc3f70ce9a1da9c51ac18c1b06b662e4f9a0e9f4b2" dependencies = [ "base64 0.21.2", ] [[package]] name = "rustversion" -version = "1.0.12" +version = "1.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f3208ce4d8448b3f3e7d168a73f5e0c43a61e32930de3bceeccedb388b6bf06" +checksum = "7ffc183a10b4478d04cbbbfc96d0873219d962dd5accaff2ffbd4ceb7df837f4" [[package]] name = "rusty-fork" @@ -4011,9 +4267,9 @@ dependencies = [ [[package]] name = "ryu" -version = "1.0.13" +version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041" +checksum = "1ad4cc8da4ef723ed60bced201181d83791ad433213d8c24efffda1eec85d741" [[package]] name = "same-file" @@ -4026,11 +4282,11 @@ dependencies = [ [[package]] name = "schannel" -version = "0.1.21" +version = "0.1.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3" +checksum = "0c3733bf4cf7ea0880754e19cb5a462007c4a8c1914bff372ccc95b464f1df88" dependencies = [ - "windows-sys 0.42.0", + "windows-sys", ] [[package]] @@ -4042,11 +4298,17 @@ dependencies = [ "parking_lot", ] +[[package]] +name = "scoped_threadpool" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d51f5df5af43ab3f1360b429fa5e0152ac5ce8c0bd6485cae490332e96846a8" + [[package]] name = "scopeguard" -version = "1.1.0" +version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" [[package]] name = "sct" @@ -4060,9 +4322,9 @@ dependencies = [ [[package]] name = "security-framework" -version = "2.9.1" +version = "2.9.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1fc758eb7bffce5b308734e9b0c1468893cae9ff70ebf13e7090be8dcbcc83a8" +checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de" dependencies = [ "bitflags 1.3.2", "core-foundation", @@ -4073,9 +4335,9 @@ dependencies = [ [[package]] name = "security-framework-sys" -version = "2.9.0" +version = "2.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f51d0c0d83bec45f16480d0ce0058397a69e48fcdc52d1dc8855fb68acbd31a7" +checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a" dependencies = [ "core-foundation-sys", "libc", @@ -4083,40 +4345,40 @@ dependencies = [ [[package]] name = "semver" -version = "1.0.17" +version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bebd363326d05ec3e2f532ab7660680f3b02130d780c299bca73469d521bc0ed" +checksum = "b0293b4b29daaf487284529cc2f5675b8e57c61f70167ba415a463651fd6a918" dependencies = [ "serde", ] [[package]] name = "serde" -version = "1.0.164" +version = "1.0.183" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d" +checksum = "32ac8da02677876d532745a130fc9d8e6edfa81a269b107c5b00829b91d8eb3c" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" -version = "1.0.164" +version = "1.0.183" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68" +checksum = "aafe972d60b0b9bee71a91b92fee2d4fb3c9d7e8f6b179aa99f27203d99a4816" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] name = "serde_json" -version = "1.0.96" +version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "057d394a50403bcac12672b2b18fb387ab6d289d957dab67dd201875391e52f1" +checksum = "076066c5f1078eac5b722a31827a8832fe108bed65dfa75e233c89f8206e976c" dependencies = [ - "indexmap 1.9.3", + "indexmap 2.0.0", "itoa", "ryu", "serde", @@ -4124,10 +4386,11 @@ dependencies = [ [[package]] name = "serde_path_to_error" -version = "0.1.11" +version = "0.1.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7f05c1d5476066defcdfacce1f52fc3cae3af1d3089727100c02ae92e5abbe0" +checksum = "4beec8bce849d58d06238cb50db2e1c417cfeafa4c63f692b15c82b7c80f8335" dependencies = [ + "itoa", "serde", ] @@ -4164,20 +4427,20 @@ dependencies = [ [[package]] name = "serde_repr" -version = "0.1.12" +version = "0.1.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bcec881020c684085e55a25f7fd888954d56609ef363479dc5a1305eb0d40cab" +checksum = "8725e1dfadb3a50f7e5ce0b1a540466f6ed3fe7a0fca2ac2b8b831d31316bd00" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] name = "serde_spanned" -version = "0.6.2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "93107647184f6027e3b7dcb2e11034cf95ffa1e3a682c67951963ac69c1c007d" +checksum = "96426c9936fd7a0124915f9185ea1d20aa9445cc9821142f0a73bc9207a2e186" dependencies = [ "serde", ] @@ -4196,30 +4459,31 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.0.0" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9f02d8aa6e3c385bf084924f660ce2a3a6bd333ba55b35e8590b321f35d88513" +checksum = "1402f54f9a3b9e2efe71c1cea24e648acce55887983553eeb858cf3115acfd49" dependencies = [ "base64 0.21.2", "chrono", "hex", "indexmap 1.9.3", + "indexmap 2.0.0", "serde", "serde_json", "serde_with_macros", - "time 0.3.22", + "time 0.3.23", ] [[package]] name = "serde_with_macros" -version = "3.0.0" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "edc7d5d3932fb12ce722ee5e64dd38c504efba37567f0c402f6ca728c3b8b070" +checksum = "9197f1ad0e3c173a0222d3c4404fb04c3afe87e962bcb327af73e8301fa203c7" dependencies = [ - "darling 0.20.1", + "darling 0.20.3", "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] @@ -4244,7 +4508,7 @@ checksum = "91d129178576168c589c9ec973feedf7d3126c01ac2bf08795109aa35b69fb8f" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] @@ -4271,9 +4535,9 @@ dependencies = [ [[package]] name = "sha2" -version = "0.10.6" +version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82e6b795fe2e3b1e845bafcb27aa35405c4d47cdfc92af5fc8d3002f76cebdc0" +checksum = "479fb9d862239e610720565ca91403019f2f00410f1864c5aa7479b950a76ed8" dependencies = [ "cfg-if", "cpufeatures", @@ -4300,9 +4564,9 @@ dependencies = [ [[package]] name = "signal-hook" -version = "0.3.15" +version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "732768f1176d21d09e076c23a93123d40bba92d50c4058da34d45c8de8e682b9" +checksum = "8621587d4798caf8eb44879d42e56b9a93ea5dcd315a6487c357130095b62801" dependencies = [ "libc", "signal-hook-registry", @@ -4338,7 +4602,7 @@ dependencies = [ "num-bigint", "num-traits", "thiserror", - "time 0.3.22", + "time 0.3.23", ] [[package]] @@ -4367,9 +4631,9 @@ dependencies = [ [[package]] name = "smallvec" -version = "1.10.0" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" +checksum = "62bb4feee49fdd9f707ef802e22365a35de4b7b299de4763d44bfea899442ff9" [[package]] name = "socket2" @@ -4388,24 +4652,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d" [[package]] -name = "storage_models" +name = "storage_impl" version = "0.1.0" dependencies = [ "async-bb8-diesel", - "common_enums", - "common_utils", + "async-trait", + "bb8", "diesel", - "error-stack", - "frunk", - "frunk_core", "masking", - "router_derive", - "router_env", - "serde", - "serde_json", - "strum", - "thiserror", - "time 0.3.22", ] [[package]] @@ -4429,7 +4683,16 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "063e6045c0e62079840579a7e47a355ae92f60eb74daaf156fb1e84ba164e63f" dependencies = [ - "strum_macros", + "strum_macros 0.24.3", +] + +[[package]] +name = "strum" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290d54ea6f91c969195bdbcd7442c8c2a2ba87da8bf60a7ee86a235d4bc1e125" +dependencies = [ + "strum_macros 0.25.2", ] [[package]] @@ -4445,6 +4708,19 @@ dependencies = [ "syn 1.0.109", ] +[[package]] +name = "strum_macros" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8d03b598d3d0fff69bf533ee3ef19b8eeb342729596df84bcc7e1f96ec4059" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "rustversion", + "syn 2.0.28", +] + [[package]] name = "subtle" version = "2.4.1" @@ -4464,9 +4740,9 @@ dependencies = [ [[package]] name = "syn" -version = "2.0.18" +version = "2.0.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "32d41677bcbe24c20c52e7c70b0d8db04134c5d1066bf98662e2871ad200ea3e" +checksum = "04361975b3f5e348b2189d8dc55bc942f278b2d482a6a0365de5bdd62d351567" dependencies = [ "proc-macro2", "quote", @@ -4487,16 +4763,15 @@ checksum = "7b2093cf4c8eb1e67749a6762251bc9cd836b6fc171623bd0a9d324d37af2417" [[package]] name = "tempfile" -version = "3.6.0" +version = "3.7.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "31c0432476357e58790aaa47a8efb0c5138f137343f3b5f23bd36a27e3b0a6d6" +checksum = "dc02fddf48964c42031a0b3fe0428320ecf3a73c401040fc0096f97794310651" dependencies = [ - "autocfg", "cfg-if", - "fastrand", + "fastrand 2.0.0", "redox_syscall 0.3.5", - "rustix", - "windows-sys 0.48.0", + "rustix 0.38.7", + "windows-sys", ] [[package]] @@ -4564,9 +4839,9 @@ dependencies = [ "serde_urlencoded", "serial_test", "thirtyfour", - "time 0.3.22", + "time 0.3.23", "tokio", - "toml 0.7.4", + "toml 0.7.6", "uuid", ] @@ -4610,22 +4885,22 @@ dependencies = [ [[package]] name = "thiserror" -version = "1.0.40" +version = "1.0.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac" +checksum = "611040a08a0439f8248d1990b111c95baa9c704c805fa1f62104b39655fd7f90" dependencies = [ "thiserror-impl", ] [[package]] name = "thiserror-impl" -version = "1.0.40" +version = "1.0.44" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f" +checksum = "090198534930841fab3a5d1bb637cde49e339654e606195f8d9c76eeb081dc96" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] @@ -4638,6 +4913,17 @@ dependencies = [ "once_cell", ] +[[package]] +name = "tiff" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a53f4706d65497df0c4349241deddf35f84cee19c87ed86ea8ca590f4464437" +dependencies = [ + "jpeg-decoder", + "miniz_oxide 0.4.4", + "weezl", +] + [[package]] name = "time" version = "0.1.45" @@ -4651,11 +4937,13 @@ dependencies = [ [[package]] name = "time" -version = "0.3.22" +version = "0.3.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ea9e1b3cf1243ae005d9e74085d4d542f3125458f3a81af210d901dcd7411efd" +checksum = "59e399c068f43a5d116fedaf73b203fa4f9c519f17e2b34f63221d3792f81446" dependencies = [ "itoa", + "libc", + "num_threads", "serde", "time-core", "time-macros", @@ -4669,9 +4957,9 @@ checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb" [[package]] name = "time-macros" -version = "0.2.9" +version = "0.2.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "372950940a5f07bf38dbe211d7283c9e6d7327df53794992d293e534c733d09b" +checksum = "96ba15a897f3c86766b757e5ac7221554c6750054d74d5b28844fce5fb36a6c4" dependencies = [ "time-core", ] @@ -4693,11 +4981,12 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.28.2" +version = "1.29.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "94d7b1cfd2aa4011f2de74c2c4c63665e27a71006b0a192dcd2710272e73dfa2" +checksum = "532826ff75199d5833b9d2c5fe410f29235e25704ee5f0ef599fb51c21f4a4da" dependencies = [ "autocfg", + "backtrace", "bytes", "libc", "mio", @@ -4707,7 +4996,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", - "windows-sys 0.48.0", + "windows-sys", ] [[package]] @@ -4728,7 +5017,7 @@ checksum = "630bdcf245f78637c13ec01ffae6187cca34625e8c63150d424b59e55af2675e" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] @@ -4788,9 +5077,9 @@ dependencies = [ [[package]] name = "toml" -version = "0.7.4" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d6135d499e69981f9ff0ef2167955a5333c35e36f6937d382974566b3d5b94ec" +checksum = "c17e963a819c331dcacd7ab957d80bc2b9a9c1e71c804826d2f283dd65306542" dependencies = [ "serde", "serde_spanned", @@ -4800,20 +5089,20 @@ dependencies = [ [[package]] name = "toml_datetime" -version = "0.6.2" +version = "0.6.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a76a9312f5ba4c2dec6b9161fdf25d87ad8a09256ccea5a556fef03c706a10f" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" dependencies = [ "serde", ] [[package]] name = "toml_edit" -version = "0.19.10" +version = "0.19.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2380d56e8670370eee6566b0bfd4265f65b3f432e8c6d85623f728d4fa31f739" +checksum = "f8123f27e969974a3dfba720fdb560be359f57b44302d280ba72e76a74480e8a" dependencies = [ - "indexmap 1.9.3", + "indexmap 2.0.0", "serde", "serde_spanned", "toml_datetime", @@ -4899,9 +5188,9 @@ dependencies = [ [[package]] name = "tracing-actix-web" -version = "0.7.5" +version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce52ffaf2d544e317d3bef63f49a6a22022866505fa4840a4339b1756834a2a9" +checksum = "5c0b08ce08cbde6a96fc1e4ebb8132053e53ec7a5cd27eef93ede6b73ebbda06" dependencies = [ "actix-web", "opentelemetry", @@ -4918,7 +5207,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09d48f71a791638519505cefafe162606f706c25592e4bde4d97600c0195312e" dependencies = [ "crossbeam-channel", - "time 0.3.22", + "time 0.3.23", "tracing-subscriber", ] @@ -5011,9 +5300,9 @@ dependencies = [ [[package]] name = "triomphe" -version = "0.1.8" +version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1ee9bd9239c339d714d657fac840c6d2a4f9c45f4f9ec7b0975113458be78db" +checksum = "0eee8098afad3fb0c54a9007aab6804558410503ad676d4633f9c2559a00ac0f" [[package]] name = "try-lock" @@ -5029,9 +5318,9 @@ checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" [[package]] name = "ucd-trie" -version = "0.1.5" +version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9e79c4d996edb816c91e4308506774452e55e95c3c9de07b6729e17e15a5ef81" +checksum = "ed646292ffc8188ef8ea4d1e0e0150fb15a5c2e12ad9b8fc191ae7a8a7f3c4b9" [[package]] name = "unarray" @@ -5056,9 +5345,9 @@ checksum = "92888ba5573ff080736b3648696b70cafad7d250551175acbaa4e0385b3e1460" [[package]] name = "unicode-ident" -version = "1.0.9" +version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0" +checksum = "301abaae475aa91687eb82514b328ab47a211a533026cb25fc3e519b86adfc3c" [[package]] name = "unicode-normalization" @@ -5101,9 +5390,9 @@ dependencies = [ [[package]] name = "urlencoding" -version = "2.1.2" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9" +checksum = "daf8dba3b7eb870caf1ddeed7bc9d2a049f3cfdfae7cb521b087cc33ae4c49da" [[package]] name = "urlparse" @@ -5113,11 +5402,11 @@ checksum = "110352d4e9076c67839003c7788d8604e24dcded13e0b375af3efaa8cf468517" [[package]] name = "utoipa" -version = "3.3.0" +version = "3.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "68ae74ef183fae36d650f063ae7bde1cacbe1cd7e72b617cbe1e985551878b98" +checksum = "de634b7f8178c9c246c88ea251f3a0215c9a4d80778db2d7bd4423a78b5170ec" dependencies = [ - "indexmap 1.9.3", + "indexmap 2.0.0", "serde", "serde_json", "utoipa-gen", @@ -5125,21 +5414,21 @@ dependencies = [ [[package]] name = "utoipa-gen" -version = "3.3.0" +version = "3.4.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ea8ac818da7e746a63285594cce8a96f5e00ee31994e655bd827569cb8b137b" +checksum = "0fcba79cb3e5020d9bcc8313cd5aadaf51d6d54a6b3fd08c3d0360ae6b3c83d0" dependencies = [ "proc-macro-error", "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", ] [[package]] name = "utoipa-swagger-ui" -version = "3.1.3" +version = "3.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "062bba5a3568e126ac72049a63254f4cb1da2eb713db0c1ab2a4c76be191db8c" +checksum = "84614caa239fb25b2bb373a52859ffd94605ceb256eeb1d63436325cf81e3653" dependencies = [ "actix-web", "mime_guess", @@ -5153,9 +5442,9 @@ dependencies = [ [[package]] name = "uuid" -version = "1.3.4" +version = "1.4.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fa2982af2eec27de306107c027578ff7f423d65f7250e40ce0fea8f45248b81" +checksum = "79daa5ed5740825c40b389c5e50312b9c86df53fccd33f281df655642b43869d" dependencies = [ "getrandom 0.2.10", "serde", @@ -5175,15 +5464,15 @@ checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" [[package]] name = "vergen" -version = "8.2.1" +version = "8.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8b3c89c2c7e50f33e4d35527e5bf9c11d6d132226dbbd1753f0fbe9f19ef88c6" +checksum = "bbc5ad0d9d26b2c49a5ab7da76c3e79d3ee37e7821799f8223fcb8f2f391a2e7" dependencies = [ "anyhow", "git2", "rustc_version", "rustversion", - "time 0.3.22", + "time 0.3.23", ] [[package]] @@ -5271,7 +5560,7 @@ dependencies = [ "once_cell", "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", "wasm-bindgen-shared", ] @@ -5305,7 +5594,7 @@ checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" dependencies = [ "proc-macro2", "quote", - "syn 2.0.18", + "syn 2.0.28", "wasm-bindgen-backend", "wasm-bindgen-shared", ] @@ -5340,7 +5629,7 @@ dependencies = [ "serde", "serde_derive", "serde_json", - "time 0.3.22", + "time 0.3.23", "unicode-segmentation", "url", ] @@ -5364,6 +5653,12 @@ dependencies = [ "webpki", ] +[[package]] +name = "weezl" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9193164d4de03a926d909d3bc7c30543cecb35400c02114792c2cae20d5e2dbb" + [[package]] name = "winapi" version = "0.3.9" @@ -5404,21 +5699,6 @@ dependencies = [ "windows-targets", ] -[[package]] -name = "windows-sys" -version = "0.42.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" -dependencies = [ - "windows_aarch64_gnullvm 0.42.2", - "windows_aarch64_msvc 0.42.2", - "windows_i686_gnu 0.42.2", - "windows_i686_msvc 0.42.2", - "windows_x86_64_gnu 0.42.2", - "windows_x86_64_gnullvm 0.42.2", - "windows_x86_64_msvc 0.42.2", -] - [[package]] name = "windows-sys" version = "0.48.0" @@ -5430,97 +5710,55 @@ dependencies = [ [[package]] name = "windows-targets" -version = "0.48.0" +version = "0.48.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5" +checksum = "05d4b17490f70499f20b9e791dcf6a299785ce8af4d709018206dc5b4953e95f" dependencies = [ - "windows_aarch64_gnullvm 0.48.0", - "windows_aarch64_msvc 0.48.0", - "windows_i686_gnu 0.48.0", - "windows_i686_msvc 0.48.0", - "windows_x86_64_gnu 0.48.0", - "windows_x86_64_gnullvm 0.48.0", - "windows_x86_64_msvc 0.48.0", + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", ] -[[package]] -name = "windows_aarch64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" - [[package]] name = "windows_aarch64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc" -[[package]] -name = "windows_aarch64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" - [[package]] name = "windows_aarch64_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3" -[[package]] -name = "windows_i686_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" - [[package]] name = "windows_i686_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241" -[[package]] -name = "windows_i686_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" - [[package]] name = "windows_i686_msvc" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00" -[[package]] -name = "windows_x86_64_gnu" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" - [[package]] name = "windows_x86_64_gnu" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1" -[[package]] -name = "windows_x86_64_gnullvm" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" - [[package]] name = "windows_x86_64_gnullvm" version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953" -[[package]] -name = "windows_x86_64_msvc" -version = "0.42.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" - [[package]] name = "windows_x86_64_msvc" version = "0.48.0" @@ -5529,9 +5767,9 @@ checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a" [[package]] name = "winnow" -version = "0.4.7" +version = "0.5.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca0ace3845f0d96209f0375e6d367e3eb87eb65d27d445bdc9f1843a26f39448" +checksum = "acaaa1190073b2b101e15083c38ee8ec891b5e05cbee516521e94ec008f61e64" dependencies = [ "memchr", ] @@ -5602,18 +5840,18 @@ dependencies = [ [[package]] name = "zstd" -version = "0.12.3+zstd.1.5.2" +version = "0.12.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "76eea132fb024e0e13fd9c2f5d5d595d8a967aa72382ac2f9d39fcc95afd0806" +checksum = "1a27595e173641171fc74a1232b7b1c7a7cb6e18222c11e9dfb9888fa424c53c" dependencies = [ "zstd-safe", ] [[package]] name = "zstd-safe" -version = "6.0.5+zstd.1.5.4" +version = "6.0.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d56d9e60b4b1758206c238a10165fbcae3ca37b01744e394c463463f6529d23b" +checksum = "ee98ffd0b48ee95e6c5168188e44a54550b1564d9d530ee21d5f0eaed1069581" dependencies = [ "libc", "zstd-sys", diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index dc2ad5370ee..e99f3c150d2 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -96,6 +96,7 @@ redis_interface = { version = "0.1.0", path = "../redis_interface" } router_derive = { version = "0.1.0", path = "../router_derive" } router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } +storage_impl = { version = "0.1.0", path = "../storage_impl"} [target.'cfg(not(target_os = "windows"))'.dependencies] signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"] } diff --git a/crates/router/src/configs/kms.rs b/crates/router/src/configs/kms.rs index 17ff6069d41..0491fb61fc6 100644 --- a/crates/router/src/configs/kms.rs +++ b/crates/router/src/configs/kms.rs @@ -44,3 +44,23 @@ impl KmsDecrypt for settings::ActiveKmsSecrets { Ok(self) } } + +#[async_trait::async_trait] +impl KmsDecrypt for settings::Database { + type Output = storage_impl::config::Database; + + async fn decrypt_inner( + mut self, + kms_client: &KmsClient, + ) -> CustomResult<Self::Output, KmsError> { + Ok(storage_impl::config::Database { + host: self.host, + port: self.port, + dbname: self.dbname, + username: self.username, + password: self.password.decrypt_inner(kms_client).await?.into(), + pool_size: self.pool_size, + connection_timeout: self.connection_timeout, + }) + } +} diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 9b09025edc6..29134fbfda4 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -432,6 +432,21 @@ pub struct Database { pub connection_timeout: u64, } +#[cfg(not(feature = "kms"))] +impl Into<storage_impl::config::Database> for Database { + fn into(self) -> storage_impl::config::Database { + storage_impl::config::Database { + username: self.username, + password: self.password, + host: self.host, + port: self.port, + dbname: self.dbname, + pool_size: self.pool_size, + connection_timeout: self.connection_timeout, + } + } +} + #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct SupportedConnectors { diff --git a/crates/router/src/connection.rs b/crates/router/src/connection.rs index 647b1b107d0..8b07d7bb5ce 100644 --- a/crates/router/src/connection.rs +++ b/crates/router/src/connection.rs @@ -84,7 +84,7 @@ pub async fn pg_connection_read( > { // If only OLAP is enabled get replica pool. #[cfg(all(feature = "olap", not(feature = "oltp")))] - let pool = &store.replica_pool; + let pool = &store.diesel_store.replica_pool; // If either one of these are true we need to get master pool. // 1. Only OLTP is enabled. @@ -95,7 +95,7 @@ pub async fn pg_connection_read( all(feature = "olap", feature = "oltp"), all(not(feature = "olap"), not(feature = "oltp")) ))] - let pool = &store.master_pool; + let pool = &store.diesel_store.master_pool; pool.get() .await @@ -110,7 +110,7 @@ pub async fn pg_connection_write( errors::StorageError, > { // Since all writes should happen to master DB only choose master DB. - let pool = &store.master_pool; + let pool = &store.diesel_store.master_pool; pool.get() .await diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index 327d56dfc2f..46d8c51b090 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -11,6 +11,7 @@ use external_services::kms::{self, decrypt::KmsDecrypt}; #[cfg(not(feature = "kms"))] use masking::PeekInterface; use redis_interface::{errors as redis_errors, PubsubInterface, RedisValue}; +use storage_impl::diesel as diesel_impl; use tokio::sync::oneshot; pub use self::{api::*, encryption::*}; @@ -18,7 +19,6 @@ use crate::{ async_spawn, cache::{CacheKind, ACCOUNTS_CACHE, CONFIG_CACHE}, configs::settings, - connection::{diesel_make_pg_pool, PgPool}, consts, core::errors, }; @@ -129,9 +129,10 @@ impl RedisConnInterface for Store { #[derive(Clone)] pub struct Store { - pub master_pool: PgPool, + #[cfg(not(feature = "olap"))] + pub diesel_store: diesel_impl::store::Store, #[cfg(feature = "olap")] - pub replica_pool: PgPool, + pub diesel_store: diesel_impl::store::ReplicaStore, pub redis_conn: Arc<redis_interface::RedisConnectionPool>, #[cfg(feature = "kv_store")] pub(crate) config: StoreConfig, @@ -178,20 +179,43 @@ impl Store { ) .await; + #[allow(clippy::expect_used)] Self { - master_pool: diesel_make_pg_pool( - &config.master_database, - test_transaction, + #[cfg(not(feature = "olap"))] + diesel_store: diesel_impl::store::Store::new( + #[cfg(not(feature = "kms"))] + &config.master_database.clone().into(), #[cfg(feature = "kms")] - kms_client, + &config + .master_database + .clone() + .decrypt_inner(kms_client) + .await + .expect("Failed to decrypt master database"), + test_transaction, ) .await, #[cfg(feature = "olap")] - replica_pool: diesel_make_pg_pool( - &config.replica_database, - test_transaction, + diesel_store: diesel_impl::store::ReplicaStore::new( + #[cfg(not(feature = "kms"))] + &config.master_database.clone().into(), #[cfg(feature = "kms")] - kms_client, + &config + .master_database + .clone() + .decrypt_inner(kms_client) + .await + .expect("Failed to decrypt master database"), + #[cfg(not(feature = "kms"))] + &config.replica_database.clone().into(), + #[cfg(feature = "kms")] + &config + .replica_database + .clone() + .decrypt_inner(kms_client) + .await + .expect("Failed to decrypt replica database"), + test_transaction, ) .await, redis_conn, diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml new file mode 100644 index 00000000000..06fdd25dc88 --- /dev/null +++ b/crates/storage_impl/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "storage_impl" +description = "Storage backend implementations for data structures in router" +version = "0.1.0" +edition.workspace = true +rust-version.workspace = true +readme = "README.md" +license.workspace = true + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +# First Party dependencies +masking = { version = "0.1.0", path = "../masking" } + +# Third party crates +bb8 = "0.8.1" +diesel = { version = "2.1.0", default-features = false, features = ["postgres"] } +async-bb8-diesel = { git = "https://github.com/oxidecomputer/async-bb8-diesel", rev = "be3d9bce50051d8c0e0c06078e8066cc27db3001" } +async-trait = "0.1.72" diff --git a/crates/storage_impl/README.md b/crates/storage_impl/README.md new file mode 100644 index 00000000000..c5b6c208698 --- /dev/null +++ b/crates/storage_impl/README.md @@ -0,0 +1,3 @@ +# Storage implementations + +Storage backend implementations for data structures & objects. diff --git a/crates/storage_impl/src/config.rs b/crates/storage_impl/src/config.rs new file mode 100644 index 00000000000..ad543b1942a --- /dev/null +++ b/crates/storage_impl/src/config.rs @@ -0,0 +1,12 @@ +use masking::Secret; + +#[derive(Debug, Clone)] +pub struct Database { + pub username: String, + pub password: Secret<String>, + pub host: String, + pub port: u16, + pub dbname: String, + pub pool_size: u32, + pub connection_timeout: u64, +} diff --git a/crates/storage_impl/src/diesel.rs b/crates/storage_impl/src/diesel.rs new file mode 100644 index 00000000000..55c88cbf3d2 --- /dev/null +++ b/crates/storage_impl/src/diesel.rs @@ -0,0 +1 @@ +pub mod store; diff --git a/crates/storage_impl/src/diesel/store.rs b/crates/storage_impl/src/diesel/store.rs new file mode 100644 index 00000000000..821d1e6715f --- /dev/null +++ b/crates/storage_impl/src/diesel/store.rs @@ -0,0 +1,84 @@ +use async_bb8_diesel::{AsyncConnection, ConnectionError}; +use bb8::CustomizeConnection; +use diesel::PgConnection; +use masking::PeekInterface; + +use crate::config::Database; + +pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>; +pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>; + +#[derive(Clone)] +pub struct Store { + pub master_pool: PgPool, +} + +impl Store { + pub async fn new(config: &Database, test_transaction: bool) -> Self { + Self { + master_pool: diesel_make_pg_pool(config, test_transaction).await, + } + } +} + +#[derive(Clone)] +pub struct ReplicaStore { + pub master_pool: PgPool, + pub replica_pool: PgPool, +} + +impl ReplicaStore { + pub async fn new( + master_config: &Database, + replica_config: &Database, + test_transaction: bool, + ) -> Self { + let master_pool = diesel_make_pg_pool(master_config, test_transaction).await; + let replica_pool = diesel_make_pg_pool(replica_config, test_transaction).await; + Self { + master_pool, + replica_pool, + } + } +} + +#[allow(clippy::expect_used)] +pub async fn diesel_make_pg_pool(database: &Database, test_transaction: bool) -> PgPool { + let database_url = format!( + "postgres://{}:{}@{}:{}/{}", + database.username, + database.password.peek(), + database.host, + database.port, + database.dbname + ); + let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url); + let mut pool = bb8::Pool::builder() + .max_size(database.pool_size) + .connection_timeout(std::time::Duration::from_secs(database.connection_timeout)); + + if test_transaction { + pool = pool.connection_customizer(Box::new(TestTransaction)); + } + + pool.build(manager) + .await + .expect("Failed to create PostgreSQL connection pool") +} + +#[derive(Debug)] +struct TestTransaction; + +#[async_trait::async_trait] +impl CustomizeConnection<PgPooledConn, ConnectionError> for TestTransaction { + #[allow(clippy::unwrap_used)] + async fn on_acquire(&self, conn: &mut PgPooledConn) -> Result<(), ConnectionError> { + use diesel::Connection; + + conn.run(|conn| { + conn.begin_test_transaction().unwrap(); + Ok(()) + }) + .await + } +} diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs new file mode 100644 index 00000000000..55e9d3d1867 --- /dev/null +++ b/crates/storage_impl/src/lib.rs @@ -0,0 +1,2 @@ +pub mod config; +pub mod diesel; diff --git a/crates/storage_impl/src/redis.rs b/crates/storage_impl/src/redis.rs new file mode 100644 index 00000000000..e69de29bb2d diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index 0063db94984..39b4bccd2b4 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -5921,7 +5921,7 @@ "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins", "example": 900, "nullable": true, - "minimum": 0.0 + "minimum": 0 }, "organization_id": { "type": "string", @@ -6215,7 +6215,7 @@ "format": "int32", "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins", "nullable": true, - "minimum": 0.0 + "minimum": 0 } } }, @@ -6936,13 +6936,13 @@ "type": "integer", "format": "int64", "description": "Timestamp at which session is requested", - "minimum": 0.0 + "minimum": 0 }, "expires_at": { "type": "integer", "format": "int64", "description": "Timestamp at which session expires", - "minimum": 0.0 + "minimum": 0 }, "merchant_session_identifier": { "type": "string", @@ -6976,7 +6976,7 @@ "type": "integer", "format": "int32", "description": "The number of retries to get the session response", - "minimum": 0.0 + "minimum": 0 }, "psp_id": { "type": "string", @@ -7030,7 +7030,7 @@ "format": "int32", "description": "The quantity of the product to be purchased", "example": 1, - "minimum": 0.0 + "minimum": 0 } } }, @@ -7053,7 +7053,7 @@ "format": "int32", "description": "The quantity of the product to be purchased", "example": 1, - "minimum": 0.0 + "minimum": 0 }, "amount": { "type": "integer", @@ -7365,6 +7365,7 @@ "$ref": "#/components/schemas/AuthenticationType" } ], + "default": "three_ds", "nullable": true }, "cancellation_reason": { @@ -7553,7 +7554,7 @@ "size": { "type": "integer", "description": "The number of payments included in the list", - "minimum": 0.0 + "minimum": 0 }, "data": { "type": "array", @@ -8204,7 +8205,7 @@ "description": "The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,", "example": 6540, "nullable": true, - "minimum": 0.0 + "minimum": 0 }, "routing": { "allOf": [ @@ -8338,6 +8339,7 @@ "$ref": "#/components/schemas/AuthenticationType" } ], + "default": "three_ds", "nullable": true }, "payment_method_data": { @@ -8538,7 +8540,7 @@ "description": "The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,", "example": 6540, "nullable": true, - "minimum": 0.0 + "minimum": 0 }, "routing": { "allOf": [ @@ -8672,6 +8674,7 @@ "$ref": "#/components/schemas/AuthenticationType" } ], + "default": "three_ds", "nullable": true }, "payment_method_data": { @@ -8875,7 +8878,12 @@ "maxLength": 255 }, "status": { - "$ref": "#/components/schemas/IntentStatus" + "allOf": [ + { + "$ref": "#/components/schemas/IntentStatus" + } + ], + "default": "requires_confirmation" }, "amount": { "type": "integer", @@ -8889,7 +8897,7 @@ "description": "The maximum amount that could be captured from the payment", "example": 6540, "nullable": true, - "minimum": 100.0 + "minimum": 100 }, "amount_received": { "type": "integer", @@ -8897,7 +8905,7 @@ "description": "The amount which is already captured from the payment", "example": 6540, "nullable": true, - "minimum": 100.0 + "minimum": 100 }, "connector": { "type": "string", @@ -9077,6 +9085,7 @@ "$ref": "#/components/schemas/AuthenticationType" } ], + "default": "three_ds", "nullable": true }, "statement_descriptor_name": { @@ -9962,7 +9971,7 @@ "size": { "type": "integer", "description": "The number of refunds included in the list", - "minimum": 0.0 + "minimum": 0 }, "data": { "type": "array", @@ -10007,7 +10016,7 @@ "description": "Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the full payment amount", "example": 6540, "nullable": true, - "minimum": 100.0 + "minimum": 100 }, "reason": { "type": "string", @@ -10022,6 +10031,7 @@ "$ref": "#/components/schemas/RefundType" } ], + "default": "Instant", "nullable": true }, "metadata": {
refactor
Add a separate crate to represent store implementations (#1853)
1b5b566387da83a2582216e05be4ceb1aa7251be
2024-05-07 17:18:49
Chethan Rao
refactor: store `card_cvc` in extended_card_info and extend max ttl (#4568)
false
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs index e845317b693..3beeb9071a2 100644 --- a/crates/api_models/src/admin.rs +++ b/crates/api_models/src/admin.rs @@ -1113,7 +1113,7 @@ pub struct ExtendedCardInfoConfig { #[schema(value_type = String)] pub public_key: Secret<String>, /// TTL for extended card info - #[schema(default = 900, maximum = 3600, value_type = u16)] + #[schema(default = 900, maximum = 7200, value_type = u16)] #[serde(default)] pub ttl_in_secs: TtlForExtendedCardInfo, } @@ -1137,7 +1137,7 @@ impl<'de> Deserialize<'de> for TtlForExtendedCardInfo { // Check if value exceeds the maximum allowed if value > consts::MAX_TTL_FOR_EXTENDED_CARD_INFO { Err(serde::de::Error::custom( - "ttl_in_secs must be less than or equal to 3600 (1hr)", + "ttl_in_secs must be less than or equal to 7200 (2hrs)", )) } else { Ok(Self(value)) diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 0e46eb19931..69b4700acbc 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -934,6 +934,10 @@ pub struct ExtendedCardInfo { #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, + /// The CVC number for the card + #[schema(value_type = String, example = "242")] + pub card_cvc: Secret<String>, + /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, @@ -959,6 +963,7 @@ impl From<Card> for ExtendedCardInfo { card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, + card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs index 509056152eb..94b53766db0 100644 --- a/crates/common_utils/src/consts.rs +++ b/crates/common_utils/src/consts.rs @@ -82,4 +82,4 @@ pub const DEFAULT_ENABLE_SAVED_PAYMENT_METHOD: bool = false; pub const DEFAULT_TTL_FOR_EXTENDED_CARD_INFO: u16 = 15 * 60; /// Max ttl for Extended card info in redis (in seconds) -pub const MAX_TTL_FOR_EXTENDED_CARD_INFO: u16 = 60 * 60; +pub const MAX_TTL_FOR_EXTENDED_CARD_INFO: u16 = 60 * 60 * 2; diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json index c45a4aaaa10..ec7d820a139 100644 --- a/openapi/openapi_spec.json +++ b/openapi/openapi_spec.json @@ -8717,7 +8717,8 @@ "card_number", "card_exp_month", "card_exp_year", - "card_holder_name" + "card_holder_name", + "card_cvc" ], "properties": { "card_number": { @@ -8740,6 +8741,11 @@ "description": "The card holder's name", "example": "John Test" }, + "card_cvc": { + "type": "string", + "description": "The CVC number for the card", + "example": "242" + }, "card_issuer": { "type": "string", "description": "The name of the issuer of card", @@ -8786,7 +8792,7 @@ "format": "int32", "description": "TTL for extended card info", "default": 900, - "maximum": 3600, + "maximum": 7200, "minimum": 0 } }
refactor
store `card_cvc` in extended_card_info and extend max ttl (#4568)
55bb117e1ddc147d7309823dc593bd1a05fe69a9
2023-05-31 13:13:55
Kartikeya Hegde
fix(router): subscriber return type (#1292)
false
diff --git a/crates/router/src/services.rs b/crates/router/src/services.rs index 42f9602d7af..1e1bd40db63 100644 --- a/crates/router/src/services.rs +++ b/crates/router/src/services.rs @@ -23,10 +23,7 @@ use crate::{ #[async_trait::async_trait] pub trait PubSubInterface { - async fn subscribe( - &self, - channel: &str, - ) -> errors::CustomResult<usize, redis_errors::RedisError>; + async fn subscribe(&self, channel: &str) -> errors::CustomResult<(), redis_errors::RedisError>; async fn publish<'a>( &self, @@ -40,10 +37,7 @@ pub trait PubSubInterface { #[async_trait::async_trait] impl PubSubInterface for redis_interface::RedisConnectionPool { #[inline] - async fn subscribe( - &self, - channel: &str, - ) -> errors::CustomResult<usize, redis_errors::RedisError> { + async fn subscribe(&self, channel: &str) -> errors::CustomResult<(), redis_errors::RedisError> { // Spawns a task that will automatically re-subscribe to any channels or channel patterns used by the client. self.subscriber.manage_subscriptions();
fix
subscriber return type (#1292)
c27a235edc9dcfc152b3c57f4efd0db82548ac69
2024-03-09 10:42:30
github-actions
chore(version): 2024.03.09.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 30a13b69623..cc07e5f63de 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,25 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.03.09.0 + +### Features + +- **core:** Add core functions for external authentication ([#3969](https://github.com/juspay/hyperswitch/pull/3969)) ([`897e264`](https://github.com/juspay/hyperswitch/commit/897e264ad9e26df9877a18eef26a24e05de78528)) +- **payment_link:** Add shimmer page before payment_link loads starts ([#4014](https://github.com/juspay/hyperswitch/pull/4014)) ([`ba9d465`](https://github.com/juspay/hyperswitch/commit/ba9d465483edcefeacc7ace0fc8efc86ca0f813c)) + +### Bug Fixes + +- **deserialization:** Error message is different when invalid data is passed for payment method data ([#4022](https://github.com/juspay/hyperswitch/pull/4022)) ([`f1fe295`](https://github.com/juspay/hyperswitch/commit/f1fe295475adb0e827bd713be036687da662b361)) + +### Miscellaneous Tasks + +- **postman:** Update Postman collection files ([`a7d0487`](https://github.com/juspay/hyperswitch/commit/a7d04873d63c1f007d0081f02ba9a373e24ae882)) + +**Full Changelog:** [`2024.03.08.0...2024.03.09.0`](https://github.com/juspay/hyperswitch/compare/2024.03.08.0...2024.03.09.0) + +- - - + ## 2024.03.08.0 ### Features
chore
2024.03.09.0
1ee11849d4a60afbf3d05103cb491a11e905b811
2023-10-12 13:06:09
Hrithikesh
fix: percentage float inconsistency problem and api models changes to support surcharge feature (#2550)
false
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 662129204c2..ce61d30d36f 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -21,6 +21,7 @@ mime = "0.3.17" reqwest = { version = "0.11.18", optional = true } serde = { version = "1.0.163", features = ["derive"] } serde_json = "1.0.96" +serde_with = "3.0.0" strum = { version = "0.24.1", features = ["derive"] } time = { version = "0.3.21", features = ["serde", "serde-well-known", "std"] } url = { version = "2.4.0", features = ["serde"] } diff --git a/crates/api_models/src/lib.rs b/crates/api_models/src/lib.rs index caff4e1780c..29ad9be051b 100644 --- a/crates/api_models/src/lib.rs +++ b/crates/api_models/src/lib.rs @@ -16,6 +16,5 @@ pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; pub mod refunds; -pub mod types; pub mod verifications; pub mod webhooks; diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs index eb15f0e3bc3..9d3983e73a1 100644 --- a/crates/api_models/src/payment_methods.rs +++ b/crates/api_models/src/payment_methods.rs @@ -3,8 +3,10 @@ use std::collections::HashMap; use cards::CardNumber; use common_utils::{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH, crypto::OptionalEncryptableName, pii, + types::Percentage, }; use serde::de; +use serde_with::serde_as; use utoipa::ToSchema; #[cfg(feature = "payouts")] @@ -12,7 +14,6 @@ use crate::payouts; use crate::{ admin, enums as api_enums, payments::{self, BankCodeResponse}, - types::Percentage, }; #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] @@ -251,12 +252,28 @@ pub struct PaymentExperienceTypes { pub eligible_connectors: Vec<String>, } -#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] +#[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct CardNetworkTypes { /// The card network enabled #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: api_enums::CardNetwork, + /// surcharge details for this card network + #[schema(example = r#" + { + "surcharge": { + "type": "rate", + "value": { + "percentage": 2.5 + } + }, + "tax_on_surcharge": { + "percentage": 1.5 + } + } + "#)] + pub surcharge_details: Option<SurchargeDetailsResponse>, + /// The list of eligible connectors for a given card network #[schema(example = json!(["stripe", "adyen"]))] pub eligible_connectors: Vec<String>, @@ -304,18 +321,31 @@ pub struct ResponsePaymentMethodTypes { } } "#)] - pub surcharge_details: Option<SurchargeDetails>, + pub surcharge_details: Option<SurchargeDetailsResponse>, } -#[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] -pub struct SurchargeDetails { +pub struct SurchargeDetailsResponse { /// surcharge value - surcharge: Surcharge, + pub surcharge: Surcharge, /// tax on surcharge value - tax_on_surcharge: Option<Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>>, + pub tax_on_surcharge: Option<Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>>, + /// surcharge amount for this payment + pub surcharge_amount: i64, + /// tax on surcharge amount for this payment + pub tax_on_surcharge_amount: i64, + /// sum of original amount, + pub final_amount: i64, +} + +#[serde_as] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +pub struct SurchargeMetadata { + #[serde_as(as = "HashMap<_, _>")] + pub surcharge_results: HashMap<String, SurchargeDetailsResponse>, } -#[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type", content = "value")] pub enum Surcharge { /// Fixed Surcharge value diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 01edef87a67..08646a4a0b3 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -795,6 +795,168 @@ pub enum PaymentMethodData { GiftCard(Box<GiftCardData>), } +pub trait GetPaymentMethodType { + fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; +} + +impl GetPaymentMethodType for CardRedirectData { + fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { + match self { + Self::Knet {} => api_enums::PaymentMethodType::Knet, + Self::Benefit {} => api_enums::PaymentMethodType::Benefit, + Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, + } + } +} + +impl GetPaymentMethodType for WalletData { + fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { + match self { + Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, + Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, + Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, + Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, + Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, + Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, + Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { + api_enums::PaymentMethodType::ApplePay + } + Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, + Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { + api_enums::PaymentMethodType::GooglePay + } + Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, + Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, + Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, + Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, + Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, + Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, + Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, + Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { + api_enums::PaymentMethodType::WeChatPay + } + Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, + Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, + } + } +} + +impl GetPaymentMethodType for PayLaterData { + fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { + match self { + Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, + Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, + Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, + Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, + Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, + Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, + Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, + Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, + } + } +} + +impl GetPaymentMethodType for BankRedirectData { + fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { + match self { + Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, + Self::Bizum {} => api_enums::PaymentMethodType::Bizum, + Self::Blik { .. } => api_enums::PaymentMethodType::Blik, + Self::Eps { .. } => api_enums::PaymentMethodType::Eps, + Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, + Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, + Self::Interac { .. } => api_enums::PaymentMethodType::Interac, + Self::OnlineBankingCzechRepublic { .. } => { + api_enums::PaymentMethodType::OnlineBankingCzechRepublic + } + Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, + Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, + Self::OnlineBankingSlovakia { .. } => { + api_enums::PaymentMethodType::OnlineBankingSlovakia + } + Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, + Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, + Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, + Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, + Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, + Self::OnlineBankingThailand { .. } => { + api_enums::PaymentMethodType::OnlineBankingThailand + } + } + } +} + +impl GetPaymentMethodType for BankDebitData { + fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { + match self { + Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, + Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, + Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, + Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, + } + } +} + +impl GetPaymentMethodType for BankTransferData { + fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { + match self { + Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, + Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::Sepa, + Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, + Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, + Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, + Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, + Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, + Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, + Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, + Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, + Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, + Self::Pix {} => api_enums::PaymentMethodType::Pix, + Self::Pse {} => api_enums::PaymentMethodType::Pse, + } + } +} + +impl GetPaymentMethodType for CryptoData { + fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { + api_enums::PaymentMethodType::CryptoCurrency + } +} + +impl GetPaymentMethodType for UpiData { + fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { + api_enums::PaymentMethodType::UpiCollect + } +} +impl GetPaymentMethodType for VoucherData { + fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { + match self { + Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, + Self::Efecty => api_enums::PaymentMethodType::Efecty, + Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, + Self::RedCompra => api_enums::PaymentMethodType::RedCompra, + Self::RedPagos => api_enums::PaymentMethodType::RedPagos, + Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, + Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, + Self::Oxxo => api_enums::PaymentMethodType::Oxxo, + Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, + Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, + Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, + Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, + Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, + Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, + } + } +} +impl GetPaymentMethodType for GiftCardData { + fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { + match self { + Self::Givex(_) => api_enums::PaymentMethodType::Givex, + Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, + } + } +} + #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs index 01c9c80fcec..ca6bba48006 100644 --- a/crates/common_utils/src/lib.rs +++ b/crates/common_utils/src/lib.rs @@ -13,6 +13,7 @@ pub mod pii; pub mod request; #[cfg(feature = "signals")] pub mod signals; +pub mod types; pub mod validation; /// Date-time utilities. diff --git a/crates/api_models/src/types.rs b/crates/common_utils/src/types.rs similarity index 52% rename from crates/api_models/src/types.rs rename to crates/common_utils/src/types.rs index bd594ba6276..d745334a21e 100644 --- a/crates/api_models/src/types.rs +++ b/crates/common_utils/src/types.rs @@ -1,46 +1,68 @@ -use common_utils::errors::{ApiModelsError, CustomResult}; -use error_stack::ResultExt; +//! Types that can be used in other crates +use error_stack::{IntoReport, ResultExt}; use serde::{de::Visitor, Deserialize, Deserializer}; -use utoipa::ToSchema; -#[derive(Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] +use crate::errors::{ApiModelsError, CustomResult}; + +/// Represents Percentage Value between 0 and 100 both inclusive +#[derive(Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct Percentage<const PRECISION: u8> { // this value will range from 0 to 100, decimal length defined by precision macro /// Percentage value ranging between 0 and 100 - #[schema(example = 2.5)] percentage: f32, } fn get_invalid_percentage_error_message(precision: u8) -> String { format!( - "value should be between 0 to 100 and precise to only upto {} decimal digits", + "value should be a float between 0 to 100 and precise to only upto {} decimal digits", precision ) } impl<const PRECISION: u8> Percentage<PRECISION> { - pub fn from_float(value: f32) -> CustomResult<Self, ApiModelsError> { - if Self::is_valid_value(value) { - Ok(Self { percentage: value }) + /// construct percentage using a string representation of float value + pub fn from_string(value: String) -> CustomResult<Self, ApiModelsError> { + if Self::is_valid_string_value(&value)? { + Ok(Self { + percentage: value + .parse() + .into_report() + .change_context(ApiModelsError::InvalidPercentageValue)?, + }) } else { Err(ApiModelsError::InvalidPercentageValue.into()) .attach_printable(get_invalid_percentage_error_message(PRECISION)) } } + /// function to get percentage value pub fn get_percentage(&self) -> f32 { self.percentage } - fn is_valid_value(value: f32) -> bool { - Self::is_valid_range(value) && Self::is_valid_precision_length(value) + fn is_valid_string_value(value: &str) -> CustomResult<bool, ApiModelsError> { + let float_value = Self::is_valid_float_string(value)?; + Ok(Self::is_valid_range(float_value) && Self::is_valid_precision_length(value)) + } + fn is_valid_float_string(value: &str) -> CustomResult<f32, ApiModelsError> { + value + .parse() + .into_report() + .change_context(ApiModelsError::InvalidPercentageValue) } fn is_valid_range(value: f32) -> bool { (0.0..=100.0).contains(&value) } - fn is_valid_precision_length(value: f32) -> bool { - let multiplier = f32::powf(10.0, PRECISION.into()); - let multiplied_value = value * multiplier; - // if fraction part is 0, then the percentage value is valid - multiplied_value.fract() == 0.0 + fn is_valid_precision_length(value: &str) -> bool { + if value.contains('.') { + // if string has '.' then take the decimal part and verify precision length + match value.split('.').last() { + Some(decimal_part) => decimal_part.trim_end_matches('0').len() <= PRECISION.into(), + // will never be None + None => false, + } + } else { + // if there is no '.' then it is a whole number with no decimal part. So return true + true + } } } @@ -62,17 +84,17 @@ impl<'de, const PRECISION: u8> Visitor<'de> for PercentageVisitor<PRECISION> { if percentage_value.is_some() { return Err(serde::de::Error::duplicate_field("percentage")); } - percentage_value = Some(map.next_value::<f32>()?); + percentage_value = Some(map.next_value::<serde_json::Value>()?); } else { // Ignore unknown fields let _: serde::de::IgnoredAny = map.next_value()?; } } if let Some(value) = percentage_value { - let str_value = value.to_string(); - Ok(Percentage::from_float(value).map_err(|_| { + let string_value = value.to_string(); + Ok(Percentage::from_string(string_value.clone()).map_err(|_| { serde::de::Error::invalid_value( - serde::de::Unexpected::Other(&format!("percentage value `{}`", str_value)), + serde::de::Unexpected::Other(&format!("percentage value {}", string_value)), &&*get_invalid_percentage_error_message(PRECISION), ) })?) diff --git a/crates/api_models/tests/percentage.rs b/crates/common_utils/tests/percentage.rs similarity index 60% rename from crates/api_models/tests/percentage.rs rename to crates/common_utils/tests/percentage.rs index 3e137a2592d..95c11252337 100644 --- a/crates/api_models/tests/percentage.rs +++ b/crates/common_utils/tests/percentage.rs @@ -1,12 +1,11 @@ #![allow(clippy::panic_in_result_fn)] -use api_models::types::Percentage; -use common_utils::errors::ApiModelsError; +use common_utils::{errors::ApiModelsError, types::Percentage}; const PRECISION_2: u8 = 2; const PRECISION_0: u8 = 0; #[test] fn invalid_range_more_than_100() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { - let percentage = Percentage::<PRECISION_2>::from_float(100.01); + let percentage = Percentage::<PRECISION_2>::from_string("100.01".to_string()); assert!(percentage.is_err()); if let Err(err) = percentage { assert_eq!( @@ -18,7 +17,7 @@ fn invalid_range_more_than_100() -> Result<(), Box<dyn std::error::Error + Send } #[test] fn invalid_range_less_than_0() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { - let percentage = Percentage::<PRECISION_2>::from_float(-0.01); + let percentage = Percentage::<PRECISION_2>::from_string("-0.01".to_string()); assert!(percentage.is_err()); if let Err(err) = percentage { assert_eq!( @@ -28,21 +27,35 @@ fn invalid_range_less_than_0() -> Result<(), Box<dyn std::error::Error + Send + } Ok(()) } + +#[test] +fn invalid_string() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { + let percentage = Percentage::<PRECISION_2>::from_string("-0.01ed".to_string()); + assert!(percentage.is_err()); + if let Err(err) = percentage { + assert_eq!( + *err.current_context(), + ApiModelsError::InvalidPercentageValue + ) + } + Ok(()) +} + #[test] fn valid_range() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { - let percentage = Percentage::<PRECISION_2>::from_float(2.22); + let percentage = Percentage::<PRECISION_2>::from_string("2.22".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 2.22) } - let percentage = Percentage::<PRECISION_2>::from_float(0.0); + let percentage = Percentage::<PRECISION_2>::from_string("0.05".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { - assert_eq!(percentage.get_percentage(), 0.0) + assert_eq!(percentage.get_percentage(), 0.05) } - let percentage = Percentage::<PRECISION_2>::from_float(100.0); + let percentage = Percentage::<PRECISION_2>::from_string("100.0".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 100.0) @@ -51,19 +64,19 @@ fn valid_range() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { } #[test] fn valid_precision() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { - let percentage = Percentage::<PRECISION_2>::from_float(2.2); + let percentage = Percentage::<PRECISION_2>::from_string("2.2".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 2.2) } - let percentage = Percentage::<PRECISION_2>::from_float(2.20000); + let percentage = Percentage::<PRECISION_2>::from_string("2.20000".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 2.2) } - let percentage = Percentage::<PRECISION_0>::from_float(2.0); + let percentage = Percentage::<PRECISION_0>::from_string("2.0".to_string()); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { assert_eq!(percentage.get_percentage(), 2.0) @@ -74,7 +87,7 @@ fn valid_precision() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { #[test] fn invalid_precision() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { - let percentage = Percentage::<PRECISION_2>::from_float(2.221); + let percentage = Percentage::<PRECISION_2>::from_string("2.221".to_string()); assert!(percentage.is_err()); if let Err(err) = percentage { assert_eq!( @@ -87,15 +100,47 @@ fn invalid_precision() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { #[test] fn deserialization_test_ok() -> Result<(), Box<dyn std::error::Error + Send + Sync>> { + let mut decimal = 0; + let mut integer = 0; + // check for all percentage values from 0 to 100 + while integer <= 100 { + let json_string = format!( + r#" + {{ + "percentage" : {}.{} + }} + "#, + integer, decimal + ); + let percentage = serde_json::from_str::<Percentage<PRECISION_2>>(&json_string); + assert!(percentage.is_ok()); + if let Ok(percentage) = percentage { + assert_eq!( + percentage.get_percentage(), + format!("{}.{}", integer, decimal) + .parse::<f32>() + .unwrap_or_default() + ) + } + if integer == 100 { + break; + } + decimal += 1; + if decimal == 100 { + decimal = 0; + integer += 1; + } + } + let json_string = r#" { - "percentage" : 12.4 + "percentage" : 18.7 } "#; let percentage = serde_json::from_str::<Percentage<PRECISION_2>>(json_string); assert!(percentage.is_ok()); if let Ok(percentage) = percentage { - assert_eq!(percentage.get_percentage(), 12.4) + assert_eq!(percentage.get_percentage(), 18.7) } let json_string = r#" @@ -122,7 +167,7 @@ fn deserialization_test_err() -> Result<(), Box<dyn std::error::Error + Send + S let percentage = serde_json::from_str::<Percentage<PRECISION_0>>(json_string); assert!(percentage.is_err()); if let Err(err) = percentage { - assert_eq!(err.to_string(), "invalid value: percentage value `12.4`, expected value should be between 0 to 100 and precise to only upto 0 decimal digits at line 4 column 9".to_string()) + assert_eq!(err.to_string(), "invalid value: percentage value 12.4, expected value should be a float between 0 to 100 and precise to only upto 0 decimal digits at line 4 column 9".to_string()) } // invalid percentage value @@ -134,7 +179,7 @@ fn deserialization_test_err() -> Result<(), Box<dyn std::error::Error + Send + S let percentage = serde_json::from_str::<Percentage<PRECISION_2>>(json_string); assert!(percentage.is_err()); if let Err(err) = percentage { - assert_eq!(err.to_string(), "invalid value: percentage value `123.42`, expected value should be between 0 to 100 and precise to only upto 2 decimal digits at line 4 column 9".to_string()) + assert_eq!(err.to_string(), "invalid value: percentage value 123.42, expected value should be a float between 0 to 100 and precise to only upto 2 decimal digits at line 4 column 9".to_string()) } // missing percentage field @@ -146,7 +191,6 @@ fn deserialization_test_err() -> Result<(), Box<dyn std::error::Error + Send + S let percentage = serde_json::from_str::<Percentage<PRECISION_2>>(json_string); assert!(percentage.is_err()); if let Err(err) = percentage { - dbg!(err.to_string()); assert_eq!( err.to_string(), "missing field `percentage` at line 4 column 9".to_string() diff --git a/crates/data_models/src/payments/payment_attempt.rs b/crates/data_models/src/payments/payment_attempt.rs index a372a77f064..29a83a30997 100644 --- a/crates/data_models/src/payments/payment_attempt.rs +++ b/crates/data_models/src/payments/payment_attempt.rs @@ -294,6 +294,10 @@ pub enum PaymentAttemptUpdate { MultipleCaptureCountUpdate { multiple_capture_count: i16, }, + SurchargeAmountUpdate { + surcharge_amount: Option<i64>, + tax_amount: Option<i64>, + }, AmountToCaptureUpdate { status: storage_enums::AttemptStatus, amount_capturable: i64, diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index ebda08d759e..97f45a86830 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -214,6 +214,10 @@ pub enum PaymentAttemptUpdate { status: storage_enums::AttemptStatus, amount_capturable: i64, }, + SurchargeAmountUpdate { + surcharge_amount: Option<i64>, + tax_amount: Option<i64>, + }, PreprocessingUpdate { status: storage_enums::AttemptStatus, payment_method_id: Option<Option<String>>, @@ -257,6 +261,8 @@ pub struct PaymentAttemptUpdateInternal { capture_method: Option<storage_enums::CaptureMethod>, connector_response_reference_id: Option<String>, multiple_capture_count: Option<i16>, + surcharge_amount: Option<i64>, + tax_amount: Option<i64>, amount_capturable: Option<i64>, surcharge_metadata: Option<serde_json::Value>, } @@ -507,6 +513,14 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { surcharge_metadata, ..Default::default() }, + PaymentAttemptUpdate::SurchargeAmountUpdate { + surcharge_amount, + tax_amount, + } => Self { + surcharge_amount, + tax_amount, + ..Default::default() + }, } } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index deccf98d83e..88ea12388db 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -1172,6 +1172,7 @@ pub async fn list_payment_methods( card_network_types.push(CardNetworkTypes { card_network: card_network_type.0.clone(), eligible_connectors: card_network_type.1.clone(), + surcharge_details: None, }) } diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index d65e53c95ba..14b97fec42e 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -9,7 +9,11 @@ pub mod types; use std::{fmt::Debug, marker::PhantomData, ops::Deref, time::Instant}; -use api_models::{enums, payments::HeaderPayload}; +use api_models::{ + enums, + payment_methods::{SurchargeDetailsResponse, SurchargeMetadata}, + payments::HeaderPayload, +}; use common_utils::{ext_traits::AsyncExt, pii}; use data_models::mandates::MandateData; use diesel_models::{ephemeral_key, fraud_check::FraudCheck}; @@ -814,6 +818,18 @@ where { let call_connectors_start_time = Instant::now(); let mut join_handlers = Vec::with_capacity(connectors.len()); + let surcharge_metadata = payment_data + .payment_attempt + .surcharge_metadata + .as_ref() + .map(|surcharge_metadata_value| { + surcharge_metadata_value + .clone() + .parse_value::<SurchargeMetadata>("SurchargeMetadata") + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to Deserialize SurchargeMetadata")?; for session_connector_data in connectors.iter() { let connector_id = session_connector_data.connector.connector.id(); @@ -827,6 +843,14 @@ where false, ) .await?; + payment_data.surcharge_details = + surcharge_metadata.as_ref().and_then(|surcharge_metadata| { + let payment_method_type = session_connector_data.payment_method_type; + surcharge_metadata + .surcharge_results + .get(&payment_method_type.to_string()) + .cloned() + }); let router_data = payment_data .construct_router_data( @@ -1460,6 +1484,7 @@ where pub recurring_mandate_payment_data: Option<RecurringMandatePaymentData>, pub ephemeral_key: Option<ephemeral_key::EphemeralKey>, pub redirect_response: Option<api_models::payments::RedirectResponse>, + pub surcharge_details: Option<SurchargeDetailsResponse>, pub frm_message: Option<FraudCheck>, } diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs index d7b3d743b95..edb6478efec 100644 --- a/crates/router/src/core/payments/operations/payment_approve.rs +++ b/crates/router/src/core/payments/operations/payment_approve.rs @@ -251,6 +251,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ephemeral_key: None, multiple_capture_data: None, redirect_response, + surcharge_details: None, frm_message: frm_response.ok(), }, Some(CustomerDetails { diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs index 72006946c20..d92d86e7923 100644 --- a/crates/router/src/core/payments/operations/payment_cancel.rs +++ b/crates/router/src/core/payments/operations/payment_cancel.rs @@ -171,6 +171,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ephemeral_key: None, multiple_capture_data: None, redirect_response: None, + surcharge_details: None, frm_message: None, }, None, diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs index bd64ebac632..eb88265bfc8 100644 --- a/crates/router/src/core/payments/operations/payment_capture.rs +++ b/crates/router/src/core/payments/operations/payment_capture.rs @@ -229,6 +229,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ephemeral_key: None, multiple_capture_data, redirect_response: None, + surcharge_details: None, frm_message: None, }, None, diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs index 506a9b4421c..02965290224 100644 --- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs +++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs @@ -246,6 +246,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ephemeral_key: None, multiple_capture_data: None, redirect_response, + surcharge_details: None, frm_message: None, }, Some(CustomerDetails { diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index 761264e4798..a40de370b36 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -359,6 +359,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ephemeral_key: None, multiple_capture_data: None, redirect_response: None, + surcharge_details: None, frm_message: None, }, Some(customer_details), diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 479b0e2ccee..0be92418183 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -294,6 +294,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ephemeral_key, multiple_capture_data: None, redirect_response: None, + surcharge_details: None, frm_message: None, }, Some(customer_details), 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 0ff49279f3c..1b33f2dddb8 100644 --- a/crates/router/src/core/payments/operations/payment_method_validate.rs +++ b/crates/router/src/core/payments/operations/payment_method_validate.rs @@ -195,6 +195,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ephemeral_key: None, multiple_capture_data: None, redirect_response: None, + surcharge_details: None, frm_message: None, }, Some(payments::CustomerDetails { diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs index c9a24b8fb84..2e9bd3eb9ed 100644 --- a/crates/router/src/core/payments/operations/payment_reject.rs +++ b/crates/router/src/core/payments/operations/payment_reject.rs @@ -157,6 +157,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ephemeral_key: None, multiple_capture_data: None, redirect_response: None, + surcharge_details: None, frm_message: frm_response.ok(), }, None, diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 261275296f1..cc91482440b 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -191,6 +191,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ephemeral_key: None, multiple_capture_data: None, redirect_response: None, + surcharge_details: None, frm_message: None, }, Some(customer_details), diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs index 07015810039..4979b7902c8 100644 --- a/crates/router/src/core/payments/operations/payment_start.rs +++ b/crates/router/src/core/payments/operations/payment_start.rs @@ -166,6 +166,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ephemeral_key: None, multiple_capture_data: None, redirect_response: None, + surcharge_details: None, frm_message: None, }, Some(customer_details), diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs index 6e0ef2f4bac..c2762a96663 100644 --- a/crates/router/src/core/payments/operations/payment_status.rs +++ b/crates/router/src/core/payments/operations/payment_status.rs @@ -402,6 +402,7 @@ async fn get_tracker_for_sync< ephemeral_key: None, multiple_capture_data, redirect_response: None, + surcharge_details: None, frm_message: frm_response.ok(), }, None, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 9e0ef76d3e7..1c7b432c327 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -345,6 +345,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ephemeral_key: None, multiple_capture_data: None, redirect_response: None, + surcharge_details: None, frm_message: None, }, Some(customer_details), diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 8526f48a590..d19460127b1 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -1024,6 +1024,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsAuthoriz webhook_url, complete_authorize_url, customer_id: None, + surcharge_details: payment_data.surcharge_details, }) } } @@ -1185,6 +1186,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSessionD billing_address.address.and_then(|address| address.country) }), order_details, + surcharge_details: payment_data.surcharge_details, }) } } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index cb8fe8fa797..faa393fd751 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -379,6 +379,7 @@ pub struct PaymentsAuthorizeData { 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<api_models::payment_methods::SurchargeDetailsResponse>, pub customer_id: Option<String>, } @@ -514,6 +515,7 @@ pub struct PaymentsSessionData { pub amount: i64, pub currency: storage_enums::Currency, pub country: Option<api::enums::CountryAlpha2>, + pub surcharge_details: Option<api_models::payment_methods::SurchargeDetailsResponse>, pub order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>, } @@ -1075,6 +1077,7 @@ impl From<&SetupMandateRouterData> for PaymentsAuthorizeData { payment_experience: None, payment_method_type: None, customer_id: None, + surcharge_details: None, } } } diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs index 63d2ee364fa..cba0640e79a 100644 --- a/crates/router/tests/connectors/aci.rs +++ b/crates/router/tests/connectors/aci.rs @@ -68,6 +68,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData { webhook_url: None, complete_authorize_url: None, customer_id: None, + surcharge_details: None, }, response: Err(types::ErrorResponse::default()), payment_method_id: None, diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs index 06f048bb746..2ee6c4912e7 100644 --- a/crates/router/tests/connectors/adyen.rs +++ b/crates/router/tests/connectors/adyen.rs @@ -153,6 +153,7 @@ impl AdyenTest { webhook_url: None, complete_authorize_url: None, customer_id: None, + surcharge_details: None, }) } } diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs index 1eaf1580f0a..2f6db7a9e85 100644 --- a/crates/router/tests/connectors/bitpay.rs +++ b/crates/router/tests/connectors/bitpay.rs @@ -90,6 +90,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { complete_authorize_url: None, capture_method: None, customer_id: None, + surcharge_details: None, }) } diff --git a/crates/router/tests/connectors/cashtocode.rs b/crates/router/tests/connectors/cashtocode.rs index 141aee4ff49..fdb1b94a714 100644 --- a/crates/router/tests/connectors/cashtocode.rs +++ b/crates/router/tests/connectors/cashtocode.rs @@ -65,6 +65,7 @@ impl CashtocodeTest { webhook_url: None, complete_authorize_url: None, customer_id: Some("John Doe".to_owned()), + surcharge_details: None, }) } diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs index dc677c6e31a..cc8cc774a14 100644 --- a/crates/router/tests/connectors/coinbase.rs +++ b/crates/router/tests/connectors/coinbase.rs @@ -92,6 +92,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { complete_authorize_url: None, capture_method: None, customer_id: None, + surcharge_details: None, }) } diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs index d8628415995..48313e5d1a1 100644 --- a/crates/router/tests/connectors/cryptopay.rs +++ b/crates/router/tests/connectors/cryptopay.rs @@ -90,6 +90,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { complete_authorize_url: None, capture_method: None, customer_id: None, + surcharge_details: None, }) } diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs index 79fadf3e130..a46fc20604a 100644 --- a/crates/router/tests/connectors/opennode.rs +++ b/crates/router/tests/connectors/opennode.rs @@ -91,6 +91,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> { complete_authorize_url: None, capture_method: None, customer_id: None, + surcharge_details: None, }) } diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs index 81f4f6bef29..7cd2e16fd36 100644 --- a/crates/router/tests/connectors/utils.rs +++ b/crates/router/tests/connectors/utils.rs @@ -886,6 +886,7 @@ impl Default for PaymentAuthorizeType { complete_authorize_url: None, webhook_url: None, customer_id: None, + surcharge_details: None, }; Self(data) } diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs index 11de3be8a2c..b9ea1364fdb 100644 --- a/crates/router/tests/connectors/worldline.rs +++ b/crates/router/tests/connectors/worldline.rs @@ -100,6 +100,7 @@ impl WorldlineTest { webhook_url: None, complete_authorize_url: None, customer_id: None, + surcharge_details: None, }) } } diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 4764ce68a31..b9b850a0aaa 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -1307,6 +1307,13 @@ impl DataModelExt for PaymentAttemptUpdate { Self::SurchargeMetadataUpdate { surcharge_metadata } => { DieselPaymentAttemptUpdate::SurchargeMetadataUpdate { surcharge_metadata } } + Self::SurchargeAmountUpdate { + surcharge_amount, + tax_amount, + } => DieselPaymentAttemptUpdate::SurchargeAmountUpdate { + surcharge_amount, + tax_amount, + }, } } @@ -1500,6 +1507,13 @@ impl DataModelExt for PaymentAttemptUpdate { DieselPaymentAttemptUpdate::SurchargeMetadataUpdate { surcharge_metadata } => { Self::SurchargeMetadataUpdate { surcharge_metadata } } + DieselPaymentAttemptUpdate::SurchargeAmountUpdate { + surcharge_amount, + tax_amount, + } => Self::SurchargeAmountUpdate { + surcharge_amount, + tax_amount, + }, } } }
fix
percentage float inconsistency problem and api models changes to support surcharge feature (#2550)
5ad3950892fc0c84b26092b0732dd18d2d913d12
2023-07-28 17:15:04
Nishant Joshi
fix(logs): remove request from logs (#1810)
false
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index f448f484ebe..e47a248fbf4 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -84,7 +84,7 @@ pub async fn payments_create( // tag = "Payments", // operation_id = "Start a Redirection Payment" // )] -#[instrument(skip(state), fields(flow = ?Flow::PaymentsStart))] +#[instrument(skip(state, req), fields(flow = ?Flow::PaymentsStart))] pub async fn payments_start( state: web::Data<app::AppState>, req: actix_web::HttpRequest, @@ -135,7 +135,7 @@ pub async fn payments_start( operation_id = "Retrieve a Payment", security(("api_key" = []), ("publishable_key" = [])) )] -#[instrument(skip(state), fields(flow = ?Flow::PaymentsRetrieve))] +#[instrument(skip(state, req), fields(flow = ?Flow::PaymentsRetrieve))] // #[get("/{payment_id}")] pub async fn payments_retrieve( state: web::Data<app::AppState>, @@ -194,7 +194,7 @@ pub async fn payments_retrieve( operation_id = "Retrieve a Payment", security(("api_key" = [])) )] -#[instrument(skip(state), fields(flow = ?Flow::PaymentsRetrieve))] +#[instrument(skip(state, req), fields(flow = ?Flow::PaymentsRetrieve))] // #[post("/sync")] pub async fn payments_retrieve_with_gateway_creds( state: web::Data<app::AppState>,
fix
remove request from logs (#1810)
ee0461e9a57b2ff77d26b4a543bd1e407f3fcc1c
2024-01-18 05:50:02
github-actions
chore(version): 2024.01.18.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index b9b01fe4e91..b17ee4964b4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,31 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.01.18.0 + +### Features + +- **connector_events:** Added api to fetch connector event logs ([#3319](https://github.com/juspay/hyperswitch/pull/3319)) ([`68a3a28`](https://github.com/juspay/hyperswitch/commit/68a3a280676c8309f9becffae545b134b5e1f2ea)) +- **payment_method:** Add capability to store bank details using /payment_methods endpoint ([#3113](https://github.com/juspay/hyperswitch/pull/3113)) ([`01c2de2`](https://github.com/juspay/hyperswitch/commit/01c2de223f60595d77c06a59a40dfe041e02cfee)) + +### Bug Fixes + +- **core:** Add validation for authtype and metadata in update payment connector ([#3305](https://github.com/juspay/hyperswitch/pull/3305)) ([`52f38d3`](https://github.com/juspay/hyperswitch/commit/52f38d3d5a7d035e8211e1f51c8f982232e2d7ab)) +- **events:** Fix event generation for paymentmethods list ([#3337](https://github.com/juspay/hyperswitch/pull/3337)) ([`ac8d81b`](https://github.com/juspay/hyperswitch/commit/ac8d81b32b3d91b875113d32782a8c62e39ba2a8)) + +### Refactors + +- **connector:** [cybersource] recurring mandate flow ([#3354](https://github.com/juspay/hyperswitch/pull/3354)) ([`387c1c4`](https://github.com/juspay/hyperswitch/commit/387c1c491bdc413ae361d04f0be25eaa58e72fa9)) +- [Noon] adding new field max_amount to mandate request ([#3209](https://github.com/juspay/hyperswitch/pull/3209)) ([`eb2a61d`](https://github.com/juspay/hyperswitch/commit/eb2a61d8597995838f21b8233653c691118b2191)) + +### Miscellaneous Tasks + +- **router:** Remove recon from default features ([#3370](https://github.com/juspay/hyperswitch/pull/3370)) ([`928beec`](https://github.com/juspay/hyperswitch/commit/928beecdd7fe9e09b38ffe750627ca4af94ffc93)) + +**Full Changelog:** [`2024.01.17.0...2024.01.18.0`](https://github.com/juspay/hyperswitch/compare/2024.01.17.0...2024.01.18.0) + +- - - + ## 2024.01.17.0 ### Features
chore
2024.01.18.0
82fecd96777cc3cfd2fdf74fb64b950e4f3c0a0c
2023-01-17 18:21:42
Rachit Naithani
refactor(storage_models): made generic queries public (#395)
false
diff --git a/crates/storage_models/src/query/generics.rs b/crates/storage_models/src/query/generics.rs index 2db28246037..bf09b2e594c 100644 --- a/crates/storage_models/src/query/generics.rs +++ b/crates/storage_models/src/query/generics.rs @@ -24,7 +24,7 @@ use router_env::{instrument, logger, tracing}; use crate::{errors, PgPooledConn, StorageResult}; #[instrument(level = "DEBUG", skip_all)] -pub(super) async fn generic_insert<T, V, R>(conn: &PgPooledConn, values: V) -> StorageResult<R> +pub async fn generic_insert<T, V, R>(conn: &PgPooledConn, values: V) -> StorageResult<R> where T: HasTable<Table = T> + Table + 'static, V: Debug + Insertable<T>, @@ -53,7 +53,7 @@ where } #[instrument(level = "DEBUG", skip_all)] -pub(super) async fn generic_update<T, V, P>( +pub async fn generic_update<T, V, P>( conn: &PgPooledConn, predicate: P, values: V, @@ -82,7 +82,7 @@ where } #[instrument(level = "DEBUG", skip_all)] -pub(super) async fn generic_update_with_results<T, V, P, R>( +pub async fn generic_update_with_results<T, V, P, R>( conn: &PgPooledConn, predicate: P, values: V, @@ -112,7 +112,7 @@ where } #[instrument(level = "DEBUG", skip_all)] -pub(super) async fn generic_update_by_id<T, V, Pk, R>( +pub async fn generic_update_by_id<T, V, Pk, R>( conn: &PgPooledConn, id: Pk, values: V, @@ -160,7 +160,7 @@ where } #[instrument(level = "DEBUG", skip_all)] -pub(super) async fn generic_delete<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<bool> +pub async fn generic_delete<T, P>(conn: &PgPooledConn, predicate: P) -> StorageResult<bool> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, <T as FilterDsl<P>>::Output: IntoUpdateTarget, @@ -191,7 +191,7 @@ where } #[instrument(level = "DEBUG", skip_all)] -pub(super) async fn generic_delete_one_with_result<T, P, R>( +pub async fn generic_delete_one_with_result<T, P, R>( conn: &PgPooledConn, predicate: P, ) -> StorageResult<R> @@ -247,7 +247,7 @@ where } #[instrument(level = "DEBUG", skip_all)] -pub(super) async fn generic_find_by_id<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R> +pub async fn generic_find_by_id<T, Pk, R>(conn: &PgPooledConn, id: Pk) -> StorageResult<R> where T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static, <T as FindDsl<Pk>>::Output: QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static, @@ -260,7 +260,7 @@ where } #[instrument(level = "DEBUG", skip_all)] -pub(super) async fn generic_find_by_id_optional<T, Pk, R>( +pub async fn generic_find_by_id_optional<T, Pk, R>( conn: &PgPooledConn, id: Pk, ) -> StorageResult<Option<R>> @@ -302,7 +302,7 @@ where } #[instrument(level = "DEBUG", skip_all)] -pub(super) async fn generic_find_one<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R> +pub async fn generic_find_one<T, P, R>(conn: &PgPooledConn, predicate: P) -> StorageResult<R> where T: FilterDsl<P> + HasTable<Table = T> + Table + 'static, <T as FilterDsl<P>>::Output: @@ -313,7 +313,7 @@ where } #[instrument(level = "DEBUG", skip_all)] -pub(super) async fn generic_find_one_optional<T, P, R>( +pub async fn generic_find_one_optional<T, P, R>( conn: &PgPooledConn, predicate: P, ) -> StorageResult<Option<R>> @@ -327,7 +327,7 @@ where } #[instrument(level = "DEBUG", skip_all)] -pub(super) async fn generic_filter<T, P, R>( +pub async fn generic_filter<T, P, R>( conn: &PgPooledConn, predicate: P, limit: Option<i64>,
refactor
made generic queries public (#395)
25790a161aebe86d58edb6feafce821a77b69dd4
2024-01-22 18:50:30
github-actions
chore(version): 2024.01.22.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 51d650f3fb8..a964c6b1748 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.01.22.1 + +### Features + +- **core:** Send `customer_name` to connectors when creating customer ([#3380](https://github.com/juspay/hyperswitch/pull/3380)) ([`7813cee`](https://github.com/juspay/hyperswitch/commit/7813ceece2081b73f1374e2ee5a9a673f0b72127)) + +### Miscellaneous Tasks + +- Chore(deps): bump the cargo group across 1 directories with 3 updates ([#3409](https://github.com/juspay/hyperswitch/pull/3409)) ([`6c46e9c`](https://github.com/juspay/hyperswitch/commit/6c46e9c19b304bb11f304e60c46e8abf67accf6d)) + +**Full Changelog:** [`2024.01.22.0...2024.01.22.1`](https://github.com/juspay/hyperswitch/compare/2024.01.22.0...2024.01.22.1) + +- - - + ## 2024.01.22.0 ### Features
chore
2024.01.22.1
8e538cd6b3da4a155c55ce153982bff3c59ef575
2024-10-14 15:42:55
Sarthak Soni
feat(payment_methods_v2): Delete payment method api (#6211)
false
diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rs index af3c657c34a..445ad5ab800 100644 --- a/crates/hyperswitch_domain_models/src/payment_methods.rs +++ b/crates/hyperswitch_domain_models/src/payment_methods.rs @@ -14,6 +14,20 @@ use time::PrimitiveDateTime; use crate::type_encryption::{crypto_operation, AsyncLift, CryptoOperation}; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] +pub struct VaultId(String); + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl VaultId { + pub fn get_string_repr(&self) -> &String { + &self.0 + } + + pub fn generate(id: String) -> Self { + Self(id) + } +} #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") @@ -67,7 +81,7 @@ pub struct PaymentMethod { pub payment_method_type: Option<storage_enums::PaymentMethodType>, pub metadata: Option<pii::SecretSerdeValue>, pub payment_method_data: OptionalEncryptableValue, - pub locker_id: Option<String>, + pub locker_id: Option<VaultId>, pub last_used_at: PrimitiveDateTime, pub connector_mandate_details: Option<pii::SecretSerdeValue>, pub customer_acceptance: Option<pii::SecretSerdeValue>, @@ -302,7 +316,7 @@ impl super::behaviour::Conversion for PaymentMethod { payment_method_type: self.payment_method_type, metadata: self.metadata, payment_method_data: self.payment_method_data.map(|val| val.into()), - locker_id: self.locker_id, + locker_id: self.locker_id.map(|id| id.get_string_repr().clone()), last_used_at: self.last_used_at, connector_mandate_details: self.connector_mandate_details, customer_acceptance: self.customer_acceptance, @@ -356,7 +370,7 @@ impl super::behaviour::Conversion for PaymentMethod { .and_then(|val| val.try_into_optionaloperation()) }) .await?, - locker_id: item.locker_id, + locker_id: item.locker_id.map(VaultId::generate), last_used_at: item.last_used_at, connector_mandate_details: item.connector_mandate_details, customer_acceptance: item.customer_acceptance, @@ -415,7 +429,7 @@ impl super::behaviour::Conversion for PaymentMethod { payment_method_type: self.payment_method_type, metadata: self.metadata, payment_method_data: self.payment_method_data.map(|val| val.into()), - locker_id: self.locker_id, + locker_id: self.locker_id.map(|id| id.get_string_repr().clone()), last_used_at: self.last_used_at, connector_mandate_details: self.connector_mandate_details, customer_acceptance: self.customer_acceptance, diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs index 1b93f05d823..721dd9de1c4 100644 --- a/crates/router/src/consts.rs +++ b/crates/router/src/consts.rs @@ -149,6 +149,26 @@ pub const VAULT_FINGERPRINT_REQUEST_URL: &str = "/fingerprint"; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub const VAULT_RETRIEVE_REQUEST_URL: &str = "/vault/retrieve"; +/// Vault Delete request url +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub const VAULT_DELETE_REQUEST_URL: &str = "/vault/delete"; + /// Vault Header content type #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] pub const VAULT_HEADER_CONTENT_TYPE: &str = "application/json"; + +/// Vault Add flow type +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub const VAULT_ADD_FLOW_TYPE: &str = "add_to_vault"; + +/// Vault Retrieve flow type +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub const VAULT_RETRIEVE_FLOW_TYPE: &str = "retrieve_from_vault"; + +/// Vault Delete flow type +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub const VAULT_DELETE_FLOW_TYPE: &str = "delete_from_vault"; + +/// Vault Fingerprint fetch flow type +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +pub const VAULT_GET_FINGERPRINT_FLOW_TYPE: &str = "get_fingerprint_vault"; diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs index 8841ad7f383..9a093a065e4 100644 --- a/crates/router/src/core/payment_methods.rs +++ b/crates/router/src/core/payment_methods.rs @@ -1124,7 +1124,7 @@ pub async fn create_payment_method_in_db( req: &api::PaymentMethodCreate, customer_id: &id_type::CustomerId, payment_method_id: id_type::GlobalPaymentMethodId, - locker_id: Option<String>, + locker_id: Option<domain::VaultId>, merchant_id: &id_type::MerchantId, pm_metadata: Option<common_utils::pii::SecretSerdeValue>, customer_acceptance: Option<common_utils::pii::SecretSerdeValue>, @@ -1276,12 +1276,12 @@ pub async fn vault_payment_method( pmd: &pm_types::PaymentMethodVaultingData, merchant_account: &domain::MerchantAccount, key_store: &domain::MerchantKeyStore, - existing_vault_id: Option<String>, + existing_vault_id: Option<domain::VaultId>, ) -> RouterResult<pm_types::AddVaultResponse> { let db = &*state.store; - // get fingerprint_id from locker - let fingerprint_id_from_locker = cards::get_fingerprint_id_from_locker(state, pmd) + // get fingerprint_id from vault + let fingerprint_id_from_vault = vault::get_fingerprint_id_from_vault(state, pmd) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to get fingerprint_id from vault")?; @@ -1292,7 +1292,7 @@ pub async fn vault_payment_method( db.find_payment_method_by_fingerprint_id( &(state.into()), key_store, - &fingerprint_id_from_locker, + &fingerprint_id_from_vault, ) .await .change_context(errors::ApiErrorResponse::InternalServerError) @@ -1305,13 +1305,13 @@ pub async fn vault_payment_method( }, )?; - let resp_from_locker = - cards::vault_payment_method_in_locker(state, merchant_account, pmd, existing_vault_id) + let resp_from_vault = + vault::add_payment_method_to_vault(state, merchant_account, pmd, existing_vault_id) .await .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to vault payment method in locker")?; + .attach_printable("Failed to add payment method in vault")?; - Ok(resp_from_locker) + Ok(resp_from_vault) } #[cfg(all( @@ -1339,10 +1339,12 @@ async fn get_pm_list_context( storage::PaymentTokenData::permanent_card( Some(pm.get_id().clone()), pm.locker_id - .clone() + .as_ref() + .map(|id| id.get_string_repr().clone()) .or(Some(pm.get_id().get_string_repr().to_owned())), pm.locker_id - .clone() + .as_ref() + .map(|id| id.get_string_repr().clone()) .unwrap_or(pm.get_id().get_string_repr().to_owned()), ), ), @@ -1767,20 +1769,16 @@ pub async fn update_payment_method( }, )?; - let pmd: pm_types::PaymentMethodVaultingData = cards::retrieve_payment_method_from_vault( - &state, - &merchant_account, - &payment_method.customer_id, - &payment_method, - ) - .await - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to retrieve payment method from vault")? - .data - .expose() - .parse_struct("PaymentMethodCreateData") - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to parse PaymentMethodCreateData")?; + let pmd: pm_types::PaymentMethodVaultingData = + vault::retrieve_payment_method_from_vault(&state, &merchant_account, &payment_method) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to retrieve payment method from vault")? + .data + .expose() + .parse_struct("PaymentMethodVaultingData") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse PaymentMethodVaultingData")?; let vault_request_data = pm_transforms::generate_pm_vaulting_req_from_update_request(pmd, req.payment_method_data); @@ -1825,6 +1823,76 @@ pub async fn update_payment_method( Ok(services::ApplicationResponse::Json(response)) } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn delete_payment_method( + state: SessionState, + pm_id: api::PaymentMethodId, + key_store: domain::MerchantKeyStore, + merchant_account: domain::MerchantAccount, +) -> RouterResponse<api::PaymentMethodDeleteResponse> { + let db = state.store.as_ref(); + let key_manager_state = &(&state).into(); + + let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unable to generate GlobalPaymentMethodId")?; + + let payment_method = db + .find_payment_method( + &((&state).into()), + &key_store, + &pm_id, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?; + + let vault_id = payment_method + .locker_id + .clone() + .get_required_value("locker_id") + .attach_printable("Missing locker_id in PaymentMethod")?; + + let _customer = db + .find_customer_by_global_id( + key_manager_state, + payment_method.customer_id.get_string_repr(), + merchant_account.get_id(), + &key_store, + merchant_account.storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Customer not found for the payment method")?; + + // Soft delete + let pm_update = storage::PaymentMethodUpdate::StatusUpdate { + status: Some(enums::PaymentMethodStatus::Inactive), + }; + db.update_payment_method( + &((&state).into()), + &key_store, + payment_method, + pm_update, + merchant_account.storage_scheme, + ) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to update payment method in db")?; + + vault::delete_payment_method_data_from_vault(&state, &merchant_account, vault_id) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to delete payment method from vault")?; + + let response = api::PaymentMethodDeleteResponse { + payment_method_id: pm_id.get_string_repr().to_string(), + }; + + Ok(services::ApplicationResponse::Json(response)) +} + #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl pm_types::SavedPMLPaymentsInfo { pub async fn form_payments_info( diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index abcdf504e1c..5da298815e7 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -221,37 +221,6 @@ pub async fn create_payment_method( Ok(response) } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -async fn create_vault_request<R: pm_types::VaultingInterface>( - jwekey: &settings::Jwekey, - locker: &settings::Locker, - payload: Vec<u8>, -) -> errors::CustomResult<Request, errors::VaultError> { - let private_key = jwekey.vault_private_key.peek().as_bytes(); - - let jws = services::encryption::jws_sign_payload( - &payload, - &locker.locker_signing_key_id, - private_key, - ) - .await - .change_context(errors::VaultError::RequestEncryptionFailed)?; - - let jwe_payload = payment_methods::create_jwe_body_for_vault(jwekey, &jws).await?; - - let mut url = locker.host.to_owned(); - url.push_str(R::get_vaulting_request_url()); - let mut request = Request::new(services::Method::Post, &url); - request.add_header( - headers::CONTENT_TYPE, - router_consts::VAULT_HEADER_CONTENT_TYPE.into(), - ); - request.set_body(common_utils::request::RequestContent::Json(Box::new( - jwe_payload, - ))); - Ok(request) -} - #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") @@ -1411,107 +1380,6 @@ pub async fn add_payment_method( Ok(services::ApplicationResponse::Json(resp)) } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[instrument(skip_all)] -pub async fn get_fingerprint_id_from_locker< - D: pm_types::VaultingDataInterface + serde::Serialize, ->( - state: &routes::SessionState, - data: &D, -) -> errors::CustomResult<String, errors::VaultError> { - let key = data.get_vaulting_data_key(); - let data = serde_json::to_value(data) - .change_context(errors::VaultError::RequestEncodingFailed) - .attach_printable("Failed to encode Vaulting data to value")? - .to_string(); - - let payload = pm_types::VaultFingerprintRequest { key, data } - .encode_to_vec() - .change_context(errors::VaultError::RequestEncodingFailed) - .attach_printable("Failed to encode VaultFingerprintRequest")?; - - let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload) - .await - .change_context(errors::VaultError::VaultAPIError) - .attach_printable("Failed to get response from locker")?; - - let fingerprint_resp: pm_types::VaultFingerprintResponse = resp - .parse_struct("VaultFingerprintResp") - .change_context(errors::VaultError::ResponseDeserializationFailed) - .attach_printable("Failed to parse data into VaultFingerprintResp")?; - - Ok(fingerprint_resp.fingerprint_id) -} - -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[instrument(skip_all)] -pub async fn vault_payment_method_in_locker( - state: &routes::SessionState, - merchant_account: &domain::MerchantAccount, - pmd: &pm_types::PaymentMethodVaultingData, - existing_vault_id: Option<String>, -) -> errors::CustomResult<pm_types::AddVaultResponse, errors::VaultError> { - let payload = pm_types::AddVaultRequest { - entity_id: merchant_account.get_id().to_owned(), - vault_id: pm_types::VaultId::generate( - existing_vault_id.unwrap_or(uuid::Uuid::now_v7().to_string()), - ), - data: pmd, - ttl: state.conf.locker.ttl_for_storage_in_secs, - } - .encode_to_vec() - .change_context(errors::VaultError::RequestEncodingFailed) - .attach_printable("Failed to encode AddVaultRequest")?; - - let resp = call_to_vault::<pm_types::AddVault>(state, payload) - .await - .change_context(errors::VaultError::VaultAPIError) - .attach_printable("Failed to get response from locker")?; - - let stored_pm_resp: pm_types::AddVaultResponse = resp - .parse_struct("AddVaultResponse") - .change_context(errors::VaultError::ResponseDeserializationFailed) - .attach_printable("Failed to parse data into AddVaultResponse")?; - - Ok(stored_pm_resp) -} - -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[instrument(skip_all)] -pub async fn retrieve_payment_method_from_vault( - state: &routes::SessionState, - merchant_account: &domain::MerchantAccount, - customer_id: &id_type::CustomerId, - pm: &domain::PaymentMethod, -) -> errors::CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError> { - let payload = pm_types::VaultRetrieveRequest { - entity_id: merchant_account.get_id().to_owned(), - vault_id: pm_types::VaultId::generate( - pm.locker_id - .clone() - .ok_or(errors::VaultError::MissingRequiredField { - field_name: "locker_id", - }) - .attach_printable("Missing locker_id for VaultRetrieveRequest")?, - ), - } - .encode_to_vec() - .change_context(errors::VaultError::RequestEncodingFailed) - .attach_printable("Failed to encode VaultRetrieveRequest")?; - - let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload) - .await - .change_context(errors::VaultError::VaultAPIError) - .attach_printable("Failed to get response from locker")?; - - let stored_pm_resp: pm_types::VaultRetrieveResponse = resp - .parse_struct("VaultRetrieveResponse") - .change_context(errors::VaultError::ResponseDeserializationFailed) - .attach_printable("Failed to parse data into VaultRetrieveResponse")?; - - Ok(stored_pm_resp) -} - #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") @@ -2266,37 +2134,6 @@ pub async fn add_card_to_hs_locker( Ok(stored_card) } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[instrument(skip_all)] -pub async fn call_to_vault<V: pm_types::VaultingInterface>( - state: &routes::SessionState, - payload: Vec<u8>, -) -> errors::CustomResult<String, errors::VaultError> { - let locker = &state.conf.locker; - let jwekey = state.conf.jwekey.get_inner(); - - let request = create_vault_request::<V>(jwekey, locker, payload).await?; - let response = services::call_connector_api(state, request, "vault_in_locker") - .await - .change_context(errors::VaultError::VaultAPIError); - - let jwe_body: services::JweBody = response - .get_response_inner("JweBody") - .change_context(errors::VaultError::ResponseDeserializationFailed) - .attach_printable("Failed to get JweBody from vault response")?; - - let decrypted_payload = payment_methods::get_decrypted_vault_response_payload( - jwekey, - jwe_body, - locker.decryption_scheme.clone(), - ) - .await - .change_context(errors::VaultError::ResponseDecryptionFailed) - .attach_printable("Error getting decrypted vault response payload")?; - - Ok(decrypted_payload) -} - #[instrument(skip_all)] pub async fn call_locker_api<T>( state: &routes::SessionState, @@ -5401,21 +5238,6 @@ pub async fn retrieve_payment_method( )) } -#[cfg(all( - any(feature = "v2", feature = "v1"), - not(feature = "payment_methods_v2") -))] -#[instrument(skip_all)] -#[cfg(all(feature = "v2", feature = "customer_v2"))] -pub async fn delete_payment_method( - _state: routes::SessionState, - _merchant_account: domain::MerchantAccount, - _pm_id: api::PaymentMethodId, - _key_store: domain::MerchantKeyStore, -) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> { - todo!() -} - #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[instrument(skip_all)] pub async fn delete_payment_method( @@ -5518,17 +5340,6 @@ pub async fn delete_payment_method( )) } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[instrument(skip_all)] -pub async fn delete_payment_method( - _state: routes::SessionState, - _merchant_account: domain::MerchantAccount, - _pm_id: api::PaymentMethodId, - _key_store: domain::MerchantKeyStore, -) -> errors::RouterResponse<api::PaymentMethodDeleteResponse> { - todo!() -} - pub async fn create_encrypted_data<T>( state: &routes::SessionState, key_store: &domain::MerchantKeyStore, diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs index 75278010ceb..7a24f2a30a2 100644 --- a/crates/router/src/core/payment_methods/vault.rs +++ b/crates/router/src/core/payment_methods/vault.rs @@ -1,4 +1,6 @@ use common_enums::PaymentMethodType; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use common_utils::request; use common_utils::{ crypto::{DecodeMessage, EncodeMessage, GcmAes256}, ext_traits::{BytesExt, Encode}, @@ -23,6 +25,11 @@ use crate::{ }, utils::StringExt, }; +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +use crate::{ + core::payment_methods::transformers as pm_transforms, headers, services, settings, + types::payment_methods as pm_types, utils::ConnectorResponseExt, +}; const VAULT_SERVICE_NAME: &str = "CARD"; pub struct SupplementaryVaultData { @@ -1172,6 +1179,191 @@ pub async fn delete_tokenized_data( } } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +async fn create_vault_request<R: pm_types::VaultingInterface>( + jwekey: &settings::Jwekey, + locker: &settings::Locker, + payload: Vec<u8>, +) -> CustomResult<request::Request, errors::VaultError> { + let private_key = jwekey.vault_private_key.peek().as_bytes(); + + let jws = services::encryption::jws_sign_payload( + &payload, + &locker.locker_signing_key_id, + private_key, + ) + .await + .change_context(errors::VaultError::RequestEncryptionFailed)?; + + let jwe_payload = pm_transforms::create_jwe_body_for_vault(jwekey, &jws).await?; + + let mut url = locker.host.to_owned(); + url.push_str(R::get_vaulting_request_url()); + let mut request = request::Request::new(services::Method::Post, &url); + request.add_header( + headers::CONTENT_TYPE, + consts::VAULT_HEADER_CONTENT_TYPE.into(), + ); + request.set_body(request::RequestContent::Json(Box::new(jwe_payload))); + Ok(request) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn call_to_vault<V: pm_types::VaultingInterface>( + state: &routes::SessionState, + payload: Vec<u8>, +) -> CustomResult<String, errors::VaultError> { + let locker = &state.conf.locker; + let jwekey = state.conf.jwekey.get_inner(); + + let request = create_vault_request::<V>(jwekey, locker, payload).await?; + let response = services::call_connector_api(state, request, V::get_vaulting_flow_name()) + .await + .change_context(errors::VaultError::VaultAPIError); + + let jwe_body: services::JweBody = response + .get_response_inner("JweBody") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Failed to get JweBody from vault response")?; + + let decrypted_payload = pm_transforms::get_decrypted_vault_response_payload( + jwekey, + jwe_body, + locker.decryption_scheme.clone(), + ) + .await + .change_context(errors::VaultError::ResponseDecryptionFailed) + .attach_printable("Error getting decrypted vault response payload")?; + + Ok(decrypted_payload) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn get_fingerprint_id_from_vault< + D: pm_types::VaultingDataInterface + serde::Serialize, +>( + state: &routes::SessionState, + data: &D, +) -> CustomResult<String, errors::VaultError> { + let key = data.get_vaulting_data_key(); + let data = serde_json::to_string(data) + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode Vaulting data to string")?; + + let payload = pm_types::VaultFingerprintRequest { key, data } + .encode_to_vec() + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode VaultFingerprintRequest")?; + + let resp = call_to_vault::<pm_types::GetVaultFingerprint>(state, payload) + .await + .change_context(errors::VaultError::VaultAPIError) + .attach_printable("Call to vault failed")?; + + let fingerprint_resp: pm_types::VaultFingerprintResponse = resp + .parse_struct("VaultFingerprintResponse") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Failed to parse data into VaultFingerprintResponse")?; + + Ok(fingerprint_resp.fingerprint_id) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn add_payment_method_to_vault( + state: &routes::SessionState, + merchant_account: &domain::MerchantAccount, + pmd: &pm_types::PaymentMethodVaultingData, + existing_vault_id: Option<domain::VaultId>, +) -> CustomResult<pm_types::AddVaultResponse, errors::VaultError> { + let payload = pm_types::AddVaultRequest { + entity_id: merchant_account.get_id().to_owned(), + vault_id: existing_vault_id + .unwrap_or(domain::VaultId::generate(uuid::Uuid::now_v7().to_string())), + data: pmd, + ttl: state.conf.locker.ttl_for_storage_in_secs, + } + .encode_to_vec() + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode AddVaultRequest")?; + + let resp = call_to_vault::<pm_types::AddVault>(state, payload) + .await + .change_context(errors::VaultError::VaultAPIError) + .attach_printable("Call to vault failed")?; + + let stored_pm_resp: pm_types::AddVaultResponse = resp + .parse_struct("AddVaultResponse") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Failed to parse data into AddVaultResponse")?; + + Ok(stored_pm_resp) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn retrieve_payment_method_from_vault( + state: &routes::SessionState, + merchant_account: &domain::MerchantAccount, + pm: &domain::PaymentMethod, +) -> CustomResult<pm_types::VaultRetrieveResponse, errors::VaultError> { + let payload = pm_types::VaultRetrieveRequest { + entity_id: merchant_account.get_id().to_owned(), + vault_id: pm + .locker_id + .clone() + .ok_or(errors::VaultError::MissingRequiredField { + field_name: "locker_id", + }) + .attach_printable("Missing locker_id for VaultRetrieveRequest")?, + } + .encode_to_vec() + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode VaultRetrieveRequest")?; + + let resp = call_to_vault::<pm_types::VaultRetrieve>(state, payload) + .await + .change_context(errors::VaultError::VaultAPIError) + .attach_printable("Call to vault failed")?; + + let stored_pm_resp: pm_types::VaultRetrieveResponse = resp + .parse_struct("VaultRetrieveResponse") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Failed to parse data into VaultRetrieveResponse")?; + + Ok(stored_pm_resp) +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all)] +pub async fn delete_payment_method_data_from_vault( + state: &routes::SessionState, + merchant_account: &domain::MerchantAccount, + vault_id: domain::VaultId, +) -> CustomResult<pm_types::VaultDeleteResponse, errors::VaultError> { + let payload = pm_types::VaultDeleteRequest { + entity_id: merchant_account.get_id().to_owned(), + vault_id, + } + .encode_to_vec() + .change_context(errors::VaultError::RequestEncodingFailed) + .attach_printable("Failed to encode VaultDeleteRequest")?; + + let resp = call_to_vault::<pm_types::VaultDelete>(state, payload) + .await + .change_context(errors::VaultError::VaultAPIError) + .attach_printable("Call to vault failed")?; + + let stored_pm_resp: pm_types::VaultDeleteResponse = resp + .parse_struct("VaultDeleteResponse") + .change_context(errors::VaultError::ResponseDeserializationFailed) + .attach_printable("Failed to parse data into VaultDeleteResponse")?; + + Ok(stored_pm_resp) +} + // ********************************************** PROCESS TRACKER ********************************************** pub async fn add_delete_tokenized_data_task( diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 54e4471b057..c267b113fcd 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -1091,7 +1091,8 @@ impl PaymentMethods { web::resource("/{id}/update_saved_payment_method") .route(web::patch().to(payment_method_update_api)), ) - .service(web::resource("/{id}").route(web::get().to(payment_method_retrieve_api))); + .service(web::resource("/{id}").route(web::get().to(payment_method_retrieve_api))) + .service(web::resource("/{id}").route(web::delete().to(payment_method_delete_api))); route } diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs index 3e3aada154f..77c072448a2 100644 --- a/crates/router/src/routes/payment_methods.rs +++ b/crates/router/src/routes/payment_methods.rs @@ -14,8 +14,9 @@ use router_env::{instrument, logger, tracing, Flow}; use super::app::{AppState, SessionState}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use crate::core::payment_methods::{ - create_payment_method, list_customer_payment_method_util, payment_method_intent_confirm, - payment_method_intent_create, retrieve_payment_method, update_payment_method, + create_payment_method, delete_payment_method, list_customer_payment_method_util, + payment_method_intent_confirm, payment_method_intent_create, retrieve_payment_method, + update_payment_method, }; use crate::{ core::{ @@ -239,6 +240,33 @@ pub async fn payment_method_retrieve_api( .await } +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))] +pub async fn payment_method_delete_api( + state: web::Data<AppState>, + req: HttpRequest, + path: web::Path<String>, +) -> HttpResponse { + let flow = Flow::PaymentMethodsDelete; + let payload = web::Json(PaymentMethodId { + payment_method_id: path.into_inner(), + }) + .into_inner(); + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth, pm, _| { + delete_payment_method(state, pm, auth.key_store, auth.merchant_account) + }, + &auth::HeaderAuth(auth::ApiKeyAuth), + api_locking::LockAction::NotApplicable, + )) + .await +} + #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsMigrate))] pub async fn migrate_payment_method_api( state: web::Data<AppState>, @@ -796,6 +824,10 @@ pub async fn payment_method_update_api( .await } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "payment_methods_v2") +))] #[instrument(skip_all, fields(flow = ?Flow::PaymentMethodsDelete))] pub async fn payment_method_delete_api( state: web::Data<AppState>, diff --git a/crates/router/src/types/payment_methods.rs b/crates/router/src/types/payment_methods.rs index a1c0f8156fa..29290f0b7fc 100644 --- a/crates/router/src/types/payment_methods.rs +++ b/crates/router/src/types/payment_methods.rs @@ -10,32 +10,17 @@ use crate::{ }; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[async_trait::async_trait] pub trait VaultingInterface { fn get_vaulting_request_url() -> &'static str; + + fn get_vaulting_flow_name() -> &'static str; } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[async_trait::async_trait] pub trait VaultingDataInterface { fn get_vaulting_data_key(&self) -> String; } -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[derive(Debug, serde::Deserialize, serde::Serialize)] -pub struct VaultId(String); - -#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -impl VaultId { - pub fn get_string_repr(&self) -> &String { - &self.0 - } - - pub fn generate(id: String) -> Self { - Self(id) - } -} - #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultFingerprintRequest { @@ -53,7 +38,7 @@ pub struct VaultFingerprintResponse { #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVaultRequest<D> { pub entity_id: common_utils::id_type::MerchantId, - pub vault_id: VaultId, + pub vault_id: domain::VaultId, pub data: D, pub ttl: i64, } @@ -62,7 +47,7 @@ pub struct AddVaultRequest<D> { #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AddVaultResponse { pub entity_id: common_utils::id_type::MerchantId, - pub vault_id: VaultId, + pub vault_id: domain::VaultId, pub fingerprint_id: Option<String>, } @@ -79,27 +64,51 @@ pub struct GetVaultFingerprint; pub struct VaultRetrieve; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[async_trait::async_trait] +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct VaultDelete; + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl VaultingInterface for AddVault { fn get_vaulting_request_url() -> &'static str { consts::ADD_VAULT_REQUEST_URL } + + fn get_vaulting_flow_name() -> &'static str { + consts::VAULT_ADD_FLOW_TYPE + } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[async_trait::async_trait] impl VaultingInterface for GetVaultFingerprint { fn get_vaulting_request_url() -> &'static str { consts::VAULT_FINGERPRINT_REQUEST_URL } + + fn get_vaulting_flow_name() -> &'static str { + consts::VAULT_GET_FINGERPRINT_FLOW_TYPE + } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[async_trait::async_trait] impl VaultingInterface for VaultRetrieve { fn get_vaulting_request_url() -> &'static str { consts::VAULT_RETRIEVE_REQUEST_URL } + + fn get_vaulting_flow_name() -> &'static str { + consts::VAULT_RETRIEVE_FLOW_TYPE + } +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +impl VaultingInterface for VaultDelete { + fn get_vaulting_request_url() -> &'static str { + consts::VAULT_DELETE_REQUEST_URL + } + + fn get_vaulting_flow_name() -> &'static str { + consts::VAULT_DELETE_FLOW_TYPE + } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -109,7 +118,6 @@ pub enum PaymentMethodVaultingData { } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] -#[async_trait::async_trait] impl VaultingDataInterface for PaymentMethodVaultingData { fn get_vaulting_data_key(&self) -> String { match &self { @@ -141,7 +149,7 @@ pub struct SavedPMLPaymentsInfo { #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VaultRetrieveRequest { pub entity_id: common_utils::id_type::MerchantId, - pub vault_id: VaultId, + pub vault_id: domain::VaultId, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] @@ -149,3 +157,17 @@ pub struct VaultRetrieveRequest { pub struct VaultRetrieveResponse { pub data: Secret<String>, } + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct VaultDeleteRequest { + pub entity_id: common_utils::id_type::MerchantId, + pub vault_id: domain::VaultId, +} + +#[cfg(all(feature = "v2", feature = "payment_methods_v2"))] +#[derive(Debug, serde::Deserialize, serde::Serialize)] +pub struct VaultDeleteResponse { + pub entity_id: common_utils::id_type::MerchantId, + pub vault_id: domain::VaultId, +}
feat
Delete payment method api (#6211)
b1c4e30e929fb8d31d854765d5f1ddad5e77f065
2024-11-27 23:48:13
likhinbopanna
ci(cypress): Move MIT requests to configs and add Paybox Mandates (#6650)
false
diff --git a/cypress-tests/cypress/e2e/PaymentTest/00009-RefundPayment.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00009-RefundPayment.cy.js index 9eb64c0acf2..4eef1ac8737 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00009-RefundPayment.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00009-RefundPayment.cy.js @@ -815,8 +815,15 @@ describe("Card - Refund flow - No 3DS", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -825,8 +832,15 @@ describe("Card - Refund flow - No 3DS", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 7000, true, "automatic", diff --git a/cypress-tests/cypress/e2e/PaymentTest/00011-CreateSingleuseMandate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00011-CreateSingleuseMandate.cy.js index 5c140913826..bace2a78018 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00011-CreateSingleuseMandate.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00011-CreateSingleuseMandate.cy.js @@ -49,8 +49,15 @@ describe("Card - SingleUse Mandates flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -112,8 +119,15 @@ describe("Card - SingleUse Mandates flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 6500, true, "manual", @@ -197,8 +211,15 @@ describe("Card - SingleUse Mandates flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 7000, true, "automatic", diff --git a/cypress-tests/cypress/e2e/PaymentTest/00012-CreateMultiuseMandate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00012-CreateMultiuseMandate.cy.js index 3596af70fe1..312c74c23c0 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00012-CreateMultiuseMandate.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00012-CreateMultiuseMandate.cy.js @@ -49,8 +49,15 @@ describe("Card - MultiUse Mandates flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -58,8 +65,15 @@ describe("Card - MultiUse Mandates flow test", () => { ); }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -121,8 +135,15 @@ describe("Card - MultiUse Mandates flow test", () => { }); it("Confirm No 3DS MIT 1", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 6500, true, "manual", @@ -149,8 +170,15 @@ describe("Card - MultiUse Mandates flow test", () => { }); it("Confirm No 3DS MIT 2", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 6500, true, "manual", @@ -230,8 +258,15 @@ describe("Card - MultiUse Mandates flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 6500, true, "automatic", diff --git a/cypress-tests/cypress/e2e/PaymentTest/00013-ListAndRevokeMandate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00013-ListAndRevokeMandate.cy.js index f341db19f6c..cad829ba310 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00013-ListAndRevokeMandate.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00013-ListAndRevokeMandate.cy.js @@ -49,8 +49,15 @@ describe("Card - List and revoke Mandates flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -105,8 +112,15 @@ describe("Card - List and revoke Mandates flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "MITAutoCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 7000, true, "automatic", diff --git a/cypress-tests/cypress/e2e/PaymentTest/00015-ZeroAuthMandate.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00015-ZeroAuthMandate.cy.js index b9083142727..15e7597286a 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00015-ZeroAuthMandate.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00015-ZeroAuthMandate.cy.js @@ -47,8 +47,15 @@ describe("Card - SingleUse Mandates flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -89,8 +96,15 @@ describe("Card - SingleUse Mandates flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -98,8 +112,15 @@ describe("Card - SingleUse Mandates flow test", () => { ); }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 7000, true, "automatic", diff --git a/cypress-tests/cypress/e2e/PaymentTest/00019-MandatesUsingPMID.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00019-MandatesUsingPMID.cy.js index b2951e37586..401f662c67e 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00019-MandatesUsingPMID.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00019-MandatesUsingPMID.cy.js @@ -67,8 +67,15 @@ describe("Card - Mandates using Payment Method Id flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingPMId( fixtures.pmIdConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -148,8 +155,15 @@ describe("Card - Mandates using Payment Method Id flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingPMId( fixtures.pmIdConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -193,8 +207,15 @@ describe("Card - Mandates using Payment Method Id flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingPMId( fixtures.pmIdConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -202,8 +223,15 @@ describe("Card - Mandates using Payment Method Id flow test", () => { ); }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingPMId( fixtures.pmIdConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -265,8 +293,15 @@ describe("Card - Mandates using Payment Method Id flow test", () => { }); it("Confirm No 3DS MIT 1", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingPMId( fixtures.pmIdConfirmBody, + req_data, + res_data, 6500, true, "manual", @@ -293,8 +328,15 @@ describe("Card - Mandates using Payment Method Id flow test", () => { }); it("Confirm No 3DS MIT 2", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingPMId( fixtures.pmIdConfirmBody, + req_data, + res_data, 6500, true, "manual", @@ -361,8 +403,15 @@ describe("Card - Mandates using Payment Method Id flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingPMId( fixtures.pmIdConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -370,8 +419,15 @@ describe("Card - Mandates using Payment Method Id flow test", () => { ); }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingPMId( fixtures.pmIdConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -438,8 +494,15 @@ describe("Card - Mandates using Payment Method Id flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingPMId( fixtures.pmIdConfirmBody, + req_data, + res_data, 7000, true, "automatic", diff --git a/cypress-tests/cypress/e2e/PaymentTest/00020-MandatesUsingNTID.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00020-MandatesUsingNTID.cy.js index edd46f7f834..dcccfd390bf 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00020-MandatesUsingNTID.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00020-MandatesUsingNTID.cy.js @@ -29,8 +29,15 @@ describe("Card - Mandates using Network Transaction Id flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingNTID( fixtures.ntidConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -52,8 +59,15 @@ describe("Card - Mandates using Network Transaction Id flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingNTID( fixtures.ntidConfirmBody, + req_data, + res_data, 7000, true, "manual", @@ -75,8 +89,15 @@ describe("Card - Mandates using Network Transaction Id flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingNTID( fixtures.ntidConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -84,8 +105,15 @@ describe("Card - Mandates using Network Transaction Id flow test", () => { ); }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingNTID( fixtures.ntidConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -107,8 +135,15 @@ describe("Card - Mandates using Network Transaction Id flow test", () => { }); it("Confirm No 3DS MIT 1", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingNTID( fixtures.ntidConfirmBody, + req_data, + res_data, 6500, true, "manual", @@ -135,8 +170,15 @@ describe("Card - Mandates using Network Transaction Id flow test", () => { }); it("Confirm No 3DS MIT 2", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITManualCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingNTID( fixtures.ntidConfirmBody, + req_data, + res_data, 6500, true, "manual", @@ -176,8 +218,15 @@ describe("Card - Mandates using Network Transaction Id flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingNTID( fixtures.ntidConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -185,8 +234,15 @@ describe("Card - Mandates using Network Transaction Id flow test", () => { ); }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingNTID( fixtures.ntidConfirmBody, + req_data, + res_data, 7000, true, "automatic", @@ -208,8 +264,15 @@ describe("Card - Mandates using Network Transaction Id flow test", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))[ + "card_pm" + ]["MITAutoCapture"]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitUsingNTID( fixtures.ntidConfirmBody, + req_data, + res_data, 7000, true, "automatic", diff --git a/cypress-tests/cypress/e2e/PaymentTest/00022-Variations.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00022-Variations.cy.js index b24b9f10f79..035b7da97ab 100644 --- a/cypress-tests/cypress/e2e/PaymentTest/00022-Variations.cy.js +++ b/cypress-tests/cypress/e2e/PaymentTest/00022-Variations.cy.js @@ -463,9 +463,15 @@ describe("Corner cases", () => { let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ "Void" ]; - let commonData = getConnectorDetails(globalState.get("commons"))["card_pm"]["Void"]; + let commonData = getConnectorDetails(globalState.get("commons"))[ + "card_pm" + ]["Void"]; let req_data = data["Request"]; - let res_data = utils.getConnectorFlowDetails(data, commonData, "ResponseCustom"); + let res_data = utils.getConnectorFlowDetails( + data, + commonData, + "ResponseCustom" + ); cy.voidCallTest(fixtures.voidBody, req_data, res_data, globalState); if (should_continue) @@ -595,9 +601,15 @@ describe("Corner cases", () => { let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ "Refund" ]; - let commonData = getConnectorDetails(globalState.get("commons"))["card_pm"]["Refund"]; + let commonData = getConnectorDetails(globalState.get("commons"))[ + "card_pm" + ]["Refund"]; let req_data = data["Request"]; - let res_data = utils.getConnectorFlowDetails(data, commonData, "ResponseCustom"); + let res_data = utils.getConnectorFlowDetails( + data, + commonData, + "ResponseCustom" + ); cy.refundCallTest( fixtures.refundBody, req_data, @@ -658,9 +670,15 @@ describe("Corner cases", () => { let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ "Refund" ]; - let commonData = getConnectorDetails(globalState.get("commons"))["card_pm"]["Refund"]; + let commonData = getConnectorDetails(globalState.get("commons"))[ + "card_pm" + ]["Refund"]; let req_data = data["Request"]; - let res_data = utils.getConnectorFlowDetails(data, commonData, "ResponseCustom"); + let res_data = utils.getConnectorFlowDetails( + data, + commonData, + "ResponseCustom" + ); cy.refundCallTest( fixtures.refundBody, req_data, @@ -734,8 +752,15 @@ describe("Corner cases", () => { }); it("Confirm No 3DS MIT", () => { + let data = getConnectorDetails(globalState.get("connectorId"))["card_pm"][ + "MITAutoCapture" + ]; + let req_data = data["Request"]; + let res_data = data["Response"]; cy.mitForMandatesCallTest( fixtures.mitConfirmBody, + req_data, + res_data, 65000, true, "manual", diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js b/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js index 9ce384c7a74..81525041147 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Adyen.js @@ -398,6 +398,24 @@ export const connectorDetails = { }, }, }, + MITAutoCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MITManualCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, ZeroAuthMandate: { Request: { payment_method: "card", diff --git a/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js b/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js index 4a443e0962a..af4dee5d537 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/BankOfAmerica.js @@ -395,6 +395,24 @@ export const connectorDetails = { }, }, }, + MITAutoCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MITManualCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, ZeroAuthMandate: { Request: { payment_method: "card", diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js b/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js index ca24a50bcef..72dc8f6479b 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Cybersource.js @@ -458,6 +458,24 @@ export const connectorDetails = { }, }, }, + MITAutoCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MITManualCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, ZeroAuthMandate: { Request: { payment_method: "card", diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Fiuu.js b/cypress-tests/cypress/e2e/PaymentUtils/Fiuu.js index 4a910c7897c..d82a5f128d6 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Fiuu.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Fiuu.js @@ -360,6 +360,28 @@ export const connectorDetails = { }, }, }, + MITAutoCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "failed", + error_code: "The currency not allow for the RecordType", + error_message: "The currency not allow for the RecordType", + }, + }, + }, + MITManualCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "failed", + error_code: "The currency not allow for the RecordType", + error_message: "The currency not allow for the RecordType", + }, + }, + }, PaymentMethodIdMandateNo3DSAutoCapture: { Request: { payment_method: "card", diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Noon.js b/cypress-tests/cypress/e2e/PaymentUtils/Noon.js index 70c056b6c92..38b0c0c1117 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Noon.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Noon.js @@ -468,6 +468,24 @@ export const connectorDetails = { }, }, }, + MITAutoCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MITManualCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, ZeroAuthMandate: { Response: { status: 501, diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Paybox.js b/cypress-tests/cypress/e2e/PaymentUtils/Paybox.js index d1eb91692da..70bfa5c3240 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Paybox.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Paybox.js @@ -6,6 +6,57 @@ const successfulNo3DSCardDetails = { card_cvc: "222", }; +const successfulThreeDSTestCardDetails = { + card_number: "4000000000001091", + card_exp_month: "01", + card_exp_year: "25", + 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", + }, + }, + mandate_type: { + single_use: { + amount: 7000, + currency: "EUR", + }, + }, +}; + +const multiUseMandateData = { + customer_acceptance: { + acceptance_type: "offline", + accepted_at: "1963-05-03T04:07:52.723Z", + online: { + ip_address: "125.0.0.1", + user_agent: "amet irure esse", + }, + }, + mandate_type: { + multi_use: { + amount: 6500, + currency: "EUR", + }, + }, +}; + +const customerAcceptance = { + acceptance_type: "offline", + accepted_at: "1963-05-03T04:07:52.723Z", + online: { + ip_address: "125.0.0.1", + user_agent: "amet irure esse", + }, +}; + export const connectorDetails = { card_pm: { PaymentIntent: { @@ -21,6 +72,22 @@ export const connectorDetails = { }, }, }, + PaymentIntentOffSession: { + Request: { + currency: "EUR", + amount: 6500, + authentication_type: "no_three_ds", + customer_acceptance: null, + setup_future_usage: "off_session", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + setup_future_usage: "off_session", + }, + }, + }, No3DSManualCapture: { Request: { currency: "EUR", @@ -52,7 +119,43 @@ export const connectorDetails = { Response: { status: 200, body: { - status: "processing", + status: "succeeded", + }, + }, + }, + "3DSManualCapture": { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulThreeDSTestCardDetails, + }, + currency: "EUR", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_customer_action", + setup_future_usage: "on_session", + }, + }, + }, + "3DSAutoCapture": { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulThreeDSTestCardDetails, + }, + currency: "EUR", + customer_acceptance: null, + setup_future_usage: "on_session", + }, + Response: { + status: 200, + body: { + status: "requires_customer_action", + setup_future_usage: "on_session", }, }, }, @@ -67,10 +170,10 @@ export const connectorDetails = { Response: { status: 200, body: { - status: "processing", + status: "succeeded", amount: 6500, - amount_capturable: 6500, - amount_received: null, + amount_capturable: 0, + amount_received: 6500, }, }, }, @@ -79,10 +182,24 @@ export const connectorDetails = { Response: { status: 200, body: { - status: "processing", + status: "partially_captured", amount: 6500, - amount_capturable: 6500, - amount_received: null, + amount_capturable: 0, + amount_received: 100, + }, + }, + }, + VoidAfterConfirm: { + Request: {}, + Response: { + status: 501, + body: { + status: "cancelled", + error: { + type: "invalid_request", + message: "Cancel/Void flow is not implemented", + code: "IR_00", + }, }, }, }, @@ -131,7 +248,405 @@ export const connectorDetails = { }, }, }, - + MandateSingleUse3DSAutoCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulThreeDSTestCardDetails, + }, + currency: "EUR", + mandate_data: singleUseMandateData, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "IR_19", + reason: + "Capture Not allowed in case of Creating the Subscriber is not supported by Paybox", + }, + }, + }, + }, + MandateSingleUse3DSManualCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulThreeDSTestCardDetails, + }, + currency: "EUR", + mandate_data: singleUseMandateData, + }, + Response: { + status: 200, + body: { + status: "requires_customer_action", + }, + }, + }, + MandateSingleUseNo3DSAutoCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "EUR", + mandate_data: singleUseMandateData, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "IR_19", + reason: + "Capture Not allowed in case of Creating the Subscriber is not supported by Paybox", + }, + }, + }, + }, + MandateSingleUseNo3DSManualCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "EUR", + mandate_data: singleUseMandateData, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + MandateMultiUseNo3DSAutoCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "EUR", + mandate_data: multiUseMandateData, + }, + Response: { + status: 200, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "IR_19", + reason: + "Capture Not allowed in case of Creating the Subscriber is not supported by Paybox", + }, + }, + }, + }, + MandateMultiUseNo3DSManualCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "EUR", + mandate_data: multiUseMandateData, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + MandateMultiUse3DSAutoCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulThreeDSTestCardDetails, + }, + currency: "EUR", + mandate_data: multiUseMandateData, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "IR_19", + reason: + "Capture Not allowed in case of Creating the Subscriber is not supported by Paybox", + }, + }, + }, + }, + MandateMultiUse3DSManualCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulThreeDSTestCardDetails, + }, + currency: "EUR", + mandate_data: multiUseMandateData, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + MITAutoCapture: { + Request: { + currency: "EUR", + amount: 6500, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MITManualCapture: { + Request: { + currency: "EUR", + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + PaymentMethodIdMandateNo3DSAutoCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "EUR", + mandate_data: null, + customer_acceptance: customerAcceptance, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "IR_19", + reason: + "Capture Not allowed in case of Creating the Subscriber is not supported by Paybox", + }, + }, + }, + }, + PaymentMethodIdMandateNo3DSManualCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "EUR", + mandate_data: null, + customer_acceptance: customerAcceptance, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + PaymentMethodIdMandate3DSAutoCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulThreeDSTestCardDetails, + }, + currency: "EUR", + mandate_data: null, + authentication_type: "three_ds", + customer_acceptance: customerAcceptance, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "IR_19", + reason: + "Capture Not allowed in case of Creating the Subscriber is not supported by Paybox", + }, + }, + }, + }, + PaymentMethodIdMandate3DSManualCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulThreeDSTestCardDetails, + }, + mandate_data: null, + authentication_type: "three_ds", + customer_acceptance: customerAcceptance, + }, + Response: { + status: 200, + body: { + status: "requires_customer_action", + }, + }, + }, + ZeroAuthMandate: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "EUR", + mandate_data: singleUseMandateData, + }, + Response: { + status: 200, + body: { + status: "processing", + }, + }, + }, + ZeroAuthPaymentIntent: { + Request: { + amount: 0, + setup_future_usage: "off_session", + currency: "EUR", + }, + Response: { + status: 200, + body: { + status: "requires_payment_method", + setup_future_usage: "off_session", + }, + }, + }, + ZeroAuthConfirmPayment: { + Request: { + payment_type: "setup_mandate", + payment_method: "card", + payment_method_type: "credit", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + }, + Response: { + status: 200, + body: { + status: "processing", + }, + }, + }, + SaveCardUseNo3DSAutoCapture: { + Request: { + payment_method: "card", + payment_method_type: "debit", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "EUR", + setup_future_usage: "on_session", + customer_acceptance: customerAcceptance, + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + SaveCardUseNo3DSAutoCaptureOffSession: { + Request: { + payment_method: "card", + payment_method_type: "debit", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + setup_future_usage: "off_session", + customer_acceptance: customerAcceptance, + }, + Response: { + status: 400, + body: { + error: { + type: "invalid_request", + message: "Payment method type not supported", + code: "IR_19", + reason: + "Capture Not allowed in case of Creating the Subscriber is not supported by Paybox", + }, + }, + }, + }, + SaveCardUseNo3DSManualCaptureOffSession: { + 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: "requires_capture", + }, + }, + }, + SaveCardConfirmAutoCaptureOffSession: { + Request: { + setup_future_usage: "off_session", + }, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + SaveCardConfirmManualCaptureOffSession: { + Request: { + setup_future_usage: "off_session", + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, + SaveCardUseNo3DSManualCapture: { + Request: { + payment_method: "card", + payment_method_data: { + card: successfulNo3DSCardDetails, + }, + currency: "EUR", + setup_future_usage: "on_session", + customer_acceptance: customerAcceptance, + }, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, InvalidCardNumber: { Request: { currency: "EUR", diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js b/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js index 98af56b882c..984fe63b2fb 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/Stripe.js @@ -448,6 +448,24 @@ export const connectorDetails = { }, }, }, + MITAutoCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MITManualCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, ZeroAuthMandate: { Request: { payment_method: "card", diff --git a/cypress-tests/cypress/e2e/PaymentUtils/WellsFargo.js b/cypress-tests/cypress/e2e/PaymentUtils/WellsFargo.js index b25a6dc7e8b..608343f1083 100644 --- a/cypress-tests/cypress/e2e/PaymentUtils/WellsFargo.js +++ b/cypress-tests/cypress/e2e/PaymentUtils/WellsFargo.js @@ -362,6 +362,24 @@ export const connectorDetails = { }, }, }, + MITAutoCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "succeeded", + }, + }, + }, + MITManualCapture: { + Request: {}, + Response: { + status: 200, + body: { + status: "requires_capture", + }, + }, + }, ZeroAuthMandate: { Request: { payment_method: "card", diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js index 48a62fb4388..17c2270efef 100644 --- a/cypress-tests/cypress/support/commands.js +++ b/cypress-tests/cypress/support/commands.js @@ -1926,7 +1926,18 @@ Cypress.Commands.add( Cypress.Commands.add( "mitForMandatesCallTest", - (requestBody, amount, confirm, capture_method, globalState) => { + ( + requestBody, + req_data, + res_data, + amount, + confirm, + capture_method, + globalState + ) => { + for (const key in req_data) { + requestBody[key] = req_data[key]; + } requestBody.amount = amount; requestBody.confirm = confirm; requestBody.capture_method = capture_method; @@ -1966,10 +1977,13 @@ Cypress.Commands.add( .to.have.property("redirect_to_url"); const nextActionUrl = response.body.next_action.redirect_to_url; cy.log(nextActionUrl); + for (const key in res_data.body) { + expect(res_data.body[key], [key]).to.equal(response.body[key]); + } } else if (response.body.authentication_type === "no_three_ds") { - if (response.body.connector === "fiuu") { - expect(response.body.status).to.equal("failed"); - } + for (const key in res_data.body) { + expect(res_data.body[key], [key]).to.equal(response.body[key]); + } } else { throw new Error( `Invalid authentication type ${response.body.authentication_type}` @@ -1982,11 +1996,12 @@ Cypress.Commands.add( .to.have.property("redirect_to_url"); const nextActionUrl = response.body.next_action.redirect_to_url; cy.log(nextActionUrl); + for (const key in res_data.body) { + expect(res_data.body[key], [key]).to.equal(response.body[key]); + } } else if (response.body.authentication_type === "no_three_ds") { - if (response.body.connector === "fiuu") { - expect(response.body.status).to.equal("failed"); - } else { - expect(response.body.status).to.equal("requires_capture"); + for (const key in res_data.body) { + expect(res_data.body[key], [key]).to.equal(response.body[key]); } } else { throw new Error( @@ -2009,9 +2024,7 @@ Cypress.Commands.add( ); } } else { - throw new Error( - `Error Response: ${response.status}\n${response.body.error.message}\n${response.body.error.code}` - ); + defaultErrorHandler(response, res_data); } }); } @@ -2019,7 +2032,18 @@ Cypress.Commands.add( Cypress.Commands.add( "mitUsingPMId", - (requestBody, amount, confirm, capture_method, globalState) => { + ( + requestBody, + req_data, + res_data, + amount, + confirm, + capture_method, + globalState + ) => { + for (const key in req_data) { + requestBody[key] = req_data[key]; + } requestBody.amount = amount; requestBody.confirm = confirm; requestBody.capture_method = capture_method; @@ -2046,10 +2070,13 @@ Cypress.Commands.add( .to.have.property("redirect_to_url"); const nextActionUrl = response.body.next_action.redirect_to_url; cy.log(nextActionUrl); + for (const key in res_data.body) { + expect(res_data.body[key], [key]).to.equal(response.body[key]); + } } else if (response.body.authentication_type === "no_three_ds") { - if (response.body.connector === "fiuu") { - expect(response.body.status).to.equal("failed"); - } + for (const key in res_data.body) { + expect(res_data.body[key], [key]).to.equal(response.body[key]); + } } else { throw new Error( `Invalid authentication type ${response.body.authentication_type}` @@ -2062,11 +2089,12 @@ Cypress.Commands.add( .to.have.property("redirect_to_url"); const nextActionUrl = response.body.next_action.redirect_to_url; cy.log(nextActionUrl); + for (const key in res_data.body) { + expect(res_data.body[key], [key]).to.equal(response.body[key]); + } } else if (response.body.authentication_type === "no_three_ds") { - if (response.body.connector === "fiuu") { - expect(response.body.status).to.equal("failed"); - } else { - expect(response.body.status).to.equal("requires_capture"); + for (const key in res_data.body) { + expect(res_data.body[key], [key]).to.equal(response.body[key]); } } else { throw new Error( @@ -2079,9 +2107,7 @@ Cypress.Commands.add( ); } } else { - throw new Error( - `Error Response: ${response.status}\n${response.body.error.message}\n${response.body.error.code}` - ); + defaultErrorHandler(response, res_data); } }); } @@ -2089,8 +2115,18 @@ Cypress.Commands.add( Cypress.Commands.add( "mitUsingNTID", - (requestBody, amount, confirm, capture_method, globalState) => { - + ( + requestBody, + req_data, + res_data, + amount, + confirm, + capture_method, + globalState + ) => { + for (const key in req_data) { + requestBody[key] = req_data[key]; + } requestBody.amount = amount; requestBody.confirm = confirm; requestBody.capture_method = capture_method; @@ -2127,8 +2163,13 @@ Cypress.Commands.add( .to.have.property("redirect_to_url"); const nextActionUrl = response.body.next_action.redirect_to_url; cy.log(nextActionUrl); + for (const key in res_data.body) { + expect(res_data.body[key], [key]).to.equal(response.body[key]); + } } else if (response.body.authentication_type === "no_three_ds") { - expect(response.body.status).to.equal("succeeded"); + for (const key in res_data.body) { + expect(res_data.body[key], [key]).to.equal(response.body[key]); + } } else { throw new Error( `Invalid authentication type ${response.body.authentication_type}` @@ -2141,8 +2182,13 @@ Cypress.Commands.add( .to.have.property("redirect_to_url"); const nextActionUrl = response.body.next_action.redirect_to_url; cy.log(nextActionUrl); + for (const key in res_data.body) { + expect(res_data.body[key], [key]).to.equal(response.body[key]); + } } else if (response.body.authentication_type === "no_three_ds") { - expect(response.body.status).to.equal("requires_capture"); + for (const key in res_data.body) { + expect(res_data.body[key], [key]).to.equal(response.body[key]); + } } else { throw new Error( `Invalid authentication type ${response.body.authentication_type}` @@ -2154,9 +2200,7 @@ Cypress.Commands.add( ); } } else { - throw new Error( - `Error Response: ${response.status}\n${response.body.error.message}\n${response.body.error.code}` - ); + defaultErrorHandler(response, res_data); } }); }
ci
Move MIT requests to configs and add Paybox Mandates (#6650)
b8501f6ae6c0af0804d7f1e7cf9f50ebd303bf94
2023-08-29 11:31:45
github-actions
chore(version): v1.29.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 4efb7e25058..56fe5597be5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,27 @@ All notable changes to HyperSwitch will be documented here. - - - +## 1.29.0 (2023-08-29) + +### Features + +- **connector:** [Paypal] add support for payment and refund webhooks ([#2003](https://github.com/juspay/hyperswitch/pull/2003)) ([`ade27f0`](https://github.com/juspay/hyperswitch/commit/ade27f01686d2a0cdee86d4d366cecaa12370ba6)) + +### Bug Fixes + +- **connector:** [Payme] populate error message in case of 2xx payment failures ([#2037](https://github.com/juspay/hyperswitch/pull/2037)) ([`aeebc5b`](https://github.com/juspay/hyperswitch/commit/aeebc5b52584ad8d8c128fa896d39fe8576dca0c)) +- **router:** Remove `attempt_count` in payments list response and add it in payments response ([#2008](https://github.com/juspay/hyperswitch/pull/2008)) ([`23b8d34`](https://github.com/juspay/hyperswitch/commit/23b8d3412c7d14e450b87b3ccb35a394d954d0a7)) + +### Miscellaneous Tasks + +- **creds:** Update connector API credentials ([#2034](https://github.com/juspay/hyperswitch/pull/2034)) ([`f04bee2`](https://github.com/juspay/hyperswitch/commit/f04bee261141622b63e34e1ebd4b0de4641e0210)) +- Address Rust 1.72 clippy lints ([#2011](https://github.com/juspay/hyperswitch/pull/2011)) ([`eaefa6e`](https://github.com/juspay/hyperswitch/commit/eaefa6e15c4facc28440d7fdc3aac9be0976324d)) + +**Full Changelog:** [`v1.28.1...v1.29.0`](https://github.com/juspay/hyperswitch/compare/v1.28.1...v1.29.0) + +- - - + + ## 1.28.1 (2023-08-28) ### Bug Fixes
chore
v1.29.0
480e8c3dcf59d6e4052aa0077dd06278fba973ff
2025-03-17 19:45:09
Prajjwal Kumar
refactor(currency_conversion): add support for expiring forex data in redis (#7455)
false
diff --git a/config/config.example.toml b/config/config.example.toml index b90bfa8aabf..7ae8e5d547c 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -74,10 +74,11 @@ max_feed_count = 200 # The maximum number of frames that will be fe # This section provides configs for currency conversion api [forex_api] -call_delay = 21600 # Expiration time for data in cache as well as redis in seconds api_key = "" # Api key for making request to foreign exchange Api fallback_api_key = "" # Api key for the fallback service -redis_lock_timeout = 100 # Redis remains write locked for 100 s once the acquire_redis_lock is called +redis_ttl_in_seconds = 172800 # Time to expire for forex data stored in Redis +data_expiration_delay_in_seconds = 21600 # Expiration time for data in cache as well as redis in seconds +redis_lock_timeout_in_seconds = 100 # Redis remains write locked for 100 s once the acquire_redis_lock is called # Logging configuration. Logging can be either to file or console or both. @@ -935,4 +936,4 @@ primary_color = "#006DF9" # Primary color of email body background_color = "#FFFFFF" # Background color of email body [additional_revenue_recovery_details_call] -connectors_with_additional_revenue_recovery_details_call = "stripebilling" # List of connectors which has additional revenue recovery details api-call \ No newline at end of file +connectors_with_additional_revenue_recovery_details_call = "stripebilling" # List of connectors which has additional revenue recovery details api-call diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 157e0aa3a42..b2ee7f39741 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -104,10 +104,11 @@ bucket_name = "bucket" # The AWS S3 bucket name for file storage # This section provides configs for currency conversion api [forex_api] -call_delay = 21600 # Expiration time for data in cache as well as redis in seconds api_key = "" # Api key for making request to foreign exchange Api fallback_api_key = "" # Api key for the fallback service -redis_lock_timeout = 100 # Redis remains write locked for 100 s once the acquire_redis_lock is called +data_expiration_delay_in_seconds = 21600 # Expiration time for data in cache as well as redis in seconds +redis_lock_timeout_in_seconds = 100 # Redis remains write locked for 100 s once the acquire_redis_lock is called +redis_ttl_in_seconds = 172800 # Time to expire for forex data stored in Redis [jwekey] # 3 priv/pub key pair vault_encryption_key = "" # public key in pem format, corresponding private key in rust locker diff --git a/config/development.toml b/config/development.toml index 739366b6042..d0dbbeae0eb 100644 --- a/config/development.toml +++ b/config/development.toml @@ -77,10 +77,11 @@ locker_enabled = true ttl_for_storage_in_secs = 220752000 [forex_api] -call_delay = 21600 api_key = "" fallback_api_key = "" -redis_lock_timeout = 100 +data_expiration_delay_in_seconds = 21600 +redis_lock_timeout_in_seconds = 100 +redis_ttl_in_seconds = 172800 [jwekey] vault_encryption_key = """ diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 956f7fa46d4..da58ab45dbd 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -30,10 +30,11 @@ dbname = "hyperswitch_db" pool_size = 5 [forex_api] -call_delay = 21600 api_key = "" fallback_api_key = "" -redis_lock_timeout = 100 +data_expiration_delay_in_seconds = 21600 +redis_lock_timeout_in_seconds = 100 +redis_ttl_in_seconds = 172800 [replica_database] username = "db_user" diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs index 605b4b576f3..b1c92046d0e 100644 --- a/crates/router/src/configs/settings.rs +++ b/crates/router/src/configs/settings.rs @@ -409,10 +409,9 @@ pub struct PaymentLink { pub struct ForexApi { pub api_key: Secret<String>, pub fallback_api_key: Secret<String>, - /// in s - pub call_delay: i64, - /// in s - pub redis_lock_timeout: u64, + pub data_expiration_delay_in_seconds: u32, + pub redis_lock_timeout_in_seconds: u32, + pub redis_ttl_in_seconds: u32, } #[derive(Debug, Deserialize, Clone, Default)] diff --git a/crates/router/src/core/currency.rs b/crates/router/src/core/currency.rs index 8c1a8512892..bc63dc878cc 100644 --- a/crates/router/src/core/currency.rs +++ b/crates/router/src/core/currency.rs @@ -15,7 +15,7 @@ pub async fn retrieve_forex( ) -> CustomResult<ApplicationResponse<currency::FxExchangeRatesCacheEntry>, ApiErrorResponse> { let forex_api = state.conf.forex_api.get_inner(); Ok(ApplicationResponse::Json( - get_forex_rates(&state, forex_api.call_delay) + get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds) .await .change_context(ApiErrorResponse::GenericNotFoundError { message: "Unable to fetch forex rates".to_string(), @@ -48,7 +48,7 @@ pub async fn get_forex_exchange_rates( state: SessionState, ) -> CustomResult<ExchangeRates, AnalyticsError> { let forex_api = state.conf.forex_api.get_inner(); - let rates = get_forex_rates(&state, forex_api.call_delay) + let rates = get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds) .await .change_context(AnalyticsError::ForexFetchFailed)?; diff --git a/crates/router/src/utils/currency.rs b/crates/router/src/utils/currency.rs index 4af9f3865f4..cd56382985b 100644 --- a/crates/router/src/utils/currency.rs +++ b/crates/router/src/utils/currency.rs @@ -38,7 +38,7 @@ static FX_EXCHANGE_RATES_CACHE: Lazy<RwLock<Option<FxExchangeRatesCacheEntry>>> impl ApiEventMetric for FxExchangeRatesCacheEntry {} #[derive(Debug, Clone, thiserror::Error)] -pub enum ForexCacheError { +pub enum ForexError { #[error("API error")] ApiError, #[error("API timeout")] @@ -107,8 +107,8 @@ impl FxExchangeRatesCacheEntry { timestamp: date_time::now_unix_timestamp(), } } - fn is_expired(&self, call_delay: i64) -> bool { - self.timestamp + call_delay < date_time::now_unix_timestamp() + fn is_expired(&self, data_expiration_delay: u32) -> bool { + self.timestamp + i64::from(data_expiration_delay) < date_time::now_unix_timestamp() } } @@ -118,7 +118,7 @@ async fn retrieve_forex_from_local_cache() -> Option<FxExchangeRatesCacheEntry> async fn save_forex_data_to_local_cache( exchange_rates_cache_entry: FxExchangeRatesCacheEntry, -) -> CustomResult<(), ForexCacheError> { +) -> CustomResult<(), ForexError> { let mut local = FX_EXCHANGE_RATES_CACHE.write().await; *local = Some(exchange_rates_cache_entry); logger::debug!("forex_log: forex saved in cache"); @@ -126,17 +126,17 @@ async fn save_forex_data_to_local_cache( } impl TryFrom<DefaultExchangeRates> for ExchangeRates { - type Error = error_stack::Report<ForexCacheError>; + type Error = error_stack::Report<ForexError>; fn try_from(value: DefaultExchangeRates) -> Result<Self, Self::Error> { let mut conversion_usable: HashMap<enums::Currency, CurrencyFactors> = HashMap::new(); for (curr, conversion) in value.conversion { let enum_curr = enums::Currency::from_str(curr.as_str()) - .change_context(ForexCacheError::ConversionError) + .change_context(ForexError::ConversionError) .attach_printable("Unable to Convert currency received")?; conversion_usable.insert(enum_curr, CurrencyFactors::from(conversion)); } let base_curr = enums::Currency::from_str(value.base_currency.as_str()) - .change_context(ForexCacheError::ConversionError) + .change_context(ForexError::ConversionError) .attach_printable("Unable to convert base currency")?; Ok(Self { base_currency: base_curr, @@ -157,10 +157,10 @@ impl From<Conversion> for CurrencyFactors { #[instrument(skip_all)] pub async fn get_forex_rates( state: &SessionState, - call_delay: i64, -) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { + data_expiration_delay: u32, +) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { if let Some(local_rates) = retrieve_forex_from_local_cache().await { - if local_rates.is_expired(call_delay) { + if local_rates.is_expired(data_expiration_delay) { // expired local data logger::debug!("forex_log: Forex stored in cache is expired"); call_forex_api_and_save_data_to_cache_and_redis(state, Some(local_rates)).await @@ -171,26 +171,28 @@ pub async fn get_forex_rates( } } else { // No data in local - call_api_if_redis_forex_data_expired(state, call_delay).await + call_api_if_redis_forex_data_expired(state, data_expiration_delay).await } } async fn call_api_if_redis_forex_data_expired( state: &SessionState, - call_delay: i64, -) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { + data_expiration_delay: u32, +) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { match retrieve_forex_data_from_redis(state).await { - Ok(Some(data)) => call_forex_api_if_redis_data_expired(state, data, call_delay).await, + Ok(Some(data)) => { + call_forex_api_if_redis_data_expired(state, data, data_expiration_delay).await + } Ok(None) => { // No data in local as well as redis call_forex_api_and_save_data_to_cache_and_redis(state, None).await?; - Err(ForexCacheError::ForexDataUnavailable.into()) + Err(ForexError::ForexDataUnavailable.into()) } Err(error) => { // Error in deriving forex rates from redis logger::error!("forex_error: {:?}", error); call_forex_api_and_save_data_to_cache_and_redis(state, None).await?; - Err(ForexCacheError::ForexDataUnavailable.into()) + Err(ForexError::ForexDataUnavailable.into()) } } } @@ -198,11 +200,11 @@ async fn call_api_if_redis_forex_data_expired( async fn call_forex_api_and_save_data_to_cache_and_redis( state: &SessionState, stale_redis_data: Option<FxExchangeRatesCacheEntry>, -) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { +) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { // spawn a new thread and do the api fetch and write operations on redis. let forex_api_key = state.conf.forex_api.get_inner().api_key.peek(); if forex_api_key.is_empty() { - Err(ForexCacheError::ConfigurationError("api_keys not provided".into()).into()) + Err(ForexError::ConfigurationError("api_keys not provided".into()).into()) } else { let state = state.clone(); tokio::spawn( @@ -216,16 +218,16 @@ async fn call_forex_api_and_save_data_to_cache_and_redis( } .in_current_span(), ); - stale_redis_data.ok_or(ForexCacheError::EntryNotFound.into()) + stale_redis_data.ok_or(ForexError::EntryNotFound.into()) } } async fn acquire_redis_lock_and_call_forex_api( state: &SessionState, -) -> CustomResult<(), ForexCacheError> { +) -> CustomResult<(), ForexError> { let lock_acquired = acquire_redis_lock(state).await?; if !lock_acquired { - Err(ForexCacheError::CouldNotAcquireLock.into()) + Err(ForexError::CouldNotAcquireLock.into()) } else { logger::debug!("forex_log: redis lock acquired"); let api_rates = fetch_forex_rates_from_primary_api(state).await; @@ -250,7 +252,7 @@ async fn acquire_redis_lock_and_call_forex_api( async fn save_forex_data_to_cache_and_redis( state: &SessionState, forex: FxExchangeRatesCacheEntry, -) -> CustomResult<(), ForexCacheError> { +) -> CustomResult<(), ForexError> { save_forex_data_to_redis(state, &forex) .await .async_and_then(|_rates| release_redis_lock(state)) @@ -262,9 +264,9 @@ async fn save_forex_data_to_cache_and_redis( async fn call_forex_api_if_redis_data_expired( state: &SessionState, redis_data: FxExchangeRatesCacheEntry, - call_delay: i64, -) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { - match is_redis_expired(Some(redis_data.clone()).as_ref(), call_delay).await { + data_expiration_delay: u32, +) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { + match is_redis_expired(Some(redis_data.clone()).as_ref(), data_expiration_delay).await { Some(redis_forex) => { // Valid data present in redis let exchange_rates = FxExchangeRatesCacheEntry::new(redis_forex.as_ref().clone()); @@ -281,7 +283,7 @@ async fn call_forex_api_if_redis_data_expired( async fn fetch_forex_rates_from_primary_api( state: &SessionState, -) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexCacheError>> { +) -> Result<FxExchangeRatesCacheEntry, error_stack::Report<ForexError>> { let forex_api_key = state.conf.forex_api.get_inner().api_key.peek(); logger::debug!("forex_log: Primary api call for forex fetch"); @@ -301,12 +303,12 @@ async fn fetch_forex_rates_from_primary_api( false, ) .await - .change_context(ForexCacheError::ApiUnresponsive) + .change_context(ForexError::ApiUnresponsive) .attach_printable("Primary forex fetch api unresponsive")?; let forex_response = response .json::<ForexResponse>() .await - .change_context(ForexCacheError::ParsingError) + .change_context(ForexError::ParsingError) .attach_printable( "Unable to parse response received from primary api into ForexResponse", )?; @@ -347,7 +349,7 @@ async fn fetch_forex_rates_from_primary_api( pub async fn fetch_forex_rates_from_fallback_api( state: &SessionState, -) -> CustomResult<FxExchangeRatesCacheEntry, ForexCacheError> { +) -> CustomResult<FxExchangeRatesCacheEntry, ForexError> { let fallback_forex_api_key = state.conf.forex_api.get_inner().fallback_api_key.peek(); let fallback_forex_url: String = @@ -367,13 +369,13 @@ pub async fn fetch_forex_rates_from_fallback_api( false, ) .await - .change_context(ForexCacheError::ApiUnresponsive) + .change_context(ForexError::ApiUnresponsive) .attach_printable("Fallback forex fetch api unresponsive")?; let fallback_forex_response = response .json::<FallbackForexResponse>() .await - .change_context(ForexCacheError::ParsingError) + .change_context(ForexError::ParsingError) .attach_printable( "Unable to parse response received from falback api into ForexResponse", )?; @@ -432,74 +434,76 @@ pub async fn fetch_forex_rates_from_fallback_api( async fn release_redis_lock( state: &SessionState, -) -> Result<DelReply, error_stack::Report<ForexCacheError>> { +) -> Result<DelReply, error_stack::Report<ForexError>> { logger::debug!("forex_log: Releasing redis lock"); state .store .get_redis_conn() - .change_context(ForexCacheError::RedisConnectionError)? + .change_context(ForexError::RedisConnectionError)? .delete_key(&REDIX_FOREX_CACHE_KEY.into()) .await - .change_context(ForexCacheError::RedisLockReleaseFailed) + .change_context(ForexError::RedisLockReleaseFailed) .attach_printable("Unable to release redis lock") } -async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexCacheError> { +async fn acquire_redis_lock(state: &SessionState) -> CustomResult<bool, ForexError> { let forex_api = state.conf.forex_api.get_inner(); logger::debug!("forex_log: Acquiring redis lock"); state .store .get_redis_conn() - .change_context(ForexCacheError::RedisConnectionError)? + .change_context(ForexError::RedisConnectionError)? .set_key_if_not_exists_with_expiry( &REDIX_FOREX_CACHE_KEY.into(), "", - Some( - i64::try_from(forex_api.redis_lock_timeout) - .change_context(ForexCacheError::ConversionError)?, - ), + Some(i64::from(forex_api.redis_lock_timeout_in_seconds)), ) .await .map(|val| matches!(val, redis_interface::SetnxReply::KeySet)) - .change_context(ForexCacheError::CouldNotAcquireLock) + .change_context(ForexError::CouldNotAcquireLock) .attach_printable("Unable to acquire redis lock") } async fn save_forex_data_to_redis( app_state: &SessionState, forex_exchange_cache_entry: &FxExchangeRatesCacheEntry, -) -> CustomResult<(), ForexCacheError> { +) -> CustomResult<(), ForexError> { + let forex_api = app_state.conf.forex_api.get_inner(); logger::debug!("forex_log: Saving forex to redis"); app_state .store .get_redis_conn() - .change_context(ForexCacheError::RedisConnectionError)? - .serialize_and_set_key(&REDIX_FOREX_CACHE_DATA.into(), forex_exchange_cache_entry) + .change_context(ForexError::RedisConnectionError)? + .serialize_and_set_key_with_expiry( + &REDIX_FOREX_CACHE_DATA.into(), + forex_exchange_cache_entry, + i64::from(forex_api.redis_ttl_in_seconds), + ) .await - .change_context(ForexCacheError::RedisWriteError) + .change_context(ForexError::RedisWriteError) .attach_printable("Unable to save forex data to redis") } async fn retrieve_forex_data_from_redis( app_state: &SessionState, -) -> CustomResult<Option<FxExchangeRatesCacheEntry>, ForexCacheError> { +) -> CustomResult<Option<FxExchangeRatesCacheEntry>, ForexError> { logger::debug!("forex_log: Retrieving forex from redis"); app_state .store .get_redis_conn() - .change_context(ForexCacheError::RedisConnectionError)? + .change_context(ForexError::RedisConnectionError)? .get_and_deserialize_key(&REDIX_FOREX_CACHE_DATA.into(), "FxExchangeRatesCache") .await - .change_context(ForexCacheError::EntryNotFound) + .change_context(ForexError::EntryNotFound) .attach_printable("Forex entry not found in redis") } async fn is_redis_expired( redis_cache: Option<&FxExchangeRatesCacheEntry>, - call_delay: i64, + data_expiration_delay: u32, ) -> Option<Arc<ExchangeRates>> { redis_cache.and_then(|cache| { - if cache.timestamp + call_delay > date_time::now_unix_timestamp() { + if cache.timestamp + i64::from(data_expiration_delay) > date_time::now_unix_timestamp() { Some(cache.data.clone()) } else { logger::debug!("forex_log: Forex stored in redis is expired"); @@ -514,23 +518,23 @@ pub async fn convert_currency( amount: i64, to_currency: String, from_currency: String, -) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexCacheError> { +) -> CustomResult<api_models::currency::CurrencyConversionResponse, ForexError> { let forex_api = state.conf.forex_api.get_inner(); - let rates = get_forex_rates(&state, forex_api.call_delay) + let rates = get_forex_rates(&state, forex_api.data_expiration_delay_in_seconds) .await - .change_context(ForexCacheError::ApiError)?; + .change_context(ForexError::ApiError)?; let to_currency = enums::Currency::from_str(to_currency.as_str()) - .change_context(ForexCacheError::CurrencyNotAcceptable) + .change_context(ForexError::CurrencyNotAcceptable) .attach_printable("The provided currency is not acceptable")?; let from_currency = enums::Currency::from_str(from_currency.as_str()) - .change_context(ForexCacheError::CurrencyNotAcceptable) + .change_context(ForexError::CurrencyNotAcceptable) .attach_printable("The provided currency is not acceptable")?; let converted_amount = currency_conversion::conversion::convert(&rates.data, from_currency, to_currency, amount) - .change_context(ForexCacheError::ConversionError) + .change_context(ForexError::ConversionError) .attach_printable("Unable to perform currency conversion")?; Ok(api_models::currency::CurrencyConversionResponse { diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 747f5365e01..7844f9a6970 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -47,10 +47,11 @@ locker_enabled = true ttl_for_storage_in_secs = 220752000 [forex_api] -call_delay = 21600 api_key = "" fallback_api_key = "" -redis_lock_timeout = 100 +data_expiration_delay_in_seconds = 21600 +redis_lock_timeout_in_seconds = 100 +redis_ttl_in_seconds = 172800 [eph_key] validity = 1
refactor
add support for expiring forex data in redis (#7455)
d23e14c57a1defe46416130bda4845973b62a54d
2023-04-21 02:52:40
Sangamesh Kulkarni
feat: support gpay and applepay session response for all connectors (#839)
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/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs index 0aae07bb046..f7985c1fc42 100644 --- a/crates/api_models/src/enums.rs +++ b/crates/api_models/src/enums.rs @@ -668,16 +668,6 @@ pub enum RoutableConnectors { Worldpay, } -/// Wallets which support obtaining session object -#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] -#[serde(rename_all = "snake_case")] -pub enum SupportedWallets { - Paypal, - ApplePay, - Klarna, - Gpay, -} - /// Name of banks supported by Hyperswitch #[derive( Clone, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index cba73e3f3a6..d0165aa1f13 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1339,8 +1339,8 @@ pub struct PaymentsSessionRequest { /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets - #[schema(value_type = Vec<SupportedWallets>)] - pub wallets: Vec<api_enums::SupportedWallets>, + #[schema(value_type = Vec<PaymentMethodType>)] + pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } @@ -1412,6 +1412,44 @@ pub struct GpaySessionTokenData { pub data: GpayMetaData, } +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ApplepaySessionRequest { + pub merchant_identifier: String, + pub display_name: String, + pub initiative: String, + pub initiative_context: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ApplepaySessionTokenData { + #[serde(rename = "apple_pay")] + pub data: ApplePayMetadata, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct ApplePayMetadata { + pub payment_request_data: PaymentRequestMetadata, + pub session_token_data: SessionTokenInfo, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct PaymentRequestMetadata { + pub supported_networks: Vec<String>, + pub merchant_capabilities: Vec<String>, + pub label: String, +} + +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct SessionTokenInfo { + pub certificate: String, + pub certificate_keys: String, + pub merchant_identifier: String, + pub display_name: String, + pub initiative: String, + pub initiative_context: String, +} + #[derive(Debug, Clone, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] @@ -1435,6 +1473,7 @@ pub struct GpaySessionTokenResponse { pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, + pub connector: String, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] @@ -1460,9 +1499,11 @@ pub struct ApplepaySessionTokenResponse { pub session_token_data: ApplePaySessionResponse, /// Payment request object for Apple Pay pub payment_request_data: ApplePayPaymentRequest, + pub connector: String, } #[derive(Debug, Clone, serde::Serialize, ToSchema, serde::Deserialize)] +#[serde(rename_all = "camelCase")] pub struct ApplePaySessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, @@ -1501,6 +1542,7 @@ pub struct ApplePayPaymentRequest { pub merchant_capabilities: Vec<String>, /// The list of supported networks pub supported_networks: Vec<String>, + pub merchant_identifier: String, } #[derive(Debug, Clone, serde::Serialize, ToSchema, serde::Deserialize)] @@ -1514,6 +1556,13 @@ pub struct AmountInfo { pub amount: String, } +#[derive(Debug, Clone, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ApplepayErrorResponse { + pub status_code: String, + pub status_message: String, +} + #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index caa22ac115e..659dade2f84 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -1,7 +1,6 @@ pub mod aci; pub mod adyen; pub mod airwallex; -pub mod applepay; pub mod authorizedotnet; pub mod bambora; pub mod bluesnap; @@ -32,11 +31,11 @@ pub mod worldpay; pub mod mollie; pub use self::{ - aci::Aci, adyen::Adyen, airwallex::Airwallex, applepay::Applepay, - authorizedotnet::Authorizedotnet, bambora::Bambora, bluesnap::Bluesnap, braintree::Braintree, - checkout::Checkout, coinbase::Coinbase, cybersource::Cybersource, dlocal::Dlocal, - fiserv::Fiserv, forte::Forte, globalpay::Globalpay, klarna::Klarna, mollie::Mollie, - multisafepay::Multisafepay, nexinets::Nexinets, nuvei::Nuvei, opennode::Opennode, - payeezy::Payeezy, paypal::Paypal, payu::Payu, rapyd::Rapyd, shift4::Shift4, stripe::Stripe, - trustpay::Trustpay, worldline::Worldline, worldpay::Worldpay, + aci::Aci, adyen::Adyen, airwallex::Airwallex, authorizedotnet::Authorizedotnet, + bambora::Bambora, bluesnap::Bluesnap, braintree::Braintree, checkout::Checkout, + coinbase::Coinbase, cybersource::Cybersource, dlocal::Dlocal, fiserv::Fiserv, forte::Forte, + globalpay::Globalpay, klarna::Klarna, mollie::Mollie, multisafepay::Multisafepay, + nexinets::Nexinets, nuvei::Nuvei, opennode::Opennode, payeezy::Payeezy, paypal::Paypal, + payu::Payu, rapyd::Rapyd, shift4::Shift4, stripe::Stripe, trustpay::Trustpay, + worldline::Worldline, worldpay::Worldpay, }; diff --git a/crates/router/src/connector/applepay.rs b/crates/router/src/connector/applepay.rs deleted file mode 100644 index 8bc5ccd5bb2..00000000000 --- a/crates/router/src/connector/applepay.rs +++ /dev/null @@ -1,273 +0,0 @@ -mod transformers; - -use std::fmt::Debug; - -use common_utils::ext_traits::ValueExt; -use error_stack::{IntoReport, ResultExt}; - -use self::transformers as applepay; -use crate::{ - configs::settings, - core::errors::{self, CustomResult}, - headers, services, - types::{ - self, - api::{self, ConnectorCommon}, - }, - utils::{self, BytesExt, OptionExt}, -}; - -#[derive(Debug, Clone)] -pub struct Applepay; - -impl ConnectorCommon for Applepay { - fn id(&self) -> &'static str { - "applepay" - } - - fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str { - connectors.applepay.base_url.as_ref() - } -} - -impl api::Payment for Applepay {} -impl api::PaymentAuthorize for Applepay {} -impl api::PaymentSync for Applepay {} -impl api::PaymentVoid for Applepay {} -impl api::PaymentCapture for Applepay {} -impl api::PreVerify for Applepay {} -impl api::PaymentSession for Applepay {} -impl api::ConnectorAccessToken for Applepay {} -impl api::PaymentToken for Applepay {} - -impl - services::ConnectorIntegration< - api::PaymentMethodToken, - types::PaymentMethodTokenizationData, - types::PaymentsResponseData, - > for Applepay -{ - // Not Implemented (R) -} - -impl - services::ConnectorIntegration< - api::AccessTokenAuth, - types::AccessTokenRequestData, - types::AccessToken, - > for Applepay -{ - // Not Implemented (R) -} - -impl - services::ConnectorIntegration< - api::Verify, - types::VerifyRequestData, - types::PaymentsResponseData, - > for Applepay -{ -} - -impl - services::ConnectorIntegration< - api::Capture, - types::PaymentsCaptureData, - types::PaymentsResponseData, - > for Applepay -{ -} - -impl - services::ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData> - for Applepay -{ -} - -impl - services::ConnectorIntegration< - api::Authorize, - types::PaymentsAuthorizeData, - types::PaymentsResponseData, - > for Applepay -{ -} - -impl - services::ConnectorIntegration< - api::Void, - types::PaymentsCancelData, - types::PaymentsResponseData, - > for Applepay -{ -} - -#[async_trait::async_trait] -impl - services::ConnectorIntegration< - api::Session, - types::PaymentsSessionData, - types::PaymentsResponseData, - > for Applepay -{ - fn get_headers( - &self, - _req: &types::PaymentsSessionRouterData, - _connectors: &settings::Connectors, - ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { - let header = vec![( - headers::CONTENT_TYPE.to_string(), - types::PaymentsSessionType::get_content_type(self).to_string(), - )]; - Ok(header) - } - - fn get_url( - &self, - _req: &types::PaymentsSessionRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}{}", - self.base_url(connectors), - "paymentservices/paymentSession" - )) - } - - fn get_request_body( - &self, - req: &types::PaymentsSessionRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let connector_req = applepay::ApplepaySessionRequest::try_from(req)?; - let req = utils::Encode::<applepay::ApplepaySessionRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(req)) - } - - fn build_request( - &self, - req: &types::PaymentsSessionRouterData, - connectors: &settings::Connectors, - ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - let request = services::RequestBuilder::new() - .method(services::Method::Post) - .url(&types::PaymentsSessionType::get_url(self, req, connectors)?) - .attach_default_headers() - .headers(types::PaymentsSessionType::get_headers( - self, req, connectors, - )?) - .body(types::PaymentsSessionType::get_request_body(self, req)?) - .add_certificate(types::PaymentsSessionType::get_certificate(self, req)?) - .add_certificate_key(types::PaymentsSessionType::get_certificate_key(self, req)?) - .build(); - Ok(Some(request)) - } - - fn handle_response( - &self, - data: &types::PaymentsSessionRouterData, - res: types::Response, - ) -> CustomResult<types::PaymentsSessionRouterData, errors::ConnectorError> { - let response: applepay::ApplepaySessionTokenResponse = res - .response - .parse_struct("ApplepaySessionResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - - types::RouterData::try_from(types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }) - .change_context(errors::ConnectorError::ResponseHandlingFailed) - } - - fn get_error_response( - &self, - res: types::Response, - ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> { - let response: applepay::ErrorResponse = res - .response - .parse_struct("ErrorResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - Ok(types::ErrorResponse { - status_code: res.status_code, - code: response.status_code, - message: response.status_message, - reason: None, - }) - } - - fn get_certificate( - &self, - req: &types::PaymentsSessionRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let metadata = req - .connector_meta_data - .to_owned() - .get_required_value("connector_meta_data") - .change_context(errors::ConnectorError::NoConnectorMetaData)?; - - let metadata: transformers::ApplePayMetadata = metadata - .parse_value("ApplePayMetaData") - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - - Ok(Some(metadata.session_token_data.certificate)) - } - - fn get_certificate_key( - &self, - req: &types::PaymentsSessionRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let metadata = req - .connector_meta_data - .to_owned() - .get_required_value("connector_meta_data") - .change_context(errors::ConnectorError::NoConnectorMetaData)?; - - let metadata: transformers::ApplePayMetadata = metadata - .parse_value("ApplePayMetaData") - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - - Ok(Some(metadata.session_token_data.certificate_keys)) - } -} - -impl api::Refund for Applepay {} -impl api::RefundExecute for Applepay {} -impl api::RefundSync for Applepay {} - -impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> - for Applepay -{ -} - -impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> - for Applepay -{ -} - -#[async_trait::async_trait] -impl api::IncomingWebhook for Applepay { - fn get_webhook_object_reference_id( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() - } - - fn get_webhook_event_type( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() - } - - fn get_webhook_resource_object( - &self, - _request: &api::IncomingWebhookRequestDetails<'_>, - ) -> CustomResult<serde_json::Value, errors::ConnectorError> { - Err(errors::ConnectorError::WebhooksNotImplemented).into_report() - } -} diff --git a/crates/router/src/connector/applepay/transformers.rs b/crates/router/src/connector/applepay/transformers.rs deleted file mode 100644 index 4d203870999..00000000000 --- a/crates/router/src/connector/applepay/transformers.rs +++ /dev/null @@ -1,228 +0,0 @@ -use api_models::payments; -use common_utils::ext_traits::ValueExt; -use error_stack::ResultExt; -use masking::{Deserialize, Serialize}; - -use crate::{connector::utils, core::errors, types, utils::OptionExt}; - -#[derive(Debug, Serialize)] -#[serde(rename_all = "camelCase")] -pub struct ApplepaySessionRequest { - merchant_identifier: String, - display_name: String, - initiative: String, - initiative_context: String, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ApplepaySessionTokenResponse { - pub epoch_timestamp: u64, - pub expires_at: u64, - pub merchant_session_identifier: String, - pub nonce: String, - pub merchant_identifier: String, - pub domain_name: String, - pub display_name: String, - pub signature: String, - pub operational_analytics_identifier: String, - pub retries: u8, - pub psp_id: String, -} - -#[derive(Debug, Default, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub struct ErrorResponse { - pub status_code: String, - pub status_message: String, -} - -#[derive(Debug, Default, Serialize, Deserialize)] -pub struct ApplePayMetadata { - pub payment_request_data: PaymentRequestMetadata, - pub session_token_data: SessionRequest, -} - -#[derive(Debug, Default, Serialize, Deserialize)] -pub struct PaymentRequestMetadata { - pub supported_networks: Vec<String>, - pub merchant_capabilities: Vec<String>, - pub label: String, -} - -#[derive(Debug, Default, Serialize, Deserialize)] -pub struct SessionRequest { - pub certificate: String, - pub certificate_keys: String, - pub merchant_identifier: String, - pub display_name: String, - pub initiative: String, - pub initiative_context: String, -} - -#[derive(Debug, Default, Serialize, Deserialize)] -#[serde(rename_all = "snake_case")] -pub struct PaymentRequest { - pub apple_pay_merchant_id: String, - pub country_code: api_models::enums::CountryCode, - pub currency_code: String, - pub total: AmountInfo, - pub merchant_capabilities: Vec<String>, - pub supported_networks: Vec<String>, -} - -#[derive(Debug, Default, Serialize, Deserialize)] -pub struct AmountInfo { - pub label: String, - #[serde(rename = "type")] - pub label_type: String, - pub amount: String, -} - -impl TryFrom<&types::PaymentsSessionRouterData> for ApplepaySessionRequest { - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from(item: &types::PaymentsSessionRouterData) -> Result<Self, Self::Error> { - let metadata = item - .connector_meta_data - .to_owned() - .get_required_value("connector_meta_data") - .change_context(errors::ConnectorError::NoConnectorMetaData)?; - - let metadata: ApplePayMetadata = metadata - .parse_value("ApplePayMetadata") - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - - Ok(Self { - merchant_identifier: metadata.session_token_data.merchant_identifier, - display_name: metadata.session_token_data.display_name, - initiative: metadata.session_token_data.initiative, - initiative_context: metadata.session_token_data.initiative_context, - }) - } -} - -impl<F> - TryFrom< - types::ResponseRouterData< - F, - ApplepaySessionTokenResponse, - types::PaymentsSessionData, - types::PaymentsResponseData, - >, - > for types::RouterData<F, types::PaymentsSessionData, types::PaymentsResponseData> -{ - type Error = error_stack::Report<errors::ConnectorError>; - fn try_from( - item: types::ResponseRouterData< - F, - ApplepaySessionTokenResponse, - types::PaymentsSessionData, - types::PaymentsResponseData, - >, - ) -> Result<Self, Self::Error> { - let metadata = item - .data - .connector_meta_data - .to_owned() - .get_required_value("connector_meta_data") - .change_context(errors::ConnectorError::NoConnectorMetaData)?; - - let metadata: ApplePayMetadata = metadata - .parse_value("ApplePayMetadata") - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - - let amount_info = AmountInfo { - label: metadata.payment_request_data.label, - label_type: "final".to_string(), - amount: utils::to_currency_base_unit( - item.data.request.amount, - item.data.request.currency, - )?, - }; - - let payment_request = PaymentRequest { - country_code: item - .data - .request - .country - .to_owned() - .get_required_value("country_code") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "country_code", - })?, - currency_code: item.data.request.currency.to_string(), - total: amount_info, - merchant_capabilities: metadata.payment_request_data.merchant_capabilities, - supported_networks: metadata.payment_request_data.supported_networks, - apple_pay_merchant_id: metadata.session_token_data.merchant_identifier, - }; - - let applepay_session = ApplepaySessionTokenResponse { - epoch_timestamp: item.response.epoch_timestamp, - expires_at: item.response.expires_at, - merchant_session_identifier: item.response.merchant_session_identifier, - nonce: item.response.nonce, - merchant_identifier: item.response.merchant_identifier, - domain_name: item.response.domain_name, - display_name: item.response.display_name, - signature: item.response.signature, - operational_analytics_identifier: item.response.operational_analytics_identifier, - retries: item.response.retries, - psp_id: item.response.psp_id, - }; - - Ok(Self { - response: Ok(types::PaymentsResponseData::SessionResponse { - session_token: { - api_models::payments::SessionToken::ApplePay(Box::new( - payments::ApplepaySessionTokenResponse { - session_token_data: applepay_session.into(), - payment_request_data: payment_request.into(), - }, - )) - }, - }), - ..item.data - }) - } -} - -impl From<PaymentRequest> for payments::ApplePayPaymentRequest { - fn from(value: PaymentRequest) -> Self { - Self { - country_code: value.country_code, - currency_code: value.currency_code, - total: value.total.into(), - merchant_capabilities: value.merchant_capabilities, - supported_networks: value.supported_networks, - } - } -} - -impl From<AmountInfo> for payments::AmountInfo { - fn from(value: AmountInfo) -> Self { - Self { - label: value.label, - total_type: value.label_type, - amount: value.amount, - } - } -} - -impl From<ApplepaySessionTokenResponse> for payments::ApplePaySessionResponse { - fn from(value: ApplepaySessionTokenResponse) -> Self { - Self { - epoch_timestamp: value.epoch_timestamp, - expires_at: value.expires_at, - merchant_session_identifier: value.merchant_session_identifier, - nonce: value.nonce, - merchant_identifier: value.merchant_identifier, - domain_name: value.domain_name, - display_name: value.display_name, - signature: value.signature, - operational_analytics_identifier: value.operational_analytics_identifier, - retries: value.retries, - psp_id: value.psp_id, - } - } -} diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index ff0a3c84d81..2c1a0a1c444 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -88,7 +88,6 @@ macro_rules! default_imp_for_complete_authorize{ default_imp_for_complete_authorize!( connector::Aci, connector::Adyen, - connector::Applepay, connector::Authorizedotnet, connector::Bambora, connector::Bluesnap, @@ -132,7 +131,6 @@ macro_rules! default_imp_for_connector_redirect_response{ default_imp_for_connector_redirect_response!( connector::Aci, connector::Adyen, - connector::Applepay, connector::Authorizedotnet, connector::Bambora, connector::Bluesnap, @@ -166,7 +164,6 @@ default_imp_for_connector_request_id!( connector::Aci, connector::Adyen, connector::Airwallex, - connector::Applepay, connector::Authorizedotnet, connector::Bambora, connector::Bluesnap, diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 78360ce0800..53abde90bd0 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -1,17 +1,20 @@ use api_models::payments as payment_types; use async_trait::async_trait; -use error_stack::ResultExt; +use common_utils::ext_traits::ByteSliceExt; +use error_stack::{report, ResultExt}; use super::{ConstructFlowSpecificData, Feature}; use crate::{ + connector, core::{ errors::{self, ConnectorErrorExt, RouterResult}, payments::{self, access_token, transformers, PaymentData}, }, + headers, routes::{self, metrics}, services, types::{self, api, storage}, - utils::OptionExt, + utils::{self, OptionExt}, }; #[async_trait] @@ -73,8 +76,159 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio } } +fn mk_applepay_session_request( + state: &routes::AppState, + router_data: &types::PaymentsSessionRouterData, +) -> RouterResult<(services::Request, payment_types::ApplepaySessionTokenData)> { + let connector_metadata = router_data.connector_meta_data.clone(); + + let applepay_metadata = connector_metadata + .parse_value::<payment_types::ApplepaySessionTokenData>("ApplepaySessionTokenData") + .change_context(errors::ApiErrorResponse::InvalidDataFormat { + field_name: "connector_metadata".to_string(), + expected_format: "applepay_metadata_format".to_string(), + })?; + let request = payment_types::ApplepaySessionRequest { + merchant_identifier: applepay_metadata + .data + .session_token_data + .merchant_identifier + .clone(), + display_name: applepay_metadata + .data + .session_token_data + .display_name + .clone(), + initiative: applepay_metadata.data.session_token_data.initiative.clone(), + initiative_context: applepay_metadata + .data + .session_token_data + .initiative_context + .clone(), + }; + + let applepay_session_request = + utils::Encode::<payment_types::ApplepaySessionRequest>::encode_to_string_of_json(&request) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encode ApplePay session request to a string of json")?; + + let mut url = state.conf.connectors.applepay.base_url.to_owned(); + url.push_str("paymentservices/paymentSession"); + + let session_request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(url.as_str()) + .attach_default_headers() + .headers(vec![( + headers::CONTENT_TYPE.to_string(), + "application/json".to_string(), + )]) + .body(Some(applepay_session_request)) + .add_certificate(Some( + applepay_metadata + .data + .session_token_data + .certificate + .clone(), + )) + .add_certificate_key(Some( + applepay_metadata + .data + .session_token_data + .certificate_keys + .clone(), + )) + .build(); + Ok((session_request, applepay_metadata)) +} + +async fn create_applepay_session_token( + state: &routes::AppState, + router_data: &types::PaymentsSessionRouterData, + connector: &api::ConnectorData, +) -> RouterResult<types::PaymentsSessionRouterData> { + let (applepay_session_request, applepay_metadata) = + mk_applepay_session_request(state, router_data)?; + let response = services::call_connector_api(state, applepay_session_request) + .await + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failure in calling connector api")?; + let session_response: payment_types::ApplePaySessionResponse = match response { + Ok(resp) => resp + .response + .parse_struct("ApplePaySessionResponse") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse ApplePaySessionResponse struct"), + Err(err) => { + let error_response: payment_types::ApplepayErrorResponse = err + .response + .parse_struct("ApplepayErrorResponse") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to parse ApplepayErrorResponse struct")?; + Err( + report!(errors::ApiErrorResponse::InternalServerError).attach_printable(format!( + "Failed with {} status code and the error response is {:?}", + err.status_code, error_response + )), + ) + } + }?; + + let amount_info = payment_types::AmountInfo { + label: applepay_metadata.data.payment_request_data.label, + total_type: "final".to_string(), + amount: connector::utils::to_currency_base_unit( + router_data.request.amount, + router_data.request.currency, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to convert currency to base unit")?, + }; + + let applepay_payment_request = payment_types::ApplePayPaymentRequest { + country_code: router_data + .request + .country + .to_owned() + .get_required_value("country_code") + .change_context(errors::ApiErrorResponse::MissingRequiredField { + field_name: "country_code", + })?, + currency_code: router_data.request.currency.to_string(), + total: amount_info, + merchant_capabilities: applepay_metadata + .data + .payment_request_data + .merchant_capabilities, + supported_networks: applepay_metadata + .data + .payment_request_data + .supported_networks, + merchant_identifier: applepay_metadata + .data + .session_token_data + .merchant_identifier, + }; + + let response_router_data = types::PaymentsSessionRouterData { + response: Ok(types::PaymentsResponseData::SessionResponse { + session_token: payment_types::SessionToken::ApplePay(Box::new( + payment_types::ApplepaySessionTokenResponse { + session_token_data: session_response, + payment_request_data: applepay_payment_request, + connector: connector.connector_name.to_string(), + }, + )), + }), + ..router_data.clone() + }; + + Ok(response_router_data) +} + fn create_gpay_session_token( router_data: &types::PaymentsSessionRouterData, + connector: &api::ConnectorData, ) -> RouterResult<types::PaymentsSessionRouterData> { let connector_metadata = router_data.connector_meta_data.clone(); @@ -105,6 +259,7 @@ fn create_gpay_session_token( merchant_info: gpay_data.data.merchant_info, allowed_payment_methods: gpay_data.data.allowed_payment_methods, transaction_info, + connector: connector.connector_name.to_string(), }, )), }), @@ -124,7 +279,10 @@ impl types::PaymentsSessionRouterData { call_connector_action: payments::CallConnectorAction, ) -> RouterResult<Self> { match connector.get_token { - api::GetToken::Metadata => create_gpay_session_token(self), + api::GetToken::GpayMetadata => create_gpay_session_token(self, connector), + api::GetToken::ApplePayMetadata => { + create_applepay_session_token(state, self, connector).await + } api::GetToken::Connector => { let connector_integration: services::BoxedConnectorIntegration< '_, diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs index 008e0efd46b..27b819ca1f8 100644 --- a/crates/router/src/core/payments/operations/payment_session.rs +++ b/crates/router/src/core/payments/operations/payment_session.rs @@ -1,4 +1,4 @@ -use std::{collections::HashSet, marker::PhantomData}; +use std::marker::PhantomData; use api_models::admin::PaymentMethodsEnabled; use async_trait::async_trait; @@ -18,7 +18,7 @@ use crate::{ pii::Secret, routes::AppState, types::{ - api::{self, enums as api_enums, PaymentIdTypeExt}, + api::{self, PaymentIdTypeExt}, storage::{self, enums as storage_enums}, transformers::ForeignInto, }, @@ -293,8 +293,6 @@ where let connectors = &state.conf.connectors; let db = &state.store; - let supported_connectors: &Vec<String> = state.conf.connectors.supported.wallets.as_ref(); - let connector_accounts = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( &merchant_account.merchant_id, @@ -304,127 +302,73 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Database error when querying for merchant connector accounts")?; - let normal_connector_names: HashSet<String> = connector_accounts - .iter() - .filter(|connector_account| { - connector_account - .payment_methods_enabled - .clone() - .unwrap_or_default() - .iter() - .any(|payment_method| { - let parsed_payment_method_result: Result< - PaymentMethodsEnabled, - error_stack::Report<errors::ParsingError>, - > = payment_method.clone().parse_value("payment_method"); - - match parsed_payment_method_result { - Ok(parsed_payment_method) => parsed_payment_method - .payment_method_types - .map(|payment_method_types| { - payment_method_types.iter().any(|payment_method_type| { - matches!( - payment_method_type.payment_experience, - Some(api_models::enums::PaymentExperience::InvokeSdkClient) - ) - }) - }) - .unwrap_or(false), - Err(parsing_error) => { - logger::debug!(session_token_parsing_error=?parsing_error); - false - } - } - }) - }) - .map(|filtered_connector| filtered_connector.connector_name.clone()) - .collect(); - - // Parse the payment methods enabled to check if the merchant has enabled googlepay ( wallet ) using that connector. - // A single connector can support creating session token from metadata as well as by calling the connector. - let session_token_from_metadata_connectors = connector_accounts - .iter() - .filter(|connector_account| { - connector_account - .payment_methods_enabled - .clone() - .unwrap_or_default() - .iter() - .any(|payment_method| { - let parsed_payment_method_result: Result< - PaymentMethodsEnabled, - error_stack::Report<errors::ParsingError>, - > = payment_method.clone().parse_value("payment_method"); - - match parsed_payment_method_result { - Ok(parsed_payment_method) => parsed_payment_method - .payment_method_types - .map(|payment_method_types| { - payment_method_types.iter().any(|payment_method_type| { - matches!( - payment_method_type.payment_method_type, - api_models::enums::PaymentMethodType::GooglePay - ) - }) - }) - .unwrap_or(false), - Err(parsing_error) => { - logger::debug!(session_token_parsing_error=?parsing_error); - false + let mut connector_and_supporting_payment_method_type = Vec::new(); + + for connector_account in connector_accounts { + let payment_methods = connector_account + .payment_methods_enabled + .unwrap_or_default(); + for payment_method in payment_methods { + let parsed_payment_method_result: Result< + PaymentMethodsEnabled, + error_stack::Report<errors::ParsingError>, + > = payment_method.clone().parse_value("payment_method"); + + match parsed_payment_method_result { + Ok(parsed_payment_method) => { + let payment_method_types = parsed_payment_method + .payment_method_types + .unwrap_or_default(); + for payment_method_type in payment_method_types { + if matches!( + payment_method_type.payment_experience, + Some(api_models::enums::PaymentExperience::InvokeSdkClient) + ) { + let connector_and_wallet = ( + connector_account.connector_name.to_owned(), + payment_method_type.payment_method_type, + ); + connector_and_supporting_payment_method_type + .push(connector_and_wallet); } } - }) - }) - .map(|filtered_connector| filtered_connector.connector_name.clone()) - .collect::<HashSet<String>>(); - - let given_wallets = request.wallets.clone(); - - let connectors_data = if !given_wallets.is_empty() { - // Create connectors for provided wallets - let mut connectors_data = Vec::with_capacity(supported_connectors.len()); - for wallet in given_wallets { - let (connector_name, connector_type) = match wallet { - api_enums::SupportedWallets::Gpay => ("adyen", api::GetToken::Metadata), - api_enums::SupportedWallets::ApplePay => ("applepay", api::GetToken::Connector), - api_enums::SupportedWallets::Paypal => ("braintree", api::GetToken::Connector), - api_enums::SupportedWallets::Klarna => ("klarna", api::GetToken::Connector), - }; - - // Check if merchant has enabled the required merchant connector account - if session_token_from_metadata_connectors.contains(connector_name) - || normal_connector_names.contains(connector_name) + } + Err(parsing_error) => { + logger::debug!(session_token_parsing_error=?parsing_error); + } + } + } + } + + let requested_payment_method_types = request.wallets.clone(); + + let connectors_data = if !requested_payment_method_types.is_empty() { + let mut connectors_data = Vec::new(); + for payment_method_type in requested_payment_method_types { + for connector_and_payment_method_type in + &connector_and_supporting_payment_method_type { - connectors_data.push(api::ConnectorData::get_connector_by_name( - connectors, - connector_name, - connector_type, - )?); + if connector_and_payment_method_type.1 == payment_method_type { + let connector_details = api::ConnectorData::get_connector_by_name( + connectors, + connector_and_payment_method_type.0.as_str(), + api::GetToken::from(connector_and_payment_method_type.1), + )?; + connectors_data.push(connector_details); + } } } connectors_data } else { - // Create connectors for all enabled wallets - let mut connectors_data = Vec::with_capacity( - normal_connector_names.len() + session_token_from_metadata_connectors.len(), - ); - - for connector_name in normal_connector_names { - let connector_data = api::ConnectorData::get_connector_by_name( - connectors, - &connector_name, - api::GetToken::Connector, - )?; - connectors_data.push(connector_data); - } + let mut connectors_data = Vec::new(); - for connector_name in session_token_from_metadata_connectors { - let connector_data = api::ConnectorData::get_connector_by_name( + for connector_and_payment_method_type in connector_and_supporting_payment_method_type { + let connector_details = api::ConnectorData::get_connector_by_name( connectors, - &connector_name, - api::GetToken::Metadata, + connector_and_payment_method_type.0.as_str(), + api::GetToken::from(connector_and_payment_method_type.1), )?; - connectors_data.push(connector_data); + connectors_data.push(connector_details); } connectors_data }; @@ -432,3 +376,13 @@ where Ok(api::ConnectorChoice::SessionMultiple(connectors_data)) } } + +impl From<api_models::enums::PaymentMethodType> for api::GetToken { + fn from(value: api_models::enums::PaymentMethodType) -> Self { + match value { + api_models::enums::PaymentMethodType::GooglePay => Self::GpayMetadata, + api_models::enums::PaymentMethodType::ApplePay => Self::ApplePayMetadata, + _ => Self::Connector, + } + } +} diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs index ec506f3f10f..d16e2ef5972 100644 --- a/crates/router/src/openapi.rs +++ b/crates/router/src/openapi.rs @@ -140,7 +140,6 @@ Never share your secret api keys. Keep them guarded and secure. api_models::enums::AuthenticationType, api_models::enums::Connector, api_models::enums::PaymentMethod, - api_models::enums::SupportedWallets, api_models::enums::PaymentMethodIssuerCode, api_models::enums::MandateStatus, api_models::enums::PaymentExperience, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index ca8b5940c83..84304d6f1c6 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -131,9 +131,10 @@ 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 ) -#[derive(Clone)] +#[derive(Clone, Eq, PartialEq)] pub enum GetToken { - Metadata, + GpayMetadata, + ApplePayMetadata, Connector, } @@ -189,7 +190,6 @@ impl ConnectorData { "aci" => Ok(Box::new(&connector::Aci)), "adyen" => Ok(Box::new(&connector::Adyen)), "airwallex" => Ok(Box::new(&connector::Airwallex)), - "applepay" => Ok(Box::new(&connector::Applepay)), "authorizedotnet" => Ok(Box::new(&connector::Authorizedotnet)), "bambora" => Ok(Box::new(&connector::Bambora)), "bluesnap" => Ok(Box::new(&connector::Bluesnap)),
feat
support gpay and applepay session response for all connectors (#839)
53e82c3faef3ee629a38180e3882a2920332a9a8
2024-10-15 18:29:16
Swangi Kumari
feat(core): add payments post_session_tokens flow (#6202)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index 7e9cc57bf6a..9ecfe9cf644 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -10217,6 +10217,7 @@ "NextActionCall": { "type": "string", "enum": [ + "post_session_tokens", "confirm", "sync", "complete_authorize" @@ -19327,6 +19328,10 @@ "properties": { "next_action": { "$ref": "#/components/schemas/NextActionCall" + }, + "order_id": { + "type": "string", + "nullable": true } } }, diff --git a/api-reference/api-reference/payments/payments--post-session-tokens.mdx b/api-reference/api-reference/payments/payments--post-session-tokens.mdx new file mode 100644 index 00000000000..6c327886c52 --- /dev/null +++ b/api-reference/api-reference/payments/payments--post-session-tokens.mdx @@ -0,0 +1,3 @@ +--- +openapi: post /payments/{payment_id}/post_session_tokens +--- \ No newline at end of file diff --git a/api-reference/mint.json b/api-reference/mint.json index 03a76fed183..264f5366836 100644 --- a/api-reference/mint.json +++ b/api-reference/mint.json @@ -52,7 +52,8 @@ "api-reference/payments/payments-link--retrieve", "api-reference/payments/payments--list", "api-reference/payments/payments--external-3ds-authentication", - "api-reference/payments/payments--complete-authorize" + "api-reference/payments/payments--complete-authorize", + "api-reference/payments/post-session-tokens" ] }, { diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index d01a51f6d5b..49fe3b6b95d 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -912,6 +912,46 @@ ] } }, + "/payments/{payment_id}/post_session_tokens": { + "post": { + "tags": [ + "Payments" + ], + "summary": "Payments - Post Session Tokens", + "description": "\n", + "operationId": "Create Post Session Tokens for a Payment", + "requestBody": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsPostSessionTokensRequest" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "Post Session Token is done", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PaymentsPostSessionTokensResponse" + } + } + } + }, + "400": { + "description": "Missing mandatory fields" + } + }, + "security": [ + { + "publishable_key": [] + } + ] + } + }, "/refunds": { "post": { "tags": [ @@ -13811,6 +13851,7 @@ "NextActionCall": { "type": "string", "enum": [ + "post_session_tokens", "confirm", "sync", "complete_authorize" @@ -17928,6 +17969,55 @@ } } }, + "PaymentsPostSessionTokensRequest": { + "type": "object", + "required": [ + "client_secret", + "payment_method_type", + "payment_method" + ], + "properties": { + "client_secret": { + "type": "string", + "description": "It's a token used for client side verification." + }, + "payment_method_type": { + "$ref": "#/components/schemas/PaymentMethodType" + }, + "payment_method": { + "$ref": "#/components/schemas/PaymentMethod" + } + } + }, + "PaymentsPostSessionTokensResponse": { + "type": "object", + "required": [ + "payment_id", + "status" + ], + "properties": { + "payment_id": { + "type": "string", + "description": "The identifier for the payment" + }, + "next_action": { + "allOf": [ + { + "$ref": "#/components/schemas/NextActionData" + } + ], + "nullable": true + }, + "status": { + "allOf": [ + { + "$ref": "#/components/schemas/IntentStatus" + } + ], + "default": "requires_confirmation" + } + } + }, "PaymentsRequest": { "type": "object", "properties": { @@ -23039,6 +23129,10 @@ "properties": { "next_action": { "$ref": "#/components/schemas/NextActionCall" + }, + "order_id": { + "type": "string", + "nullable": true } } }, diff --git a/crates/api_models/src/events/payment.rs b/crates/api_models/src/events/payment.rs index aa8cd43ca97..1f66fb521e4 100644 --- a/crates/api_models/src/events/payment.rs +++ b/crates/api_models/src/events/payment.rs @@ -23,7 +23,8 @@ use crate::{ PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse, PaymentsExternalAuthenticationRequest, PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest, - PaymentsManualUpdateRequest, PaymentsManualUpdateResponse, PaymentsRejectRequest, + PaymentsManualUpdateRequest, PaymentsManualUpdateResponse, + PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse, PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsRetrieveRequest, PaymentsSessionResponse, PaymentsStartRequest, RedirectionResponse, }, @@ -71,6 +72,22 @@ impl ApiEventMetric for PaymentsDynamicTaxCalculationRequest { } } +impl ApiEventMetric for PaymentsPostSessionTokensRequest { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Payment { + payment_id: self.payment_id.clone(), + }) + } +} + +impl ApiEventMetric for PaymentsPostSessionTokensResponse { + fn get_api_event_type(&self) -> Option<ApiEventsType> { + Some(ApiEventsType::Payment { + payment_id: self.payment_id.clone(), + }) + } +} + impl ApiEventMetric for PaymentsDynamicTaxCalculationResponse {} impl ApiEventMetric for PaymentsCancelRequest { diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 87152c5c170..265865b973a 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -3819,6 +3819,7 @@ pub enum QrCodeInformation { #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, + pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] @@ -4873,6 +4874,34 @@ pub struct PaymentsSessionRequest { pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } +#[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] +pub struct PaymentsPostSessionTokensRequest { + /// The unique identifier for the payment + #[serde(skip_deserializing)] + #[schema(value_type = String)] + pub payment_id: id_type::PaymentId, + /// It's a token used for client side verification. + #[schema(value_type = String)] + pub client_secret: Secret<String>, + /// Payment method type + #[schema(value_type = PaymentMethodType)] + pub payment_method_type: api_enums::PaymentMethodType, + /// The payment method that is to be used for the payment + #[schema(value_type = PaymentMethod, example = "card")] + pub payment_method: api_enums::PaymentMethod, +} + +#[derive(Debug, serde::Serialize, Clone, ToSchema)] +pub struct PaymentsPostSessionTokensResponse { + /// The identifier for the payment + #[schema(value_type = String)] + pub payment_id: id_type::PaymentId, + /// Additional information required for redirection + pub next_action: Option<NextActionData>, + #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] + pub status: api_enums::IntentStatus, +} + #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment @@ -5429,6 +5458,8 @@ pub struct SdkNextAction { #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { + /// The next action call is Post Session Tokens + PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 061f00f8295..20551c2754b 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -475,6 +475,10 @@ pub enum PaymentAttemptUpdate { unified_message: Option<String>, connector_transaction_id: Option<String>, }, + PostSessionTokensUpdate { + updated_by: String, + connector_metadata: Option<serde_json::Value>, + }, } #[cfg(feature = "v2")] @@ -3065,6 +3069,60 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal { shipping_cost: None, order_tax_amount: None, }, + PaymentAttemptUpdate::PostSessionTokensUpdate { + updated_by, + connector_metadata, + } => Self { + status: None, + error_code: None, + modified_at: common_utils::date_time::now(), + error_message: None, + error_reason: None, + updated_by, + unified_code: None, + unified_message: None, + amount: None, + net_amount: None, + currency: None, + connector_transaction_id: None, + amount_to_capture: None, + connector: None, + authentication_type: None, + payment_method: None, + payment_method_id: None, + cancellation_reason: None, + mandate_id: None, + browser_info: None, + payment_token: None, + connector_metadata, + payment_method_data: None, + payment_method_type: None, + payment_experience: None, + business_sub_label: None, + straight_through_algorithm: None, + preprocessing_step_id: None, + capture_method: None, + connector_response_reference_id: None, + multiple_capture_count: None, + surcharge_amount: None, + tax_amount: None, + amount_capturable: None, + merchant_connector_id: None, + authentication_data: None, + encoded_data: None, + external_three_ds_authentication_attempted: None, + authentication_connector: None, + authentication_id: None, + fingerprint_id: None, + payment_method_billing_address_id: None, + charge_id: None, + client_source: None, + client_version: None, + customer_acceptance: None, + card_network: None, + shipping_cost: None, + order_tax_amount: None, + }, } } } diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs index 7600b08fe1e..8a9d803a6f5 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -29,8 +29,8 @@ use hyperswitch_domain_models::{ mandate_revoke::MandateRevoke, payments::{ Approve, AuthorizeSessionToken, CalculateTax, CompleteAuthorize, - CreateConnectorCustomer, IncrementalAuthorization, PostProcessing, PreProcessing, - Reject, SdkSessionUpdate, + CreateConnectorCustomer, IncrementalAuthorization, PostProcessing, PostSessionTokens, + PreProcessing, Reject, SdkSessionUpdate, }, webhooks::VerifyWebhookSource, }, @@ -38,9 +38,9 @@ use hyperswitch_domain_models::{ AcceptDisputeRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, DefendDisputeRequestData, MandateRevokeRequestData, PaymentsApproveData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, - PaymentsPreProcessingData, PaymentsRejectData, PaymentsTaxCalculationData, - RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SubmitEvidenceRequestData, - UploadFileRequestData, VerifyWebhookSourceRequestData, + PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, + PaymentsTaxCalculationData, RetrieveFileRequestData, SdkPaymentsSessionUpdateData, + SubmitEvidenceRequestData, UploadFileRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ AcceptDisputeResponse, DefendDisputeResponse, MandateRevokeResponseData, @@ -65,9 +65,9 @@ use hyperswitch_interfaces::{ files::{FileUpload, RetrieveFile, UploadFile}, payments::{ ConnectorCustomer, PaymentApprove, PaymentAuthorizeSessionToken, - PaymentIncrementalAuthorization, PaymentReject, PaymentSessionUpdate, - PaymentsCompleteAuthorize, PaymentsPostProcessing, PaymentsPreProcessing, - TaxCalculation, + PaymentIncrementalAuthorization, PaymentPostSessionTokens, PaymentReject, + PaymentSessionUpdate, PaymentsCompleteAuthorize, PaymentsPostProcessing, + PaymentsPreProcessing, TaxCalculation, }, ConnectorIntegration, ConnectorMandateRevoke, ConnectorRedirectResponse, }, @@ -195,6 +195,47 @@ default_imp_for_session_update!( connectors::Volt ); +macro_rules! default_imp_for_post_session_tokens { + ($($path:ident::$connector:ident),*) => { + $( impl PaymentPostSessionTokens for $path::$connector {} + impl + ConnectorIntegration< + PostSessionTokens, + PaymentsPostSessionTokensData, + PaymentsResponseData, + > for $path::$connector + {} + )* + }; +} + +default_imp_for_post_session_tokens!( + connectors::Bambora, + connectors::Bitpay, + connectors::Cashtocode, + connectors::Coinbase, + connectors::Cryptopay, + connectors::Digitalvirgo, + connectors::Dlocal, + connectors::Square, + connectors::Fiserv, + connectors::Fiservemea, + connectors::Helcim, + connectors::Stax, + connectors::Taxjar, + connectors::Mollie, + connectors::Novalnet, + connectors::Nexixpay, + connectors::Fiuu, + connectors::Globepay, + connectors::Worldline, + connectors::Powertranz, + connectors::Thunes, + connectors::Tsys, + connectors::Deutschebank, + connectors::Volt +); + use crate::connectors; macro_rules! default_imp_for_complete_authorize { ($($path:ident::$connector:ident),*) => { diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index c1170709c02..1c81db29d3f 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -14,7 +14,8 @@ use hyperswitch_domain_models::{ payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken, - PostProcessing, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, Void, + PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, + SetupMandate, Void, }, refunds::{Execute, RSync}, webhooks::VerifyWebhookSource, @@ -26,10 +27,10 @@ use hyperswitch_domain_models::{ MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, - PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, - PaymentsTaxCalculationData, RefundsData, RetrieveFileRequestData, - SdkPaymentsSessionUpdateData, SetupMandateRequestData, SubmitEvidenceRequestData, - UploadFileRequestData, VerifyWebhookSourceRequestData, + PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, + PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData, + RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, + SubmitEvidenceRequestData, UploadFileRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ AcceptDisputeResponse, DefendDisputeResponse, MandateRevokeResponseData, @@ -74,8 +75,8 @@ use hyperswitch_interfaces::{ payments_v2::{ ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2, - PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2, - PaymentTokenV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2, + PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, + PaymentSyncV2, PaymentTokenV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2, }, refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2}, @@ -107,6 +108,7 @@ macro_rules! default_imp_for_new_connector_integration_payment { impl PaymentsPostProcessingV2 for $path::$connector{} impl TaxCalculationV2 for $path::$connector{} impl PaymentSessionUpdateV2 for $path::$connector{} + impl PaymentPostSessionTokensV2 for $path::$connector{} impl ConnectorIntegrationV2<Authorize,PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData> for $path::$connector{} @@ -191,6 +193,13 @@ macro_rules! default_imp_for_new_connector_integration_payment { SdkPaymentsSessionUpdateData, PaymentsResponseData, > for $path::$connector{} + impl + ConnectorIntegrationV2< + PostSessionTokens, + PaymentFlowData, + PaymentsPostSessionTokensData, + PaymentsResponseData, + > for $path::$connector{} )* }; } diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 31423c33d23..5aba0616143 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -556,6 +556,8 @@ pub struct PaymentAttemptNew { pub profile_id: id_type::ProfileId, pub organization_id: id_type::OrganizationId, pub card_network: Option<String>, + pub shipping_cost: Option<MinorUnit>, + pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v1")] @@ -809,6 +811,10 @@ pub enum PaymentAttemptUpdate { unified_message: Option<String>, connector_transaction_id: Option<String>, }, + PostSessionTokensUpdate { + updated_by: String, + connector_metadata: Option<serde_json::Value>, + }, } #[cfg(feature = "v1")] @@ -1160,6 +1166,13 @@ impl PaymentAttemptUpdate { unified_message, connector_transaction_id, }, + Self::PostSessionTokensUpdate { + updated_by, + connector_metadata, + } => DieselPaymentAttemptUpdate::PostSessionTokensUpdate { + updated_by, + connector_metadata, + }, } } } diff --git a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs index a0e6adc855a..10153fc05ec 100644 --- a/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs +++ b/crates/hyperswitch_domain_models/src/router_flow_types/payments.rs @@ -55,3 +55,6 @@ pub struct CalculateTax; #[derive(Debug, Clone)] pub struct SdkSessionUpdate; + +#[derive(Debug, Clone)] +pub struct PostSessionTokens; diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs index b67621e9f06..f03ab75af19 100644 --- a/crates/hyperswitch_domain_models/src/router_request_types.rs +++ b/crates/hyperswitch_domain_models/src/router_request_types.rs @@ -73,6 +73,17 @@ pub struct PaymentsAuthorizeData { pub integrity_object: Option<AuthoriseIntegrityObject>, } +#[derive(Debug, Clone)] +pub struct PaymentsPostSessionTokensData { + pub amount: MinorUnit, + pub currency: storage_enums::Currency, + pub capture_method: Option<storage_enums::CaptureMethod>, + /// Merchant's identifier for the payment/invoice. This will be sent to the connector + /// if the connector provides support to accept multiple reference ids. + /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. + pub merchant_order_reference_id: Option<String>, +} + #[derive(Debug, Clone, PartialEq)] pub struct AuthoriseIntegrityObject { /// Authorise amount diff --git a/crates/hyperswitch_domain_models/src/types.rs b/crates/hyperswitch_domain_models/src/types.rs index 507249e5ee2..eeb63bbb508 100644 --- a/crates/hyperswitch_domain_models/src/types.rs +++ b/crates/hyperswitch_domain_models/src/types.rs @@ -2,14 +2,15 @@ use crate::{ router_data::{AccessToken, RouterData}, router_flow_types::{ AccessTokenAuth, Authorize, AuthorizeSessionToken, CalculateTax, Capture, - CompleteAuthorize, CreateConnectorCustomer, PSync, PaymentMethodToken, PreProcessing, - RSync, SetupMandate, Void, + CompleteAuthorize, CreateConnectorCustomer, PSync, PaymentMethodToken, PostSessionTokens, + PreProcessing, RSync, SetupMandate, Void, }, router_request_types::{ AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsAuthorizeData, - PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSyncData, - PaymentsTaxCalculationData, RefundsData, SetupMandateRequestData, + PaymentsCancelData, PaymentsCaptureData, PaymentsPostSessionTokensData, + PaymentsPreProcessingData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData, + SetupMandateRequestData, }, router_response_types::{ PaymentsResponseData, RefundsResponseData, TaxCalculationResponseData, @@ -38,3 +39,5 @@ pub type PaymentsCompleteAuthorizeRouterData = pub type PaymentsTaxCalculationRouterData = RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>; pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>; +pub type PaymentsPostSessionTokensRouterData = + RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>; diff --git a/crates/hyperswitch_interfaces/src/api/payments.rs b/crates/hyperswitch_interfaces/src/api/payments.rs index 43409680dc5..b3ac7e0fa90 100644 --- a/crates/hyperswitch_interfaces/src/api/payments.rs +++ b/crates/hyperswitch_interfaces/src/api/payments.rs @@ -4,14 +4,15 @@ use hyperswitch_domain_models::{ router_flow_types::payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken, - PostProcessing, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, Void, + PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, + SetupMandate, Void, }, router_request_types::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, - PaymentsPostProcessingData, PaymentsPreProcessingData, PaymentsRejectData, - PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, + PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, + PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, }, router_response_types::{PaymentsResponseData, TaxCalculationResponseData}, @@ -39,6 +40,7 @@ pub trait Payment: + ConnectorCustomer + PaymentIncrementalAuthorization + PaymentSessionUpdate + + PaymentPostSessionTokens { } @@ -124,6 +126,12 @@ pub trait PaymentSessionUpdate: { } +/// trait PostSessionTokens +pub trait PaymentPostSessionTokens: + api::ConnectorIntegration<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData> +{ +} + /// trait PaymentsCompleteAuthorize pub trait PaymentsCompleteAuthorize: api::ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData> diff --git a/crates/hyperswitch_interfaces/src/api/payments_v2.rs b/crates/hyperswitch_interfaces/src/api/payments_v2.rs index cc5fd01f9f8..e2ddf49e0cd 100644 --- a/crates/hyperswitch_interfaces/src/api/payments_v2.rs +++ b/crates/hyperswitch_interfaces/src/api/payments_v2.rs @@ -5,14 +5,15 @@ use hyperswitch_domain_models::{ router_flow_types::payments::{ Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken, - PostProcessing, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, Void, + PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, + SetupMandate, Void, }, router_request_types::{ AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, - PaymentsPostProcessingData, PaymentsPreProcessingData, PaymentsRejectData, - PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, + PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, + PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, }, router_response_types::{PaymentsResponseData, TaxCalculationResponseData}, @@ -112,6 +113,17 @@ pub trait PaymentSessionUpdateV2: { } +///trait PaymentPostSessionTokensV2 +pub trait PaymentPostSessionTokensV2: + ConnectorIntegrationV2< + PostSessionTokens, + PaymentFlowData, + PaymentsPostSessionTokensData, + PaymentsResponseData, +> +{ +} + /// trait PaymentsCompleteAuthorizeV2 pub trait PaymentsCompleteAuthorizeV2: ConnectorIntegrationV2< @@ -188,5 +200,6 @@ pub trait PaymentV2: + PaymentIncrementalAuthorizationV2 + TaxCalculationV2 + PaymentSessionUpdateV2 + + PaymentPostSessionTokensV2 { } diff --git a/crates/hyperswitch_interfaces/src/types.rs b/crates/hyperswitch_interfaces/src/types.rs index e42942a94de..81e2086f972 100644 --- a/crates/hyperswitch_interfaces/src/types.rs +++ b/crates/hyperswitch_interfaces/src/types.rs @@ -9,7 +9,8 @@ use hyperswitch_domain_models::{ payments::{ Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, - PaymentMethodToken, PostProcessing, PreProcessing, Session, SetupMandate, Void, + PaymentMethodToken, PostProcessing, PostSessionTokens, PreProcessing, Session, + SetupMandate, Void, }, refunds::{Execute, RSync}, webhooks::VerifyWebhookSource, @@ -19,10 +20,10 @@ use hyperswitch_domain_models::{ CompleteAuthorizeData, ConnectorCustomerData, DefendDisputeRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, - PaymentsPostProcessingData, PaymentsPreProcessingData, PaymentsSessionData, - PaymentsSyncData, PaymentsTaxCalculationData, RefundsData, RetrieveFileRequestData, - SetupMandateRequestData, SubmitEvidenceRequestData, UploadFileRequestData, - VerifyWebhookSourceRequestData, + PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData, + PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData, + RetrieveFileRequestData, SetupMandateRequestData, SubmitEvidenceRequestData, + UploadFileRequestData, VerifyWebhookSourceRequestData, }, router_response_types::{ AcceptDisputeResponse, DefendDisputeResponse, MandateRevokeResponseData, @@ -58,6 +59,12 @@ pub type PaymentsAuthorizeType = /// Type alias for `ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>` pub type PaymentsTaxCalculationType = dyn ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>; +/// Type alias for `ConnectorIntegration<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>` +pub type PaymentsPostSessionTokensType = dyn ConnectorIntegration< + PostSessionTokens, + PaymentsPostSessionTokensData, + PaymentsResponseData, +>; /// Type alias for `ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>` pub type SetupMandateType = dyn ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>; diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs index c28eb291592..28a7f44c7a8 100644 --- a/crates/openapi/src/openapi.rs +++ b/crates/openapi/src/openapi.rs @@ -82,6 +82,7 @@ Never share your secret api keys. Keep them guarded and secure. routes::payment_link::payment_link_retrieve, routes::payments::payments_external_authentication, routes::payments::payments_complete_authorize, + routes::payments::payments_post_session_tokens, // Routes for refunds routes::refunds::refunds_create, @@ -646,6 +647,8 @@ Never share your secret api keys. Keep them guarded and secure. api_models::payments::WalletResponseData, api_models::payments::PaymentsDynamicTaxCalculationResponse, api_models::payments::DisplayAmountOnSdk, + api_models::payments::PaymentsPostSessionTokensRequest, + api_models::payments::PaymentsPostSessionTokensResponse, )), modifiers(&SecurityAddon) )] diff --git a/crates/openapi/src/routes/payments.rs b/crates/openapi/src/routes/payments.rs index aa82dafbe47..b6a81efda09 100644 --- a/crates/openapi/src/routes/payments.rs +++ b/crates/openapi/src/routes/payments.rs @@ -583,6 +583,24 @@ pub fn payments_complete_authorize() {} pub fn payments_dynamic_tax_calculation() {} +/// Payments - Post Session Tokens +/// +/// +#[utoipa::path( + post, + path = "/payments/{payment_id}/post_session_tokens", + request_body=PaymentsPostSessionTokensRequest, + responses( + (status = 200, description = "Post Session Token is done", body = PaymentsPostSessionTokensResponse), + (status = 400, description = "Missing mandatory fields") + ), + tag = "Payments", + operation_id = "Create Post Session Tokens for a Payment", + security(("publishable_key" = [])) +)] + +pub fn payments_post_session_tokens() {} + /// Payments - Create Intent /// /// **Creates a payment intent object when amount_details are passed.** diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs index 67cf28e1a6a..e94ad375776 100644 --- a/crates/router/src/configs/defaults.rs +++ b/crates/router/src/configs/defaults.rs @@ -9239,8 +9239,79 @@ impl Default for super::settings::RequiredFields { enums::Connector::Paypal, RequiredFieldFinal { mandate: HashMap::new(), - non_mandate: HashMap::new(), - common: HashMap::new(), + non_mandate: HashMap::new( + ), + common: HashMap::from( + [ + ( + "shipping.address.first_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.first_name".to_string(), + display_name: "shipping_first_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.last_name".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.last_name".to_string(), + display_name: "shipping_last_name".to_string(), + field_type: enums::FieldType::UserShippingName, + value: None, + } + ), + ( + "shipping.address.city".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.city".to_string(), + display_name: "city".to_string(), + field_type: enums::FieldType::UserShippingAddressCity, + value: None, + } + ), + ( + "shipping.address.state".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.state".to_string(), + display_name: "state".to_string(), + field_type: enums::FieldType::UserShippingAddressState, + value: None, + } + ), + ( + "shipping.address.zip".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.zip".to_string(), + display_name: "zip".to_string(), + field_type: enums::FieldType::UserShippingAddressPincode, + value: None, + } + ), + ( + "shipping.address.country".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.country".to_string(), + display_name: "country".to_string(), + field_type: enums::FieldType::UserShippingAddressCountry{ + options: vec![ + "ALL".to_string(), + ] + }, + value: None, + } + ), + ( + "shipping.address.line1".to_string(), + RequiredFieldInfo { + required_field: "shipping.address.line1".to_string(), + display_name: "line1".to_string(), + field_type: enums::FieldType::UserShippingAddressLine1, + value: None, + } + ), + ] + ), } ), ]), diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index 5ea880c16b9..254278944e7 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -15,18 +15,20 @@ use router_env::{instrument, tracing}; use transformers as paypal; use self::transformers::{auth_headers, PaypalAuthResponse, PaypalMeta, PaypalWebhookEventType}; -use super::utils::{ConnectorErrorType, PaymentsCompleteAuthorizeRequestData}; +use super::utils::{ + ConnectorErrorType, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, +}; use crate::{ configs::settings, - connector::{ - utils as connector_utils, - utils::{to_connector_meta, ConnectorErrorTypeMapping, RefundsRequestData}, + connector::utils::{ + self as connector_utils, to_connector_meta, ConnectorErrorTypeMapping, RefundsRequestData, }, consts, core::{ errors::{self, CustomResult}, payments, }, + db::domain, events::connector_api_logs::ConnectorEvent, headers, services::{ @@ -71,6 +73,7 @@ impl api::Refund for Paypal {} impl api::RefundExecute for Paypal {} impl api::RefundSync for Paypal {} impl api::ConnectorVerifyWebhookSource for Paypal {} +impl api::PaymentPostSessionTokens for Paypal {} impl api::Payouts for Paypal {} #[cfg(feature = "payouts")] @@ -649,6 +652,94 @@ impl } } +impl + ConnectorIntegration< + api::PostSessionTokens, + types::PaymentsPostSessionTokensData, + types::PaymentsResponseData, + > for Paypal +{ + fn get_headers( + &self, + req: &types::PaymentsPostSessionTokensRouterData, + 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::PaymentsPostSessionTokensRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + Ok(format!("{}v2/checkout/orders", self.base_url(connectors))) + } + fn build_request( + &self, + req: &types::PaymentsPostSessionTokensRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { + Ok(Some( + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsPostSessionTokensType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsPostSessionTokensType::get_headers( + self, req, connectors, + )?) + .set_body(types::PaymentsPostSessionTokensType::get_request_body( + self, req, connectors, + )?) + .build(), + )) + } + + fn get_request_body( + &self, + req: &types::PaymentsPostSessionTokensRouterData, + _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = connector_utils::convert_amount( + self.amount_converter, + req.request.amount, + req.request.currency, + )?; + let connector_router_data = paypal::PaypalRouterData::try_from((amount, req))?; + let connector_req = paypal::PaypalPaymentsRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn handle_response( + &self, + data: &types::PaymentsPostSessionTokensRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsPostSessionTokensRouterData, errors::ConnectorError> { + let response: paypal::PaypalRedirectResponse = res + .response + .parse_struct("PaypalRedirectResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.get_order_error_response(res, event_builder) + } +} + impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData> for Paypal { @@ -666,10 +757,26 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_url( &self, - _req: &types::PaymentsAuthorizeRouterData, + req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!("{}v2/checkout/orders", self.base_url(connectors))) + match &req.request.payment_method_data { + domain::PaymentMethodData::Wallet(domain::WalletData::PaypalSdk( + paypal_wallet_data, + )) => { + let authorize_url = if req.request.is_auto_capture()? { + "capture".to_string() + } else { + "authorize".to_string() + }; + Ok(format!( + "{}v2/checkout/orders/{}/{authorize_url}", + self.base_url(connectors), + paypal_wallet_data.token + )) + } + _ => Ok(format!("{}v2/checkout/orders", self.base_url(connectors))), + } } fn get_request_body( @@ -692,8 +799,20 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P req: &types::PaymentsAuthorizeRouterData, connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Ok(Some( - services::RequestBuilder::new() + let payment_method_data = req.request.payment_method_data.clone(); + let req = match payment_method_data { + domain::PaymentMethodData::Wallet(domain::WalletData::PaypalSdk(_)) => { + services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsAuthorizeType::get_url( + self, req, connectors, + )?) + .headers(types::PaymentsAuthorizeType::get_headers( + self, req, connectors, + )?) + .build() + } + _ => services::RequestBuilder::new() .method(services::Method::Post) .url(&types::PaymentsAuthorizeType::get_url( self, req, connectors, @@ -705,7 +824,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P self, req, connectors, )?) .build(), - )) + }; + + Ok(Some(req)) } fn handle_response( @@ -718,7 +839,6 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P res.response .parse_struct("paypal PaypalAuthResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; - let payment_method_data = data.request.payment_method_data.clone(); match response { PaypalAuthResponse::PaypalOrdersResponse(response) => { event_builder.map(|i| i.set_response_body(&response)); @@ -733,14 +853,11 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P PaypalAuthResponse::PaypalRedirectResponse(response) => { event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); - types::RouterData::foreign_try_from(( - types::ResponseRouterData { - response, - data: data.clone(), - http_code: res.status_code, - }, - payment_method_data, - )) + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) } PaypalAuthResponse::PaypalThreeDsResponse(response) => { event_builder.map(|i| i.set_response_body(&response)); diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index b51357a42af..eafc86343b3 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -12,7 +12,7 @@ use url::Url; use crate::{ connector::utils::{ self, to_connector_meta, AccessTokenRequestInfo, AddressDetailsData, CardData, - PaymentsAuthorizeRequestData, RouterData, + PaymentsAuthorizeRequestData, PaymentsPostSessionTokensRequestData, RouterData, }, consts, core::errors, @@ -91,6 +91,21 @@ impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for OrderReque } } +impl From<&PaypalRouterData<&types::PaymentsPostSessionTokensRouterData>> for OrderRequestAmount { + fn from(item: &PaypalRouterData<&types::PaymentsPostSessionTokensRouterData>) -> Self { + Self { + currency_code: item.router_data.request.currency, + value: item.amount.clone(), + breakdown: AmountBreakdown { + item_total: OrderAmount { + currency_code: item.router_data.request.currency, + value: item.amount.clone(), + }, + }, + } + } +} + #[derive(Default, Debug, Serialize, Deserialize, Eq, PartialEq)] pub struct AmountBreakdown { item_total: OrderAmount, @@ -136,6 +151,22 @@ impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for ItemDetail } } +impl From<&PaypalRouterData<&types::PaymentsPostSessionTokensRouterData>> for ItemDetails { + fn from(item: &PaypalRouterData<&types::PaymentsPostSessionTokensRouterData>) -> Self { + Self { + name: format!( + "Payment for invoice {}", + item.router_data.connector_request_reference_id + ), + quantity: 1, + unit_amount: OrderAmount { + currency_code: item.router_data.request.currency, + value: item.amount.clone(), + }, + } + } +} + #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct Address { address_line_1: Option<Secret<String>>, @@ -165,6 +196,21 @@ impl From<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for ShippingAd } } +impl From<&PaypalRouterData<&types::PaymentsPostSessionTokensRouterData>> for ShippingAddress { + fn from(item: &PaypalRouterData<&types::PaymentsPostSessionTokensRouterData>) -> Self { + Self { + address: get_address_info(item.router_data.get_optional_shipping()), + name: Some(ShippingName { + full_name: item + .router_data + .get_optional_shipping() + .and_then(|inner_data| inner_data.address.as_ref()) + .and_then(|inner_data| inner_data.first_name.clone()), + }), + } + } +} + #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct ShippingName { full_name: Option<Secret<String>>, @@ -366,6 +412,55 @@ fn get_payee(auth_type: &PaypalAuthType) -> Option<Payee> { }) } +impl TryFrom<&PaypalRouterData<&types::PaymentsPostSessionTokensRouterData>> + for PaypalPaymentsRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PaypalRouterData<&types::PaymentsPostSessionTokensRouterData>, + ) -> Result<Self, Self::Error> { + let intent = if item.router_data.request.is_auto_capture()? { + PaypalPaymentIntent::Capture + } else { + PaypalPaymentIntent::Authorize + }; + let paypal_auth: PaypalAuthType = + PaypalAuthType::try_from(&item.router_data.connector_auth_type)?; + let payee = get_payee(&paypal_auth); + + let amount = OrderRequestAmount::from(item); + let connector_request_reference_id = + item.router_data.connector_request_reference_id.clone(); + + let shipping_address = ShippingAddress::from(item); + let item_details = vec![ItemDetails::from(item)]; + + let purchase_units = vec![PurchaseUnitRequest { + reference_id: Some(connector_request_reference_id.clone()), + custom_id: item.router_data.request.merchant_order_reference_id.clone(), + invoice_id: Some(connector_request_reference_id), + amount, + payee, + shipping: Some(shipping_address), + items: item_details, + }]; + let payment_source = Some(PaymentSourceItem::Paypal(PaypalRedirectionRequest { + experience_context: ContextStruct { + return_url: None, + cancel_url: None, + shipping_preference: ShippingPreference::GetFromFile, + user_action: Some(UserAction::PayNow), + }, + })); + + Ok(Self { + intent, + purchase_units, + payment_source, + }) + } +} + impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalPaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( @@ -1040,6 +1135,7 @@ pub struct PaypalMeta { pub capture_id: Option<String>, pub psync_flow: PaypalPaymentIntent, pub next_action: Option<api_models::payments::NextActionCall>, + pub order_id: Option<String>, } fn get_id_based_on_intent( @@ -1094,6 +1190,7 @@ impl<F, T> capture_id: Some(id), psync_flow: item.response.intent.clone(), next_action: None, + order_id: None, }), types::ResponseId::ConnectorTransactionId(item.response.id.clone()), ), @@ -1104,6 +1201,7 @@ impl<F, T> capture_id: None, psync_flow: item.response.intent.clone(), next_action: None, + order_id: None, }), types::ResponseId::ConnectorTransactionId(item.response.id.clone()), ), @@ -1252,6 +1350,7 @@ impl<F, T> capture_id: None, psync_flow: item.response.intent, next_action, + order_id: None, }); let purchase_units = item.response.purchase_units.first(); Ok(Self { @@ -1276,18 +1375,24 @@ impl<F, T> } } -impl<F, T> - ForeignTryFrom<( - types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>, - domain::PaymentMethodData, - )> for types::RouterData<F, T, types::PaymentsResponseData> +impl + TryFrom< + types::ResponseRouterData< + api::Authorize, + PaypalRedirectResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + > for types::PaymentsAuthorizeRouterData { type Error = error_stack::Report<errors::ConnectorError>; - fn foreign_try_from( - (item, payment_method_data): ( - types::ResponseRouterData<F, PaypalRedirectResponse, T, types::PaymentsResponseData>, - domain::PaymentMethodData, - ), + fn try_from( + item: types::ResponseRouterData< + api::Authorize, + PaypalRedirectResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, ) -> Result<Self, Self::Error> { let status = storage_enums::AttemptStatus::foreign_from(( item.response.clone().status, @@ -1295,21 +1400,12 @@ impl<F, T> )); let link = get_redirect_url(item.response.links.clone())?; - // For Paypal SDK flow, we need to trigger SDK client and then complete authorize - let next_action = - if let domain::PaymentMethodData::Wallet(domain::WalletData::PaypalSdk(_)) = - payment_method_data - { - Some(api_models::payments::NextActionCall::CompleteAuthorize) - } else { - None - }; - let connector_meta = serde_json::json!(PaypalMeta { authorize_id: None, capture_id: None, psync_flow: item.response.intent, - next_action, + next_action: None, + order_id: None, }); let purchase_units = item.response.purchase_units.first(); Ok(Self { @@ -1334,6 +1430,59 @@ impl<F, T> } } +impl + TryFrom< + types::ResponseRouterData< + api::PostSessionTokens, + PaypalRedirectResponse, + types::PaymentsPostSessionTokensData, + types::PaymentsResponseData, + >, + > for types::PaymentsPostSessionTokensRouterData +{ + type Error = error_stack::Report<errors::ConnectorError>; + + fn try_from( + item: types::ResponseRouterData< + api::PostSessionTokens, + PaypalRedirectResponse, + types::PaymentsPostSessionTokensData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let status = storage_enums::AttemptStatus::foreign_from(( + item.response.clone().status, + item.response.intent.clone(), + )); + + // For Paypal SDK flow, we need to trigger SDK client and then Confirm + let next_action = Some(api_models::payments::NextActionCall::Confirm); + + let connector_meta = serde_json::json!(PaypalMeta { + authorize_id: None, + capture_id: None, + psync_flow: item.response.intent, + next_action, + order_id: Some(item.response.id.clone()), + }); + + Ok(Self { + status, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data: None, + mandate_reference: None, + connector_metadata: Some(connector_meta), + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + charge_id: None, + }), + ..item.data + }) + } +} + impl<F> TryFrom< types::ResponseRouterData< @@ -1396,6 +1545,7 @@ impl<F> capture_id: None, psync_flow: PaypalPaymentIntent::Authenticate, // when there is no capture or auth id present next_action: None, + order_id: None, }); let status = storage_enums::AttemptStatus::foreign_from(( @@ -1818,6 +1968,7 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaypalCaptureResponse>> capture_id: Some(item.response.id.clone()), psync_flow: PaypalPaymentIntent::Capture, next_action: None, + order_id: None, })), network_txn_id: None, connector_response_reference_id: item diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index ea19acb76da..34397b5db6d 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -1121,6 +1121,20 @@ impl PaymentsSyncRequestData for types::PaymentsSyncData { } } +pub trait PaymentsPostSessionTokensRequestData { + fn is_auto_capture(&self) -> Result<bool, Error>; +} + +impl PaymentsPostSessionTokensRequestData for types::PaymentsPostSessionTokensData { + fn is_auto_capture(&self) -> Result<bool, Error> { + match self.capture_method { + Some(enums::CaptureMethod::Automatic) | None => Ok(true), + Some(enums::CaptureMethod::Manual) => Ok(false), + Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), + } + } +} + #[cfg(feature = "payouts")] pub trait CustomerDetails { fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError>; diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index f148bcdfbfa..aa38b142b7c 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -56,8 +56,8 @@ use time; #[cfg(feature = "v1")] pub use self::operations::{ PaymentApprove, PaymentCancel, PaymentCapture, PaymentConfirm, PaymentCreate, - PaymentIncrementalAuthorization, PaymentReject, PaymentSession, PaymentSessionUpdate, - PaymentStatus, PaymentUpdate, + PaymentIncrementalAuthorization, PaymentPostSessionTokens, PaymentReject, PaymentSession, + PaymentSessionUpdate, PaymentStatus, PaymentUpdate, }; use self::{ conditional_configs::perform_decision_management, @@ -3637,6 +3637,7 @@ where "PaymentReject" => true, "PaymentSession" => true, "PaymentSessionUpdate" => true, + "PaymentPostSessionTokens" => true, "PaymentIncrementalAuthorization" => matches!( payment_data.get_payment_intent().status, storage_enums::IntentStatus::RequiresCapture 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 e61d7badb6d..3ca620e9e81 100644 --- a/crates/router/src/core/payments/connector_integration_v2_impls.rs +++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs @@ -46,6 +46,8 @@ mod dummy_connector_default_impl { impl<const T: u8> api::PaymentSessionUpdateV2 for connector::DummyConnector<T> {} + impl<const T: u8> api::PaymentPostSessionTokensV2 for connector::DummyConnector<T> {} + impl<const T: u8> services::ConnectorIntegrationV2< api::Authorize, @@ -203,6 +205,15 @@ mod dummy_connector_default_impl { > for connector::DummyConnector<T> { } + impl<const T: u8> + services::ConnectorIntegrationV2< + api::PostSessionTokens, + types::PaymentFlowData, + types::PaymentsPostSessionTokensData, + types::PaymentsResponseData, + > for connector::DummyConnector<T> + { + } impl<const T: u8> services::ConnectorIntegrationV2< @@ -581,6 +592,7 @@ macro_rules! default_imp_for_new_connector_integration_payment { impl api::PaymentsPostProcessingV2 for $path::$connector{} impl api::TaxCalculationV2 for $path::$connector{} impl api::PaymentSessionUpdateV2 for $path::$connector{} + impl api::PaymentPostSessionTokensV2 for $path::$connector{} impl services::ConnectorIntegrationV2<api::Authorize,types::PaymentFlowData, types::PaymentsAuthorizeData, types::PaymentsResponseData> for $path::$connector{} @@ -666,6 +678,13 @@ macro_rules! default_imp_for_new_connector_integration_payment { types::SdkPaymentsSessionUpdateData, types::PaymentsResponseData, > for $path::$connector{} + + impl services::ConnectorIntegrationV2< + api::PostSessionTokens, + types::PaymentFlowData, + types::PaymentsPostSessionTokensData, + types::PaymentsResponseData, + > for $path::$connector{} )* }; } diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 1b340682c29..c888dc74ce0 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -4,6 +4,7 @@ pub mod cancel_flow; pub mod capture_flow; pub mod complete_authorize_flow; pub mod incremental_authorization_flow; +pub mod post_session_tokens_flow; pub mod psync_flow; pub mod reject_flow; pub mod session_flow; @@ -3060,3 +3061,84 @@ default_imp_for_session_update!( connector::Zen, connector::Zsl ); + +macro_rules! default_imp_for_post_session_tokens { + ($($path:ident::$connector:ident),*) => { + $( impl api::PaymentPostSessionTokens for $path::$connector {} + impl + services::ConnectorIntegration< + api::PostSessionTokens, + types::PaymentsPostSessionTokensData, + types::PaymentsResponseData + > for $path::$connector + {} + )* + }; +} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> api::PaymentPostSessionTokens for connector::DummyConnector<T> {} +#[cfg(feature = "dummy_connector")] +impl<const T: u8> + services::ConnectorIntegration< + api::PostSessionTokens, + types::PaymentsPostSessionTokensData, + types::PaymentsResponseData, + > for connector::DummyConnector<T> +{ +} + +default_imp_for_post_session_tokens!( + connector::Aci, + connector::Adyen, + connector::Adyenplatform, + connector::Airwallex, + connector::Authorizedotnet, + connector::Bamboraapac, + connector::Bankofamerica, + connector::Billwerk, + connector::Bluesnap, + connector::Boku, + connector::Braintree, + connector::Checkout, + connector::Cybersource, + connector::Datatrans, + connector::Ebanx, + connector::Forte, + connector::Globalpay, + connector::Gocardless, + connector::Gpayments, + connector::Iatapay, + connector::Itaubank, + connector::Klarna, + connector::Mifinity, + connector::Multisafepay, + connector::Netcetera, + connector::Nexinets, + connector::Nuvei, + connector::Nmi, + connector::Noon, + connector::Opayo, + connector::Opennode, + connector::Paybox, + connector::Payeezy, + connector::Payme, + connector::Payone, + connector::Payu, + connector::Placetopay, + connector::Plaid, + connector::Prophetpay, + connector::Rapyd, + connector::Razorpay, + connector::Riskified, + connector::Signifyd, + connector::Stripe, + connector::Shift4, + connector::Threedsecureio, + connector::Trustpay, + connector::Wellsfargo, + connector::Wellsfargopayout, + connector::Wise, + connector::Worldpay, + connector::Zen, + connector::Zsl +); diff --git a/crates/router/src/core/payments/flows/post_session_tokens_flow.rs b/crates/router/src/core/payments/flows/post_session_tokens_flow.rs new file mode 100644 index 00000000000..fe83090d795 --- /dev/null +++ b/crates/router/src/core/payments/flows/post_session_tokens_flow.rs @@ -0,0 +1,131 @@ +use async_trait::async_trait; + +use super::ConstructFlowSpecificData; +use crate::{ + core::{ + errors::{ConnectorErrorExt, RouterResult}, + payments::{self, access_token, helpers, transformers, Feature, PaymentData}, + }, + routes::SessionState, + services, + types::{self, api, domain}, +}; + +#[async_trait] +impl + ConstructFlowSpecificData< + api::PostSessionTokens, + types::PaymentsPostSessionTokensData, + types::PaymentsResponseData, + > for PaymentData<api::PostSessionTokens> +{ + async fn construct_router_data<'a>( + &self, + state: &SessionState, + connector_id: &str, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + customer: &Option<domain::Customer>, + merchant_connector_account: &helpers::MerchantConnectorAccountType, + merchant_recipient_data: Option<types::MerchantRecipientData>, + header_payload: Option<api_models::payments::HeaderPayload>, + ) -> RouterResult<types::PaymentsPostSessionTokensRouterData> { + Box::pin(transformers::construct_payment_router_data::< + api::PostSessionTokens, + types::PaymentsPostSessionTokensData, + >( + state, + self.clone(), + connector_id, + merchant_account, + key_store, + customer, + merchant_connector_account, + merchant_recipient_data, + header_payload, + )) + .await + } + + async fn get_merchant_recipient_data<'a>( + &self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _merchant_connector_account: &helpers::MerchantConnectorAccountType, + _connector: &api::ConnectorData, + ) -> RouterResult<Option<types::MerchantRecipientData>> { + Ok(None) + } +} + +#[async_trait] +impl Feature<api::PostSessionTokens, types::PaymentsPostSessionTokensData> + for types::RouterData< + api::PostSessionTokens, + types::PaymentsPostSessionTokensData, + types::PaymentsResponseData, + > +{ + async fn decide_flows<'a>( + self, + state: &SessionState, + connector: &api::ConnectorData, + call_connector_action: payments::CallConnectorAction, + connector_request: Option<services::Request>, + _business_profile: &domain::Profile, + _header_payload: api_models::payments::HeaderPayload, + ) -> RouterResult<Self> { + let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< + api::PostSessionTokens, + types::PaymentsPostSessionTokensData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + let resp = services::execute_connector_processing_step( + state, + connector_integration, + &self, + call_connector_action, + connector_request, + ) + .await + .to_payment_failed_response()?; + Ok(resp) + } + + async fn add_access_token<'a>( + &self, + state: &SessionState, + connector: &api::ConnectorData, + merchant_account: &domain::MerchantAccount, + creds_identifier: Option<&str>, + ) -> RouterResult<types::AddAccessTokenResult> { + access_token::add_access_token(state, connector, merchant_account, self, creds_identifier) + .await + } + + async fn build_flow_specific_connector_request( + &mut self, + state: &SessionState, + connector: &api::ConnectorData, + call_connector_action: payments::CallConnectorAction, + ) -> RouterResult<(Option<services::Request>, bool)> { + let request = match call_connector_action { + payments::CallConnectorAction::Trigger => { + let connector_integration: services::BoxedPaymentConnectorIntegrationInterface< + api::PostSessionTokens, + types::PaymentsPostSessionTokensData, + types::PaymentsResponseData, + > = connector.connector.get_connector_integration(); + + connector_integration + .build_request(self, &state.conf.connectors) + .to_payment_failed_response()? + } + _ => None, + }; + + Ok((request, true)) + } +} diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 053c9b8fb0a..49b89fd5623 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -957,7 +957,7 @@ fn create_paypal_sdk_session_token( connector: connector.connector_name.to_string(), session_token: paypal_sdk_data.data.client_id, sdk_next_action: payment_types::SdkNextAction { - next_action: payment_types::NextActionCall::Confirm, + next_action: payment_types::NextActionCall::PostSessionTokens, }, }, )), diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs index f91ef52fde5..efbe9bc8fcf 100644 --- a/crates/router/src/core/payments/operations.rs +++ b/crates/router/src/core/payments/operations.rs @@ -11,6 +11,8 @@ pub mod payment_confirm; #[cfg(feature = "v1")] pub mod payment_create; #[cfg(feature = "v1")] +pub mod payment_post_session_tokens; +#[cfg(feature = "v1")] pub mod payment_reject; pub mod payment_response; #[cfg(feature = "v1")] @@ -38,8 +40,9 @@ pub use self::payment_response::PaymentResponse; pub use self::{ payment_approve::PaymentApprove, payment_cancel::PaymentCancel, payment_capture::PaymentCapture, payment_confirm::PaymentConfirm, - payment_create::PaymentCreate, payment_reject::PaymentReject, payment_session::PaymentSession, - payment_start::PaymentStart, payment_status::PaymentStatus, payment_update::PaymentUpdate, + payment_create::PaymentCreate, payment_post_session_tokens::PaymentPostSessionTokens, + payment_reject::PaymentReject, payment_session::PaymentSession, payment_start::PaymentStart, + payment_status::PaymentStatus, payment_update::PaymentUpdate, payments_incremental_authorization::PaymentIncrementalAuthorization, tax_calculation::PaymentSessionUpdate, }; diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs new file mode 100644 index 00000000000..53fd32acc07 --- /dev/null +++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs @@ -0,0 +1,291 @@ +use std::marker::PhantomData; + +use api_models::enums::FrmSuggestion; +use async_trait::async_trait; +use common_utils::types::keymanager::KeyManagerState; +use error_stack::ResultExt; +use masking::PeekInterface; +use router_derive::PaymentOperation; +use router_env::{instrument, tracing}; + +use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; +use crate::{ + core::{ + errors::{self, RouterResult, StorageErrorExt}, + payments::{self, helpers, operations, PaymentData}, + }, + routes::{app::ReqState, SessionState}, + services, + types::{ + api::{self, PaymentIdTypeExt}, + domain, + storage::{self, enums as storage_enums}, + }, + utils::OptionExt, +}; + +#[derive(Debug, Clone, Copy, PaymentOperation)] +#[operation(operations = "all", flow = "post_session_tokens")] +pub struct PaymentPostSessionTokens; + +type PaymentPostSessionTokensOperation<'b, F> = + BoxedOperation<'b, F, api::PaymentsPostSessionTokensRequest, PaymentData<F>>; + +#[async_trait] +impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsPostSessionTokensRequest> + for PaymentPostSessionTokens +{ + #[instrument(skip_all)] + async fn get_trackers<'a>( + &'a self, + state: &'a SessionState, + payment_id: &api::PaymentIdType, + request: &api::PaymentsPostSessionTokensRequest, + merchant_account: &domain::MerchantAccount, + key_store: &domain::MerchantKeyStore, + _auth_flow: services::AuthFlow, + _header_payload: &api::HeaderPayload, + ) -> RouterResult< + operations::GetTrackerResponse< + 'a, + F, + api::PaymentsPostSessionTokensRequest, + PaymentData<F>, + >, + > { + let payment_id = payment_id + .get_payment_intent_id() + .change_context(errors::ApiErrorResponse::PaymentNotFound)?; + + let db = &*state.store; + let key_manager_state: &KeyManagerState = &state.into(); + let merchant_id = merchant_account.get_id(); + let storage_scheme = merchant_account.storage_scheme; + let payment_intent = db + .find_payment_intent_by_payment_id_merchant_id( + &state.into(), + &payment_id, + merchant_id, + key_store, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + + helpers::authenticate_client_secret(Some(request.client_secret.peek()), &payment_intent)?; + + let mut payment_attempt = db + .find_payment_attempt_by_payment_id_merchant_id_attempt_id( + &payment_intent.payment_id, + merchant_id, + payment_intent.active_attempt.get_id().as_str(), + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + let currency = payment_intent.currency.get_required_value("currency")?; + let amount = payment_attempt.get_total_amount().into(); + let profile_id = payment_intent + .profile_id + .as_ref() + .get_required_value("profile_id") + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("'profile_id' not set in payment intent")?; + + let business_profile = db + .find_business_profile_by_profile_id(key_manager_state, key_store, profile_id) + .await + .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { + id: profile_id.get_string_repr().to_owned(), + })?; + payment_attempt.payment_method = Some(request.payment_method); + payment_attempt.payment_method_type = Some(request.payment_method_type); + let shipping_address = helpers::get_address_by_id( + state, + payment_intent.shipping_address_id.clone(), + key_store, + &payment_intent.payment_id, + merchant_id, + merchant_account.storage_scheme, + ) + .await?; + + let billing_address = helpers::get_address_by_id( + state, + payment_intent.billing_address_id.clone(), + key_store, + &payment_intent.payment_id, + merchant_id, + merchant_account.storage_scheme, + ) + .await?; + + let payment_data = PaymentData { + flow: PhantomData, + payment_intent, + payment_attempt, + currency, + amount, + email: None, + mandate_id: None, + mandate_connector: None, + customer_acceptance: None, + token: None, + token_data: None, + setup_mandate: None, + address: payments::PaymentAddress::new( + shipping_address.as_ref().map(From::from), + billing_address.as_ref().map(From::from), + None, + business_profile.use_billing_as_payment_method_billing, + ), + confirm: None, + payment_method_data: None, + payment_method_info: None, + force_sync: None, + refunds: vec![], + disputes: vec![], + attempts: None, + sessions_token: vec![], + card_cvc: None, + creds_identifier: None, + pm_token: None, + connector_customer_id: None, + recurring_mandate_payment_data: None, + ephemeral_key: None, + multiple_capture_data: None, + redirect_response: None, + surcharge_details: None, + frm_message: None, + payment_link_data: None, + incremental_authorization_details: None, + authorizations: vec![], + authentication: None, + recurring_details: None, + poll_config: None, + tax_data: None, + }; + let get_trackers_response = operations::GetTrackerResponse { + operation: Box::new(self), + customer_details: None, + payment_data, + business_profile, + mandate_type: None, + }; + + Ok(get_trackers_response) + } +} + +#[async_trait] +impl<F: Clone + Send> Domain<F, api::PaymentsPostSessionTokensRequest, PaymentData<F>> + for PaymentPostSessionTokens +{ + #[instrument(skip_all)] + async fn get_or_create_customer_details<'a>( + &'a self, + _state: &SessionState, + _payment_data: &mut PaymentData<F>, + _request: Option<payments::CustomerDetails>, + _merchant_key_store: &domain::MerchantKeyStore, + _storage_scheme: storage_enums::MerchantStorageScheme, + ) -> errors::CustomResult< + ( + PaymentPostSessionTokensOperation<'a, F>, + Option<domain::Customer>, + ), + errors::StorageError, + > { + Ok((Box::new(self), None)) + } + + #[instrument(skip_all)] + async fn make_pm_data<'a>( + &'a self, + _state: &'a SessionState, + _payment_data: &mut PaymentData<F>, + _storage_scheme: storage_enums::MerchantStorageScheme, + _merchant_key_store: &domain::MerchantKeyStore, + _customer: &Option<domain::Customer>, + _business_profile: &domain::Profile, + ) -> RouterResult<( + PaymentPostSessionTokensOperation<'a, F>, + Option<domain::PaymentMethodData>, + Option<String>, + )> { + Ok((Box::new(self), None, None)) + } + + async fn get_connector<'a>( + &'a self, + _merchant_account: &domain::MerchantAccount, + state: &SessionState, + _request: &api::PaymentsPostSessionTokensRequest, + _payment_intent: &storage::PaymentIntent, + _merchant_key_store: &domain::MerchantKeyStore, + ) -> errors::CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { + helpers::get_connector_default(state, None).await + } + + #[instrument(skip_all)] + async fn guard_payment_against_blocklist<'a>( + &'a self, + _state: &SessionState, + _merchant_account: &domain::MerchantAccount, + _key_store: &domain::MerchantKeyStore, + _payment_data: &mut PaymentData<F>, + ) -> errors::CustomResult<bool, errors::ApiErrorResponse> { + Ok(false) + } +} + +#[async_trait] +impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsPostSessionTokensRequest> + for PaymentPostSessionTokens +{ + #[instrument(skip_all)] + async fn update_trackers<'b>( + &'b self, + _state: &'b SessionState, + _req_state: ReqState, + payment_data: PaymentData<F>, + _customer: Option<domain::Customer>, + _storage_scheme: storage_enums::MerchantStorageScheme, + _updated_customer: Option<storage::CustomerUpdate>, + _key_store: &domain::MerchantKeyStore, + _frm_suggestion: Option<FrmSuggestion>, + _header_payload: api::HeaderPayload, + ) -> RouterResult<(PaymentPostSessionTokensOperation<'b, F>, PaymentData<F>)> + where + F: 'b + Send, + { + Ok((Box::new(self), payment_data)) + } +} + +impl<F: Send + Clone> ValidateRequest<F, api::PaymentsPostSessionTokensRequest, PaymentData<F>> + for PaymentPostSessionTokens +{ + #[instrument(skip_all)] + fn validate_request<'a, 'b>( + &'b self, + request: &api::PaymentsPostSessionTokensRequest, + merchant_account: &'a domain::MerchantAccount, + ) -> RouterResult<( + PaymentPostSessionTokensOperation<'b, F>, + operations::ValidateResult, + )> { + //payment id is already generated and should be sent in the request + let given_payment_id = request.payment_id.clone(); + + Ok(( + Box::new(self), + operations::ValidateResult { + merchant_id: merchant_account.get_id().to_owned(), + payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id), + storage_scheme: merchant_account.storage_scheme, + requeue: false, + }, + )) + } +} diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index ac400eaf57f..eedadc54132 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -50,7 +50,7 @@ use crate::{ #[derive(Debug, Clone, Copy, router_derive::PaymentOperation)] #[operation( operations = "post_update_tracker", - flow = "sync_data, cancel_data, authorize_data, capture_data, complete_authorize_data, approve_data, reject_data, setup_mandate_data, session_data,incremental_authorization_data, sdk_session_update_data" + flow = "sync_data, cancel_data, authorize_data, capture_data, complete_authorize_data, approve_data, reject_data, setup_mandate_data, session_data,incremental_authorization_data, sdk_session_update_data, post_session_tokens_data" )] pub struct PaymentResponse; @@ -626,11 +626,8 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SdkPaymentsSessionUpd _key_store: &domain::MerchantKeyStore, _storage_scheme: enums::MerchantStorageScheme, _locale: &Option<String>, - #[cfg(all(feature = "v1", feature = "dynamic_routing"))] _routable_connector: Vec< - RoutableConnectorChoice, - >, - #[cfg(all(feature = "v1", feature = "dynamic_routing"))] - _business_profile: &domain::Profile, + #[cfg(feature = "dynamic_routing")] _routable_connector: Vec<RoutableConnectorChoice>, + #[cfg(feature = "dynamic_routing")] _business_profile: &domain::Profile, ) -> RouterResult<PaymentData<F>> where F: 'b + Send, @@ -687,6 +684,68 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::SdkPaymentsSessionUpd } } +#[cfg(feature = "v1")] +#[async_trait] +impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsPostSessionTokensData> + for PaymentResponse +{ + async fn update_tracker<'b>( + &'b self, + db: &'b SessionState, + _payment_id: &api::PaymentIdType, + mut payment_data: PaymentData<F>, + router_data: types::RouterData< + F, + types::PaymentsPostSessionTokensData, + types::PaymentsResponseData, + >, + _key_store: &domain::MerchantKeyStore, + storage_scheme: enums::MerchantStorageScheme, + _locale: &Option<String>, + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] _routable_connector: Vec< + RoutableConnectorChoice, + >, + #[cfg(all(feature = "v1", feature = "dynamic_routing"))] + _business_profile: &domain::Profile, + ) -> RouterResult<PaymentData<F>> + where + F: 'b + Send, + { + match router_data.response.clone() { + Ok(types::PaymentsResponseData::TransactionResponse { + connector_metadata, .. + }) => { + let m_db = db.clone().store; + let payment_attempt_update = + storage::PaymentAttemptUpdate::PostSessionTokensUpdate { + updated_by: storage_scheme.clone().to_string(), + connector_metadata, + }; + let updated_payment_attempt = m_db + .update_payment_attempt_with_attempt_id( + payment_data.payment_attempt.clone(), + payment_attempt_update, + storage_scheme, + ) + .await + .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; + payment_data.payment_attempt = updated_payment_attempt; + } + Err(err) => { + logger::error!("Invalid request sent to connector: {:?}", err); + Err(errors::ApiErrorResponse::InvalidRequestData { + message: "Invalid request sent to connector".to_string(), + })?; + } + _ => { + Err(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Unexpected response in PostSessionTokens flow")?; + } + } + Ok(payment_data) + } +} + #[cfg(feature = "v1")] #[async_trait] impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCaptureData> diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs index 0d8322854f0..5d253f44dd4 100644 --- a/crates/router/src/core/payments/transformers.rs +++ b/crates/router/src/core/payments/transformers.rs @@ -516,6 +516,42 @@ where } } +#[cfg(feature = "v1")] +impl<F, Op, D> ToResponse<F, D, Op> for api::PaymentsPostSessionTokensResponse +where + F: Clone, + Op: Debug, + D: OperationSessionGetters<F>, +{ + fn generate_response( + payment_data: D, + _customer: Option<domain::Customer>, + _auth_flow: services::AuthFlow, + _base_url: &str, + _operation: Op, + _connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig, + _connector_http_status_code: Option<u16>, + _external_latency: Option<u128>, + _is_latency_header_enabled: Option<bool>, + ) -> RouterResponse<Self> { + let papal_sdk_next_action = + paypal_sdk_next_steps_check(payment_data.get_payment_attempt().clone())?; + let next_action = papal_sdk_next_action.map(|paypal_next_action_data| { + api_models::payments::NextActionData::InvokeSdkClient { + next_action_data: paypal_next_action_data, + } + }); + Ok(services::ApplicationResponse::JsonWithHeaders(( + Self { + payment_id: payment_data.get_payment_intent().payment_id.clone(), + next_action, + status: payment_data.get_payment_intent().status, + }, + vec![], + ))) + } +} + impl ForeignTryFrom<(MinorUnit, Option<MinorUnit>, Option<MinorUnit>, Currency)> for api_models::payments::DisplayAmountOnSdk { @@ -2078,6 +2114,45 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::SdkPaymentsSessi } } +#[cfg(feature = "v2")] +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPostSessionTokensData { + type Error = error_stack::Report<errors::ApiErrorResponse>; + + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { + todo!() + } +} + +#[cfg(feature = "v1")] +impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsPostSessionTokensData { + type Error = error_stack::Report<errors::ApiErrorResponse>; + + fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> { + let payment_data = additional_data.payment_data.clone(); + let surcharge_amount = payment_data + .surcharge_details + .as_ref() + .map(|surcharge_details| surcharge_details.get_total_surcharge_amount()) + .unwrap_or_default(); + let shipping_cost = payment_data + .payment_intent + .shipping_cost + .unwrap_or_default(); + // amount here would include amount, surcharge_amount and shipping_cost + let amount = payment_data.payment_intent.amount + shipping_cost + surcharge_amount; + let merchant_order_reference_id = payment_data + .payment_intent + .merchant_order_reference_id + .clone(); + Ok(Self { + amount, //need to change after we move to connector module + currency: payment_data.currency, + merchant_order_reference_id, + capture_method: payment_data.payment_attempt.capture_method, + }) + } +} + impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsRejectData { type Error = error_stack::Report<errors::ApiErrorResponse>; diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index c267b113fcd..823cb25b004 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -582,6 +582,9 @@ impl Payments { .route(web::get().to(payments_retrieve)) .route(web::post().to(payments_update)), ) + .service( + web::resource("/{payment_id}/post_session_tokens").route(web::post().to(payments_post_session_tokens)), + ) .service( web::resource("/{payment_id}/confirm").route(web::post().to(payments_confirm)), ) diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs index 18211b7fbb0..d47ee3caec5 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::GetExtendedCardInfo | Flow::PaymentsCompleteAuthorize | Flow::PaymentsManualUpdate - | Flow::SessionUpdateTaxCalculation => Self::Payments, + | Flow::SessionUpdateTaxCalculation + | Flow::PaymentsPostSessionTokens => Self::Payments, Flow::PayoutsCreate | Flow::PayoutsRetrieve diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index 3972adeb116..7410c5ee363 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -356,6 +356,64 @@ pub async fn payments_update( .await } +#[cfg(feature = "v1")] +#[instrument(skip_all, fields(flow = ?Flow::PaymentsPostSessionTokens, payment_id))] +pub async fn payments_post_session_tokens( + state: web::Data<app::AppState>, + req: actix_web::HttpRequest, + json_payload: web::Json<payment_types::PaymentsPostSessionTokensRequest>, + path: web::Path<common_utils::id_type::PaymentId>, +) -> impl Responder { + let flow = Flow::PaymentsPostSessionTokens; + + let payment_id = path.into_inner(); + let payload = payment_types::PaymentsPostSessionTokensRequest { + payment_id, + ..json_payload.into_inner() + }; + tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr()); + let header_payload = match HeaderPayload::foreign_try_from(req.headers()) { + Ok(headers) => headers, + Err(err) => { + return api::log_and_return_error_response(err); + } + }; + + let locking_action = payload.get_locking_input(flow.clone()); + + Box::pin(api::server_wrap( + flow, + state, + &req, + payload, + |state, auth, req, req_state| { + payments::payments_core::< + api_types::PostSessionTokens, + payment_types::PaymentsPostSessionTokensResponse, + _, + _, + _, + payments::PaymentData<api_types::PostSessionTokens>, + >( + state, + req_state, + auth.merchant_account, + auth.profile_id, + auth.key_store, + payments::PaymentPostSessionTokens, + req, + api::AuthFlow::Client, + payments::CallConnectorAction::Trigger, + None, + header_payload.clone(), + ) + }, + &auth::PublishableKeyAuth, + locking_action, + )) + .await +} + #[cfg(feature = "v1")] #[instrument(skip_all, fields(flow = ?Flow::PaymentsConfirm, payment_id))] pub async fn payments_confirm( @@ -1653,6 +1711,23 @@ impl GetLockingInput for payment_types::PaymentsDynamicTaxCalculationRequest { } } +#[cfg(feature = "v1")] +impl GetLockingInput for payment_types::PaymentsPostSessionTokensRequest { + fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction + where + F: types::FlowMetric, + lock_utils::ApiIdentifier: From<F>, + { + api_locking::LockAction::Hold { + input: api_locking::LockingInput { + unique_locking_key: self.payment_id.get_string_repr().to_owned(), + api_identifier: lock_utils::ApiIdentifier::from(flow), + override_lock_retries: None, + }, + } + } +} + #[cfg(feature = "v1")] impl GetLockingInput for payments::PaymentsRedirectResponseData { fn get_locking_input<F>(&self, flow: F) -> api_locking::LockAction diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index b53a5826379..1c0463da934 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -1249,6 +1249,12 @@ impl Authenticate for api_models::payments::PaymentsDynamicTaxCalculationRequest } } +impl Authenticate for api_models::payments::PaymentsPostSessionTokensRequest { + fn get_client_secret(&self) -> Option<&String> { + Some(self.client_secret.peek()) + } +} + impl Authenticate for api_models::payments::PaymentsRetrieveRequest {} impl Authenticate for api_models::payments::PaymentsCancelRequest {} impl Authenticate for api_models::payments::PaymentsCaptureRequest {} diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs index 225d6a783fc..3731d8ee081 100644 --- a/crates/router/src/services/authentication.rs +++ b/crates/router/src/services/authentication.rs @@ -1803,6 +1803,12 @@ impl ClientSecretFetch for PaymentMethodListRequest { } } +impl ClientSecretFetch for payments::PaymentsPostSessionTokensRequest { + fn get_client_secret(&self) -> Option<&String> { + Some(self.client_secret.peek()) + } +} + #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 11f63d6c021..6f0448ef777 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -33,7 +33,8 @@ use hyperswitch_domain_models::router_flow_types::{ payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, - PostProcessing, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, Void, + PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, + SetupMandate, Void, }, refunds::{Execute, RSync}, webhooks::VerifyWebhookSource, @@ -58,10 +59,11 @@ pub use hyperswitch_domain_models::{ MultipleCaptureRequestData, PaymentMethodTokenizationData, PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData, PaymentsPostProcessingData, - PaymentsPreProcessingData, PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, - PaymentsTaxCalculationData, RefundsData, ResponseId, RetrieveFileRequestData, - SdkPaymentsSessionUpdateData, SetupMandateRequestData, SubmitEvidenceRequestData, - SyncRequestType, UploadFileRequestData, VerifyWebhookSourceRequestData, + PaymentsPostSessionTokensData, PaymentsPreProcessingData, PaymentsRejectData, + PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData, RefundsData, ResponseId, + RetrieveFileRequestData, SdkPaymentsSessionUpdateData, SetupMandateRequestData, + SubmitEvidenceRequestData, SyncRequestType, UploadFileRequestData, + VerifyWebhookSourceRequestData, }, router_response_types::{ AcceptDisputeResponse, CaptureSyncResponse, DefendDisputeResponse, MandateReference, @@ -80,10 +82,10 @@ pub use hyperswitch_interfaces::types::{ AcceptDisputeType, ConnectorCustomerType, DefendDisputeType, IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthorizeType, PaymentsBalanceType, PaymentsCaptureType, PaymentsCompleteAuthorizeType, PaymentsInitType, PaymentsPostProcessingType, - PaymentsPreAuthorizeType, PaymentsPreProcessingType, PaymentsSessionType, PaymentsSyncType, - PaymentsVoidType, RefreshTokenType, RefundExecuteType, RefundSyncType, Response, - RetrieveFileType, SetupMandateType, SubmitEvidenceType, TokenizationType, UploadFileType, - VerifyWebhookSourceType, + PaymentsPostSessionTokensType, PaymentsPreAuthorizeType, PaymentsPreProcessingType, + PaymentsSessionType, PaymentsSyncType, PaymentsVoidType, RefreshTokenType, RefundExecuteType, + RefundSyncType, Response, RetrieveFileType, SetupMandateType, SubmitEvidenceType, + TokenizationType, UploadFileType, VerifyWebhookSourceType, }; #[cfg(feature = "payouts")] pub use hyperswitch_interfaces::types::{ @@ -134,6 +136,9 @@ pub type PaymentsTaxCalculationRouterData = pub type SdkSessionUpdateRouterData = RouterData<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>; +pub type PaymentsPostSessionTokensRouterData = + RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>; + pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>; pub type PaymentsRejectRouterData = RouterData<Reject, PaymentsRejectData, PaymentsResponseData>; pub type PaymentsApproveRouterData = RouterData<Approve, PaymentsApproveData, PaymentsResponseData>; @@ -382,6 +387,7 @@ impl Capturable for CompleteAuthorizeData { impl Capturable for SetupMandateRequestData {} impl Capturable for PaymentsTaxCalculationData {} impl Capturable for SdkPaymentsSessionUpdateData {} +impl Capturable for PaymentsPostSessionTokensData {} impl Capturable for PaymentsCancelData { fn get_captured_amount<F>(&self, payment_data: &PaymentData<F>) -> Option<i64> where diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs index 575725d4874..aedf91a3ce5 100644 --- a/crates/router/src/types/api/payments.rs +++ b/crates/router/src/types/api/payments.rs @@ -9,7 +9,8 @@ pub use api_models::payments::{ PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse, PaymentsExternalAuthenticationRequest, - PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, PaymentsRedirectRequest, + PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, + PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse, PaymentsRedirectRequest, PaymentsRedirectionResponse, PaymentsRejectRequest, PaymentsRequest, PaymentsResponse, PaymentsResponseForm, PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse, PaymentsStartRequest, PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken, @@ -19,21 +20,23 @@ use error_stack::ResultExt; pub use hyperswitch_domain_models::router_flow_types::payments::{ Approve, Authorize, AuthorizeSessionToken, Balance, CalculateTax, Capture, CompleteAuthorize, CreateConnectorCustomer, IncrementalAuthorization, InitPayment, PSync, PaymentMethodToken, - PostProcessing, PreProcessing, Reject, SdkSessionUpdate, Session, SetupMandate, Void, + PostProcessing, PostSessionTokens, PreProcessing, Reject, SdkSessionUpdate, Session, + SetupMandate, Void, }; pub use hyperswitch_interfaces::api::payments::{ ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize, - PaymentAuthorizeSessionToken, PaymentCapture, PaymentIncrementalAuthorization, PaymentReject, - PaymentSession, PaymentSessionUpdate, PaymentSync, PaymentToken, PaymentVoid, - PaymentsCompleteAuthorize, PaymentsPostProcessing, PaymentsPreProcessing, TaxCalculation, + PaymentAuthorizeSessionToken, PaymentCapture, PaymentIncrementalAuthorization, + PaymentPostSessionTokens, PaymentReject, PaymentSession, PaymentSessionUpdate, PaymentSync, + PaymentToken, PaymentVoid, PaymentsCompleteAuthorize, PaymentsPostProcessing, + PaymentsPreProcessing, TaxCalculation, }; pub use super::payments_v2::{ ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, - PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2, PaymentRejectV2, - PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentV2, - PaymentVoidV2, PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, - TaxCalculationV2, + PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2, + PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, + PaymentSyncV2, PaymentTokenV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2, + PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2, }; use crate::core::errors; diff --git a/crates/router/src/types/api/payments_v2.rs b/crates/router/src/types/api/payments_v2.rs index 59f132c0154..b28cfcf2812 100644 --- a/crates/router/src/types/api/payments_v2.rs +++ b/crates/router/src/types/api/payments_v2.rs @@ -1,7 +1,7 @@ pub use hyperswitch_interfaces::api::payments_v2::{ ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2, - PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2, PaymentRejectV2, - PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentV2, - PaymentVoidV2, PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2, - TaxCalculationV2, + PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2, + PaymentPostSessionTokensV2, PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, + PaymentSyncV2, PaymentTokenV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2, + PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2, }; diff --git a/crates/router_derive/src/macros/operation.rs b/crates/router_derive/src/macros/operation.rs index 638e6a506f2..407e910b29d 100644 --- a/crates/router_derive/src/macros/operation.rs +++ b/crates/router_derive/src/macros/operation.rs @@ -31,6 +31,8 @@ pub enum Derives { IncrementalAuthorizationData, SdkSessionUpdate, SdkSessionUpdateData, + PostSessionTokens, + PostSessionTokensData, } impl Derives { @@ -113,6 +115,12 @@ impl Conversion { Derives::SdkSessionUpdateData => { syn::Ident::new("SdkPaymentsSessionUpdateData", Span::call_site()) } + Derives::PostSessionTokens => { + syn::Ident::new("PaymentsPostSessionTokensRequest", Span::call_site()) + } + Derives::PostSessionTokensData => { + syn::Ident::new("PaymentsPostSessionTokensData", Span::call_site()) + } } } @@ -434,6 +442,7 @@ pub fn operation_derive_inner(input: DeriveInput) -> syn::Result<proc_macro::Tok CompleteAuthorizeData, PaymentsIncrementalAuthorizationData, SdkPaymentsSessionUpdateData, + PaymentsPostSessionTokensData, api::{ PaymentsCaptureRequest, @@ -447,6 +456,7 @@ pub fn operation_derive_inner(input: DeriveInput) -> syn::Result<proc_macro::Tok VerifyRequest, PaymentsDynamicTaxCalculationRequest, PaymentsIncrementalAuthorizationRequest, + PaymentsPostSessionTokensRequest } }; #trait_derive diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs index 2bae094fd96..674f418785c 100644 --- a/crates/router_env/src/logger/types.rs +++ b/crates/router_env/src/logger/types.rs @@ -498,6 +498,8 @@ pub enum Flow { PaymentsManualUpdate, /// Dynamic Tax Calcultion SessionUpdateTaxCalculation, + /// Payments post session tokens flow + PaymentsPostSessionTokens, } ///
feat
add payments post_session_tokens flow (#6202)
b283b6b662c9f2eabe90473434369d8f7c2369a6
2023-12-08 17:36:17
Shanks
fix(router): allow zero amount for payment intent in list payment methods (#3090)
false
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 84aef952a53..aaecd86627c 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2237,7 +2237,7 @@ fn filter_amount_based(payment_method: &RequestPaymentMethodTypes, amount: Optio // (Some(amt), Some(max_amt)) => amt <= max_amt, // (_, _) => true, // }; - min_check && max_check + (min_check && max_check) || amount == Some(0) } fn filter_pm_based_on_allowed_types( @@ -2296,8 +2296,9 @@ fn filter_payment_amount_based( pm: &RequestPaymentMethodTypes, ) -> bool { let amount = payment_intent.amount; - pm.maximum_amount.map_or(true, |amt| amount < amt.into()) - && pm.minimum_amount.map_or(true, |amt| amount > amt.into()) + (pm.maximum_amount.map_or(true, |amt| amount <= amt.into()) + && pm.minimum_amount.map_or(true, |amt| amount >= amt.into())) + || payment_intent.amount == 0 } async fn filter_payment_mandate_based(
fix
allow zero amount for payment intent in list payment methods (#3090)
49d22981026e0bc5105aca842a3be6533bbbd477
2024-03-01 09:26:41
Chethan Rao
fix(mandates): remove validation for `mandate_data` object in payments create request (#3860)
false
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 2eaa11f44ee..f4db64dcfb5 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -8,7 +8,7 @@ use data_models::{ payments::payment_attempt::PaymentAttempt, }; use diesel_models::ephemeral_key; -use error_stack::{self, report, ResultExt}; +use error_stack::{self, ResultExt}; use masking::PeekInterface; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; @@ -628,17 +628,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_payment_method_fields_present(request)?; - if request.mandate_data.is_none() - && request - .setup_future_usage - .map(|fut_usage| fut_usage == enums::FutureUsage::OffSession) - .unwrap_or(false) - { - Err(report!(errors::ApiErrorResponse::PreconditionFailed { - message: "`setup_future_usage` cannot be `off_session` for normal payments".into() - }))? - } - let mandate_type = helpers::validate_mandate(request, payments::is_operation_confirm(self))?; diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index 071d919eb19..494db2b8529 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -683,17 +683,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen helpers::validate_payment_method_fields_present(request)?; - if request.mandate_data.is_none() - && request - .setup_future_usage - .map(|fut_usage| fut_usage == storage_enums::FutureUsage::OffSession) - .unwrap_or(false) - { - Err(report!(errors::ApiErrorResponse::PreconditionFailed { - message: "`setup_future_usage` cannot be `off_session` for normal payments".into() - }))? - } - let mandate_type = helpers::validate_mandate(request, false)?; Ok((
fix
remove validation for `mandate_data` object in payments create request (#3860)
72955ecc68280773b9c77b4db3d46de95a62f9ed
2023-12-08 19:46:16
DEEPANSHU BANSAL
fix(connector): [CYBERSOURCE] Remove Phone Number Field From Address (#3095)
false
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index d3f542d2013..a4cea13e218 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize}; use crate::{ connector::utils::{ self, AddressDetailsData, PaymentsAuthorizeRequestData, PaymentsSetupMandateRequestData, - PhoneDetailsData, RouterData, + RouterData, }, consts, core::errors, @@ -60,10 +60,8 @@ pub struct CybersourceZeroMandateRequest { impl TryFrom<&types::SetupMandateRouterData> for CybersourceZeroMandateRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> { - let phone = item.get_billing_phone()?; - let number_with_code = phone.get_number_with_country_code()?; let email = item.request.get_email()?; - let bill_to = build_bill_to(item.get_billing()?, email, number_with_code)?; + let bill_to = build_bill_to(item.get_billing()?, email)?; let order_information = OrderInformationWithBill { amount_details: Amount { @@ -276,14 +274,12 @@ pub struct BillTo { postal_code: Secret<String>, country: api_enums::CountryAlpha2, email: pii::Email, - phone_number: Secret<String>, } // for cybersource each item in Billing is mandatory fn build_bill_to( address_details: &payments::Address, email: pii::Email, - phone_number: Secret<String>, ) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> { let address = address_details .address @@ -298,7 +294,6 @@ fn build_bill_to( postal_code: address.get_zip()?.to_owned(), country: address.get_country()?.to_owned(), email, - phone_number, }) } @@ -309,10 +304,8 @@ impl TryFrom<&CybersourceRouterData<&types::PaymentsAuthorizeRouterData>> fn try_from( item: &CybersourceRouterData<&types::PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { - let phone = item.router_data.get_billing_phone()?; - let number_with_code = phone.get_number_with_country_code()?; let email = item.router_data.request.get_email()?; - let bill_to = build_bill_to(item.router_data.get_billing()?, email, number_with_code)?; + let bill_to = build_bill_to(item.router_data.get_billing()?, email)?; let order_information = OrderInformationWithBill { amount_details: Amount {
fix
[CYBERSOURCE] Remove Phone Number Field From Address (#3095)
ba624d049840f65fc21a5e578f8d4ba8543e1420
2024-05-23 13:01:27
Amisha Prabhat
refactor(payment_methods): use recurring enabled flag to decide which payment method supports MIT (#4732)
false
diff --git a/crates/diesel_models/src/query/merchant_connector_account.rs b/crates/diesel_models/src/query/merchant_connector_account.rs index bd24d12ec22..cc73bd7a532 100644 --- a/crates/diesel_models/src/query/merchant_connector_account.rs +++ b/crates/diesel_models/src/query/merchant_connector_account.rs @@ -124,7 +124,9 @@ impl MerchantConnectorAccount { if get_disabled { generics::generic_filter::<<Self as HasTable>::Table, _, _, _>( conn, - dsl::merchant_id.eq(merchant_id.to_owned()), + dsl::merchant_id + .eq(merchant_id.to_owned()) + .and(dsl::disabled.eq(true)), None, None, Some(dsl::created_at.asc()), diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 657ad625045..28121ecc801 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -3525,7 +3525,22 @@ pub async fn list_customer_payment_method( ) .await .attach_printable("unable to decrypt payment method billing address details")?; - + let connector_mandate_details = pm + .connector_mandate_details + .clone() + .map(|val| { + val.parse_value::<storage::PaymentsMandateReference>("PaymentsMandateReference") + }) + .transpose() + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to deserialize to Payment Mandate Reference ")?; + let mca_enabled = get_mca_status( + state, + &key_store, + &merchant_account.merchant_id, + connector_mandate_details, + ) + .await?; // Need validation for enabled payment method ,querying MCA let pma = api::CustomerPaymentMethod { payment_token: parent_payment_method_token.to_owned(), @@ -3537,7 +3552,7 @@ pub async fn list_customer_payment_method( card: payment_method_retrieval_context.card_details, metadata: pm.metadata, payment_method_issuer_code: pm.payment_method_issuer_code, - recurring_enabled: false, + recurring_enabled: mca_enabled, installment_payment_enabled: false, payment_experience: Some(vec![api_models::enums::PaymentExperience::RedirectToUrl]), created: Some(pm.created_at), @@ -3667,7 +3682,38 @@ pub async fn list_customer_payment_method( Ok(services::ApplicationResponse::Json(response)) } +pub async fn get_mca_status( + state: &routes::AppState, + key_store: &domain::MerchantKeyStore, + merchant_id: &str, + connector_mandate_details: Option<storage::PaymentsMandateReference>, +) -> errors::RouterResult<bool> { + if let Some(connector_mandate_details) = connector_mandate_details { + let mcas = state + .store + .find_merchant_connector_account_by_merchant_id_and_disabled_list( + merchant_id, + true, + key_store, + ) + .await + .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { + id: merchant_id.to_string(), + })?; + let mut mca_ids = HashSet::new(); + for mca in mcas { + mca_ids.insert(mca.merchant_connector_id); + } + + for mca_id in connector_mandate_details.keys() { + if !mca_ids.contains(mca_id) { + return Ok(true); + } + } + } + Ok(false) +} pub async fn decrypt_generic_data<T>( data: Option<Encryption>, key: &[u8],
refactor
use recurring enabled flag to decide which payment method supports MIT (#4732)
036a2d5056134c067ec76dfd2afce4855303f5d7
2024-10-04 18:51:04
Suman Maji
fix: add `reference` in `sepa_bank_instructions` (#6215)
false
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json index f6f7408e3d2..f96ca1dc591 100644 --- a/api-reference-v2/openapi_spec.json +++ b/api-reference-v2/openapi_spec.json @@ -19214,7 +19214,8 @@ "account_holder_name", "bic", "country", - "iban" + "iban", + "reference" ], "properties": { "account_holder_name": { @@ -19231,6 +19232,10 @@ "iban": { "type": "string", "example": "123456789" + }, + "reference": { + "type": "string", + "example": "U2PVVSEV4V9Y" } } }, diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json index d245600b814..613eff4b2ae 100644 --- a/api-reference/openapi_spec.json +++ b/api-reference/openapi_spec.json @@ -22986,7 +22986,8 @@ "account_holder_name", "bic", "country", - "iban" + "iban", + "reference" ], "properties": { "account_holder_name": { @@ -23003,6 +23004,10 @@ "iban": { "type": "string", "example": "123456789" + }, + "reference": { + "type": "string", + "example": "U2PVVSEV4V9Y" } } }, diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index 99e2a169752..584f81992bd 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -3800,6 +3800,8 @@ pub struct SepaBankTransferInstructions { pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, + #[schema(value_type = String, example = "U2PVVSEV4V9Y")] + pub reference: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 4f76acc0028..3513dead922 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -2509,7 +2509,16 @@ pub fn get_connector_metadata( let (sepa_bank_instructions, bacs_bank_instructions) = bank_instructions.map_or((None, None), |financial_address| { ( - financial_address.iban.to_owned(), + financial_address + .iban + .to_owned() + .map(|sepa_financial_details| SepaFinancialDetails { + account_holder_name: sepa_financial_details.account_holder_name, + bic: sepa_financial_details.bic, + country: sepa_financial_details.country, + iban: sepa_financial_details.iban, + reference: response.reference.to_owned(), + }), financial_address.sort_code.to_owned(), ) }); @@ -2914,6 +2923,7 @@ pub struct SepaFinancialDetails { pub bic: Secret<String>, pub country: Secret<String>, pub iban: Secret<String>, + pub reference: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
fix
add `reference` in `sepa_bank_instructions` (#6215)
0a7625ff8c85f55a95a10415b31598fe9f16704a
2024-02-19 13:33:17
Chethan Rao
refactor: include api key expiry workflow into process tracker (#3661)
false
diff --git a/crates/diesel_models/src/api_keys.rs b/crates/diesel_models/src/api_keys.rs index 6608d4ed2fd..1875fc4dc51 100644 --- a/crates/diesel_models/src/api_keys.rs +++ b/crates/diesel_models/src/api_keys.rs @@ -138,7 +138,7 @@ mod diesel_impl { // Tracking data by process_tracker #[derive(Default, Debug, Deserialize, Serialize, Clone)] -pub struct ApiKeyExpiryWorkflow { +pub struct ApiKeyExpiryTrackingData { pub key_id: String, pub merchant_id: String, pub api_key_expiry: Option<PrimitiveDateTime>, diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index 7f724729d90..c8bdb5b63fc 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -13,7 +13,7 @@ default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "acc aws_s3 = ["external_services/aws_s3"] aws_kms = ["external_services/aws_kms"] hashicorp-vault = ["external_services/hashicorp-vault"] -email = ["external_services/email", "olap"] +email = ["external_services/email", "scheduler/email", "olap"] frm = [] stripe = ["dep:serde_qs"] release = ["aws_kms", "stripe", "aws_s3", "email", "backwards_compatibility", "business_profile_routing", "accounts_cache", "kv_store", "connector_choice_mca_id", "profile_specific_fallback_routing", "vergen", "recon"] diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs index 59a108ef5e6..caa69ea1394 100644 --- a/crates/router/src/bin/scheduler.rs +++ b/crates/router/src/bin/scheduler.rs @@ -216,6 +216,8 @@ pub enum PTRunner { PaymentsSyncWorkflow, RefundWorkflowRouter, DeleteTokenizeDataWorkflow, + #[cfg(feature = "email")] + ApiKeyExpiryWorkflow, } #[derive(Debug, Copy, Clone)] @@ -240,6 +242,10 @@ impl ProcessTrackerWorkflows<routes::AppState> for WorkflowRunner { Some(PTRunner::DeleteTokenizeDataWorkflow) => { Box::new(workflows::tokenized_data::DeleteTokenizeDataWorkflow) } + #[cfg(feature = "email")] + Some(PTRunner::ApiKeyExpiryWorkflow) => { + Box::new(workflows::api_key_expiry::ApiKeyExpiryWorkflow) + } _ => Err(ProcessTrackerError::UnexpectedFlow)?, }; let app_state = &state.clone(); diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs index b694d1291a8..39212ab3814 100644 --- a/crates/router/src/core/api_keys.rs +++ b/crates/router/src/core/api_keys.rs @@ -253,7 +253,7 @@ pub async fn add_api_key_expiry_task( } } - let api_key_expiry_tracker = &storage::ApiKeyExpiryWorkflow { + let api_key_expiry_tracker = &storage::ApiKeyExpiryTrackingData { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(), // We need API key expiry too, because we need to decide on the schedule_time in @@ -427,7 +427,7 @@ pub async fn update_api_key_expiry_task( let task_ids = vec![task_id.clone()]; - let updated_tracking_data = &storage::ApiKeyExpiryWorkflow { + let updated_tracking_data = &storage::ApiKeyExpiryTrackingData { key_id: api_key.key_id.clone(), merchant_id: api_key.merchant_id.clone(), api_key_expiry: api_key.expires_at, diff --git a/crates/router/src/services/email/assets/api_key_expiry_reminder.html b/crates/router/src/services/email/assets/api_key_expiry_reminder.html new file mode 100644 index 00000000000..1865ae38141 --- /dev/null +++ b/crates/router/src/services/email/assets/api_key_expiry_reminder.html @@ -0,0 +1,203 @@ +<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /> +<title>API Key Expiry Notice</title> +<body style="background-color: #ececec"> + <style> + .apple-footer a {{ + text-decoration: none !important; + color: #999 !important; + border: none !important; + }} + .apple-email a {{ + text-decoration: none !important; + color: #448bff !important; + border: none !important; + }} + </style> + <div + id="wrapper" + style=" + background-color: none; + margin: 0 auto; + text-align: center; + width: 60%; + -premailer-height: 200; + " + > + <table + align="center" + class="main-table" + style=" + -premailer-cellpadding: 0; + -premailer-cellspacing: 0; + background-color: #fff; + border: 0; + border-top: 5px solid #0165ef; + margin: 0 auto; + mso-table-lspace: 0; + mso-table-rspace: 0; + padding: 0 40; + text-align: center; + width: 100%; + " + bgcolor="#ffffff" + cellpadding="0" + cellspacing="0" + > + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="75" + width="100%" + ></td> + </tr> + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="25" + width="100%" + ></td> + </tr> + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="50" + width="100%" + ></td> + </tr> + <tr> + <td + class="headline" + style=" + color: #444; + font-family: Roboto, Helvetica, Arial, san-serif; + font-size: 30px; + font-weight: 100; + line-height: 36px; + margin: 0 auto; + padding: 0; + text-align: center; + " + align="center" + > + <p style="font-size: 18px">Dear Merchant,</p> + <span style="font-size: 18px"> + It has come to our attention that your API key will expire in {expires_in} days. To ensure uninterrupted + access to our platform and continued smooth operation of your services, we kindly request that you take the + necessary actions as soon as possible. + </span> + </td> + </tr> + <tr> + <td + class="spacer-sm" + style=" + -premailer-height: 20; + -premailer-width: 80%; + line-height: 10px; + margin: 0 auto; + padding: 0; + " + width="100%" + ></td> + </tr> + + <tr> + <td + class="spacer-sm" + style=" + -premailer-height: 20; + -premailer-width: 100%; + line-height: 10px; + margin: 0 auto; + padding: 0; + " + height="20" + width="100%" + ></td> + </tr> + + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="75" + width="100%" + ></td> + </tr> + <tr> + <td + class="headline" + style=" + color: #444; + font-family: Roboto, Helvetica, Arial, san-serif; + font-size: 18px; + font-weight: 100; + line-height: 36px; + margin: 0 auto; + padding: 0; + text-align: center; + " + align="center" + > + Thanks,<br /> + Team Hyperswitch + </td> + </tr> + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="75" + width="100%" + ></td> + </tr> + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="75" + width="100%" + ></td> + </tr> + </table> + </div> +</body> diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index 6ad1a0eb99a..389979d5723 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -44,6 +44,9 @@ pub enum EmailBody { user_name: String, user_email: String, }, + ApiKeyExpiryReminder { + expires_in: u8, + }, } pub mod html { @@ -113,6 +116,10 @@ Email : {user_email} (note: This is an auto generated email. Use merchant email for any further communications)", ), + EmailBody::ApiKeyExpiryReminder { expires_in } => format!( + include_str!("assets/api_key_expiry_reminder.html"), + expires_in = expires_in, + ), } } } @@ -381,3 +388,26 @@ impl EmailData for ProFeatureRequest { }) } } + +pub struct ApiKeyExpiryReminder { + pub recipient_email: domain::UserEmail, + pub subject: &'static str, + pub expires_in: u8, +} + +#[async_trait::async_trait] +impl EmailData for ApiKeyExpiryReminder { + async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + let recipient = self.recipient_email.clone().into_inner(); + + let body = html::get_html_body(EmailBody::ApiKeyExpiryReminder { + expires_in: self.expires_in, + }); + + Ok(EmailContents { + subject: self.subject.to_string(), + body: external_services::email::IntermediateString::new(body), + recipient, + }) + } +} diff --git a/crates/router/src/types/storage/api_keys.rs b/crates/router/src/types/storage/api_keys.rs index 74c503d3c76..b1051c3d19c 100644 --- a/crates/router/src/types/storage/api_keys.rs +++ b/crates/router/src/types/storage/api_keys.rs @@ -1,3 +1,3 @@ #[cfg(feature = "email")] -pub use diesel_models::api_keys::ApiKeyExpiryWorkflow; +pub use diesel_models::api_keys::ApiKeyExpiryTrackingData; pub use diesel_models::api_keys::{ApiKey, ApiKeyNew, ApiKeyUpdate, HashedApiKey}; diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs index b036193bb27..deb5bf785fa 100644 --- a/crates/router/src/workflows.rs +++ b/crates/router/src/workflows.rs @@ -1,3 +1,5 @@ +#[cfg(feature = "email")] +pub mod api_key_expiry; pub mod payment_sync; pub mod refund_router; pub mod tokenized_data; diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs index eb3c1d9c1ce..b9830c4ebc5 100644 --- a/crates/router/src/workflows/api_key_expiry.rs +++ b/crates/router/src/workflows/api_key_expiry.rs @@ -1,30 +1,35 @@ -use common_utils::ext_traits::ValueExt; -use diesel_models::enums::{self as storage_enums}; +use common_utils::{errors::ValidationError, ext_traits::ValueExt}; +use diesel_models::{enums as storage_enums, ApiKeyExpiryTrackingData}; +use router_env::logger; +use scheduler::{workflows::ProcessTrackerWorkflow, SchedulerAppState}; -use super::{ApiKeyExpiryWorkflow, ProcessTrackerWorkflow}; use crate::{ errors, logger::error, - routes::AppState, + routes::{metrics, AppState}, + services::email::types::ApiKeyExpiryReminder, types::{ api, + domain::UserEmail, storage::{self, ProcessTrackerExt}, }, utils::OptionExt, }; +pub struct ApiKeyExpiryWorkflow; + #[async_trait::async_trait] -impl ProcessTrackerWorkflow for ApiKeyExpiryWorkflow { +impl ProcessTrackerWorkflow<AppState> for ApiKeyExpiryWorkflow { async fn execute_workflow<'a>( &'a self, state: &'a AppState, process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { let db = &*state.store; - let tracking_data: storage::ApiKeyExpiryWorkflow = process + let tracking_data: ApiKeyExpiryTrackingData = process .tracking_data .clone() - .parse_value("ApiKeyExpiryWorkflow")?; + .parse_value("ApiKeyExpiryTrackingData")?; let key_store = state .store @@ -41,7 +46,13 @@ impl ProcessTrackerWorkflow for ApiKeyExpiryWorkflow { let email_id = merchant_account .merchant_details .parse_value::<api::MerchantDetails>("MerchantDetails")? - .primary_email; + .primary_email + .ok_or(errors::ProcessTrackerError::EValidationError( + ValidationError::MissingRequiredField { + field_name: "email".to_string(), + } + .into(), + ))?; let task_id = process.id.clone(); @@ -53,28 +64,26 @@ impl ProcessTrackerWorkflow for ApiKeyExpiryWorkflow { usize::try_from(retry_count) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)?, ) - .ok_or(errors::ProcessTrackerError::EApiErrorResponse( - errors::ApiErrorResponse::InvalidDataValue { - field_name: "index", - } - .into(), - ))?; + .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?; + + let email_contents = ApiKeyExpiryReminder { + recipient_email: UserEmail::from_pii_email(email_id).map_err(|err| { + logger::error!(%err,"Failed to convert recipient's email to UserEmail from pii::Email"); + errors::ProcessTrackerError::EApiErrorResponse + })?, + subject: "API Key Expiry Notice", + expires_in: *expires_in, + }; state .email_client .clone() - .send_email( - email_id.ok_or_else(|| errors::ProcessTrackerError::MissingRequiredField)?, - "API Key Expiry Notice".to_string(), - format!("Dear Merchant,\n -It has come to our attention that your API key will expire in {expires_in} days. To ensure uninterrupted access to our platform and continued smooth operation of your services, we kindly request that you take the necessary actions as soon as possible.\n\n -Thanks,\n -Team Hyperswitch"), + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), ) .await - .map_err(|_| errors::ProcessTrackerError::FlowExecutionError { - flow: "ApiKeyExpiryWorkflow", - })?; + .map_err(errors::ProcessTrackerError::EEmailError)?; // If all the mails have been sent, then retry_count would be equal to length of the expiry_reminder_days vector if retry_count @@ -82,7 +91,7 @@ Team Hyperswitch"), .map_err(|_| errors::ProcessTrackerError::TypeConversionError)? { process - .finish_with_status(db, format!("COMPLETED_BY_PT_{task_id}")) + .finish_with_status(state.get_db().as_scheduler(), "COMPLETED_BY_PT".to_string()) .await? } // If tasks are remaining that has to be scheduled @@ -93,12 +102,7 @@ Team Hyperswitch"), usize::try_from(retry_count + 1) .map_err(|_| errors::ProcessTrackerError::TypeConversionError)?, ) - .ok_or(errors::ProcessTrackerError::EApiErrorResponse( - errors::ApiErrorResponse::InvalidDataValue { - field_name: "index", - } - .into(), - ))?; + .ok_or(errors::ProcessTrackerError::EApiErrorResponse)?; let updated_schedule_time = tracking_data.api_key_expiry.map(|api_key_expiry| { api_key_expiry.saturating_sub(time::Duration::days(i64::from(*expiry_reminder_day))) diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.toml index b281bc862a2..72eaea3be06 100644 --- a/crates/scheduler/Cargo.toml +++ b/crates/scheduler/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" default = ["kv_store", "olap"] olap = ["storage_impl/olap"] kv_store = [] +email = ["external_services/email"] [dependencies] # Third party crates diff --git a/crates/scheduler/src/errors.rs b/crates/scheduler/src/errors.rs index 481fae07937..78a0bdee624 100644 --- a/crates/scheduler/src/errors.rs +++ b/crates/scheduler/src/errors.rs @@ -1,4 +1,6 @@ pub use common_utils::errors::{ParsingError, ValidationError}; +#[cfg(feature = "email")] +use external_services::email::EmailError; pub use redis_interface::errors::RedisError; pub use storage_impl::errors::ApplicationError; use storage_impl::errors::StorageError; @@ -51,6 +53,9 @@ pub enum ProcessTrackerError { EParsingError(error_stack::Report<ParsingError>), #[error("Validation Error Received: {0}")] EValidationError(error_stack::Report<ValidationError>), + #[cfg(feature = "email")] + #[error("Received Error EmailError: {0}")] + EEmailError(error_stack::Report<EmailError>), #[error("Type Conversion error")] TypeConversionError, } @@ -111,3 +116,9 @@ error_to_process_tracker_error!( error_stack::Report<ValidationError>, ProcessTrackerError::EValidationError(error_stack::Report<ValidationError>) ); + +#[cfg(feature = "email")] +error_to_process_tracker_error!( + error_stack::Report<EmailError>, + ProcessTrackerError::EEmailError(error_stack::Report<EmailError>) +);
refactor
include api key expiry workflow into process tracker (#3661)
dddb1b06bea4ac89d838641508728d2da4326ba1
2025-02-06 19:13:36
awasthi21
feat(connector): [COINGATE] Add Template PR (#7052)
false
diff --git a/config/config.example.toml b/config/config.example.toml index e982a01eb11..7bb6d8fc567 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -196,6 +196,7 @@ cashtocode.base_url = "https://cluster05.api-test.cashtocode.com" chargebee.base_url = "https://$.chargebee.com/api/" checkout.base_url = "https://api.sandbox.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" +coingate.base_url = "https://api-sandbox.coingate.com/v2" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" @@ -310,6 +311,7 @@ cards = [ "adyenplatform", "authorizedotnet", "coinbase", + "coingate", "cryptopay", "braintree", "checkout", diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml index 5791c6aa83e..4d0bce877e8 100644 --- a/config/deployments/integration_test.toml +++ b/config/deployments/integration_test.toml @@ -42,6 +42,7 @@ cashtocode.base_url = "https://cluster05.api-test.cashtocode.com" chargebee.base_url = "https://$.chargebee.com/api/" checkout.base_url = "https://api.sandbox.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" +coingate.base_url = "https://api-sandbox.coingate.com/v2" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" diff --git a/config/deployments/production.toml b/config/deployments/production.toml index 78590f05f1b..8964fbc2e20 100644 --- a/config/deployments/production.toml +++ b/config/deployments/production.toml @@ -46,6 +46,7 @@ cashtocode.base_url = "https://cluster14.api.cashtocode.com" chargebee.base_url = "https://$.chargebee.com/api/" checkout.base_url = "https://api.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" +coingate.base_url = "https://api.coingate.com/v2" cryptopay.base_url = "https://business.cryptopay.me/" cybersource.base_url = "https://api.cybersource.com/" datatrans.base_url = "https://api.datatrans.com/" diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml index 4127a694fcb..e98bd1e2fad 100644 --- a/config/deployments/sandbox.toml +++ b/config/deployments/sandbox.toml @@ -46,6 +46,7 @@ cashtocode.base_url = "https://cluster05.api-test.cashtocode.com" checkout.base_url = "https://api.sandbox.checkout.com/" chargebee.base_url = "https://$.chargebee.com/api/" coinbase.base_url = "https://api.commerce.coinbase.com" +coingate.base_url = "https://api-sandbox.coingate.com/v2" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" diff --git a/config/development.toml b/config/development.toml index 473c453d1c8..f61321fda0f 100644 --- a/config/development.toml +++ b/config/development.toml @@ -108,6 +108,7 @@ cards = [ "braintree", "checkout", "coinbase", + "coingate", "cryptopay", "cybersource", "datatrans", @@ -215,6 +216,7 @@ cashtocode.base_url = "https://cluster05.api-test.cashtocode.com" chargebee.base_url = "https://$.chargebee.com/api/" checkout.base_url = "https://api.sandbox.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" +coingate.base_url = "https://api-sandbox.coingate.com/v2" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" diff --git a/config/docker_compose.toml b/config/docker_compose.toml index 12b8df6683c..ed8f99d20df 100644 --- a/config/docker_compose.toml +++ b/config/docker_compose.toml @@ -128,6 +128,7 @@ cashtocode.base_url = "https://cluster05.api-test.cashtocode.com" chargebee.base_url = "https://$.chargebee.com/api/" checkout.base_url = "https://api.sandbox.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" +coingate.base_url = "https://api-sandbox.coingate.com/v2" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" @@ -233,6 +234,7 @@ cards = [ "braintree", "checkout", "coinbase", + "coingate", "cryptopay", "cybersource", "datatrans", diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs index 28dbf33d97d..a0e606e0741 100644 --- a/crates/common_enums/src/connector_enums.rs +++ b/crates/common_enums/src/connector_enums.rs @@ -68,6 +68,7 @@ pub enum RoutableConnectors { // Chargebee, Checkout, Coinbase, + // Coingate, Cryptopay, Cybersource, Datatrans, diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs index 15345c8221f..e9738a4907a 100644 --- a/crates/hyperswitch_connectors/src/connectors.rs +++ b/crates/hyperswitch_connectors/src/connectors.rs @@ -10,6 +10,7 @@ pub mod boku; pub mod cashtocode; pub mod chargebee; pub mod coinbase; +pub mod coingate; pub mod cryptopay; pub mod ctp_mastercard; pub mod cybersource; @@ -61,16 +62,16 @@ pub use self::{ airwallex::Airwallex, amazonpay::Amazonpay, bambora::Bambora, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica, billwerk::Billwerk, bitpay::Bitpay, bluesnap::Bluesnap, boku::Boku, cashtocode::Cashtocode, chargebee::Chargebee, coinbase::Coinbase, - cryptopay::Cryptopay, ctp_mastercard::CtpMastercard, cybersource::Cybersource, - datatrans::Datatrans, deutschebank::Deutschebank, digitalvirgo::Digitalvirgo, dlocal::Dlocal, - elavon::Elavon, fiserv::Fiserv, fiservemea::Fiservemea, fiuu::Fiuu, forte::Forte, - globepay::Globepay, gocardless::Gocardless, helcim::Helcim, inespay::Inespay, - jpmorgan::Jpmorgan, mollie::Mollie, multisafepay::Multisafepay, nexinets::Nexinets, - nexixpay::Nexixpay, nomupay::Nomupay, novalnet::Novalnet, paybox::Paybox, payeezy::Payeezy, - payu::Payu, placetopay::Placetopay, powertranz::Powertranz, prophetpay::Prophetpay, - rapyd::Rapyd, razorpay::Razorpay, redsys::Redsys, shift4::Shift4, square::Square, stax::Stax, - taxjar::Taxjar, thunes::Thunes, tsys::Tsys, - unified_authentication_service::UnifiedAuthenticationService, volt::Volt, + coingate::Coingate, cryptopay::Cryptopay, ctp_mastercard::CtpMastercard, + cybersource::Cybersource, datatrans::Datatrans, deutschebank::Deutschebank, + digitalvirgo::Digitalvirgo, dlocal::Dlocal, elavon::Elavon, fiserv::Fiserv, + fiservemea::Fiservemea, fiuu::Fiuu, forte::Forte, globepay::Globepay, gocardless::Gocardless, + helcim::Helcim, inespay::Inespay, jpmorgan::Jpmorgan, mollie::Mollie, + multisafepay::Multisafepay, nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay, + novalnet::Novalnet, paybox::Paybox, payeezy::Payeezy, payu::Payu, placetopay::Placetopay, + powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay, + redsys::Redsys, shift4::Shift4, square::Square, stax::Stax, taxjar::Taxjar, thunes::Thunes, + tsys::Tsys, unified_authentication_service::UnifiedAuthenticationService, volt::Volt, wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, zen::Zen, zsl::Zsl, }; diff --git a/crates/hyperswitch_connectors/src/connectors/coingate.rs b/crates/hyperswitch_connectors/src/connectors/coingate.rs new file mode 100644 index 00000000000..e3bece084b3 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/coingate.rs @@ -0,0 +1,571 @@ +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, ConnectorSpecifications, + ConnectorValidation, + }, + configs::Connectors, + errors, + events::connector_api_logs::ConnectorEvent, + types::{self, Response}, + webhooks, +}; +use masking::{ExposeInterface, Mask}; +use transformers as coingate; + +use crate::{constants::headers, types::ResponseRouterData, utils}; + +#[derive(Clone)] +pub struct Coingate { + amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync), +} + +impl Coingate { + pub fn new() -> &'static Self { + &Self { + amount_converter: &StringMinorUnitForConnector, + } + } +} + +impl api::Payment for Coingate {} +impl api::PaymentSession for Coingate {} +impl api::ConnectorAccessToken for Coingate {} +impl api::MandateSetup for Coingate {} +impl api::PaymentAuthorize for Coingate {} +impl api::PaymentSync for Coingate {} +impl api::PaymentCapture for Coingate {} +impl api::PaymentVoid for Coingate {} +impl api::Refund for Coingate {} +impl api::RefundExecute for Coingate {} +impl api::RefundSync for Coingate {} +impl api::PaymentToken for Coingate {} + +impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> + for Coingate +{ + // Not Implemented (R) +} + +impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Coingate +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 Coingate { + fn id(&self) -> &'static str { + "coingate" + } + + 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.coingate.base_url.as_ref() + } + + fn get_auth_header( + &self, + auth_type: &ConnectorAuthType, + ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> { + let auth = coingate::CoingateAuthType::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: coingate::CoingateErrorResponse = res + .response + .parse_struct("CoingateErrorResponse") + .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 Coingate { + //TODO: implement functions when support enabled +} + +impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Coingate { + //TODO: implement sessions flow +} + +impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Coingate {} + +impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> + for Coingate +{ +} + +impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Coingate { + 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 = coingate::CoingateRouterData::from((amount, req)); + let connector_req = coingate::CoingatePaymentsRequest::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: coingate::CoingatePaymentsResponse = res + .response + .parse_struct("Coingate 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 Coingate { + 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: coingate::CoingatePaymentsResponse = res + .response + .parse_struct("coingate 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 Coingate { + 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: coingate::CoingatePaymentsResponse = res + .response + .parse_struct("Coingate 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 Coingate {} + +impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Coingate { + 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 = coingate::CoingateRouterData::from((refund_amount, req)); + let connector_req = coingate::CoingateRefundRequest::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: coingate::RefundResponse = res + .response + .parse_struct("coingate 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 Coingate { + 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: coingate::RefundResponse = res + .response + .parse_struct("coingate 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 Coingate { + 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)) + } +} + +impl ConnectorSpecifications for Coingate {} diff --git a/crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs b/crates/hyperswitch_connectors/src/connectors/coingate/transformers.rs new file mode 100644 index 00000000000..08b9ae781e1 --- /dev/null +++ b/crates/hyperswitch_connectors/src/connectors/coingate/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 CoingateRouterData<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 CoingateRouterData<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 CoingatePaymentsRequest { + amount: StringMinorUnit, + card: CoingateCard, +} + +#[derive(Default, Debug, Serialize, Eq, PartialEq)] +pub struct CoingateCard { + number: cards::CardNumber, + expiry_month: Secret<String>, + expiry_year: Secret<String>, + cvc: Secret<String>, + complete: bool, +} + +impl TryFrom<&CoingateRouterData<&PaymentsAuthorizeRouterData>> for CoingatePaymentsRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &CoingateRouterData<&PaymentsAuthorizeRouterData>, + ) -> Result<Self, Self::Error> { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::Card(req_card) => { + let card = CoingateCard { + 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 method".to_string()).into()), + } + } +} + +//TODO: Fill the struct with respective fields +// Auth Struct +pub struct CoingateAuthType { + pub(super) api_key: Secret<String>, +} + +impl TryFrom<&ConnectorAuthType> for CoingateAuthType { + 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 CoingatePaymentStatus { + Succeeded, + Failed, + #[default] + Processing, +} + +impl From<CoingatePaymentStatus> for common_enums::AttemptStatus { + fn from(item: CoingatePaymentStatus) -> Self { + match item { + CoingatePaymentStatus::Succeeded => Self::Charged, + CoingatePaymentStatus::Failed => Self::Failure, + CoingatePaymentStatus::Processing => Self::Authorizing, + } + } +} + +//TODO: Fill the struct with respective fields +#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct CoingatePaymentsResponse { + status: CoingatePaymentStatus, + id: String, +} + +impl<F, T> TryFrom<ResponseRouterData<F, CoingatePaymentsResponse, T, PaymentsResponseData>> + for RouterData<F, T, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData<F, CoingatePaymentsResponse, 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: Box::new(None), + mandate_reference: Box::new(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 CoingateRefundRequest { + pub amount: StringMinorUnit, +} + +impl<F> TryFrom<&CoingateRouterData<&RefundsRouterData<F>>> for CoingateRefundRequest { + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from(item: &CoingateRouterData<&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 CoingateErrorResponse { + 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 f58a4802d50..cfc65de64e8 100644 --- a/crates/hyperswitch_connectors/src/default_implementations.rs +++ b/crates/hyperswitch_connectors/src/default_implementations.rs @@ -107,6 +107,7 @@ default_imp_for_authorize_session_token!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -181,6 +182,7 @@ default_imp_for_calculate_tax!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -255,6 +257,7 @@ default_imp_for_session_update!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -330,6 +333,7 @@ default_imp_for_post_session_tokens!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -404,6 +408,7 @@ default_imp_for_complete_authorize!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Datatrans, connectors::Dlocal, @@ -470,6 +475,7 @@ default_imp_for_incremental_authorization!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Datatrans, connectors::Deutschebank, @@ -544,6 +550,7 @@ default_imp_for_create_customer!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -617,6 +624,7 @@ default_imp_for_connector_redirect_response!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -685,6 +693,7 @@ default_imp_for_pre_processing_steps!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Datatrans, connectors::Deutschebank, @@ -757,6 +766,7 @@ default_imp_for_post_processing_steps!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -833,6 +843,7 @@ default_imp_for_approve!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -909,6 +920,7 @@ default_imp_for_reject!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -985,6 +997,7 @@ default_imp_for_webhook_source_verification!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -1062,6 +1075,7 @@ default_imp_for_accept_dispute!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -1138,6 +1152,7 @@ default_imp_for_submit_evidence!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -1214,6 +1229,7 @@ default_imp_for_defend_dispute!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -1299,6 +1315,7 @@ default_imp_for_file_upload!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -1370,6 +1387,7 @@ default_imp_for_payouts!( connectors::Cryptopay, connectors::Datatrans, connectors::Coinbase, + connectors::Coingate, connectors::Deutschebank, connectors::Digitalvirgo, connectors::Dlocal, @@ -1444,6 +1462,7 @@ default_imp_for_payouts_create!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -1522,6 +1541,7 @@ default_imp_for_payouts_retrieve!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -1600,6 +1620,7 @@ default_imp_for_payouts_eligibility!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -1678,6 +1699,7 @@ default_imp_for_payouts_fulfill!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Datatrans, connectors::Deutschebank, @@ -1755,6 +1777,7 @@ default_imp_for_payouts_cancel!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -1833,6 +1856,7 @@ default_imp_for_payouts_quote!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -1911,6 +1935,7 @@ default_imp_for_payouts_recipient!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -1989,6 +2014,7 @@ default_imp_for_payouts_recipient_account!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -2067,6 +2093,7 @@ default_imp_for_frm_sale!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -2145,6 +2172,7 @@ default_imp_for_frm_checkout!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -2223,6 +2251,7 @@ default_imp_for_frm_transaction!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -2301,6 +2330,7 @@ default_imp_for_frm_fulfillment!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -2379,6 +2409,7 @@ default_imp_for_frm_record_return!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Cybersource, connectors::Datatrans, @@ -2454,6 +2485,7 @@ default_imp_for_revoking_mandates!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::Datatrans, connectors::Deutschebank, @@ -2528,6 +2560,7 @@ default_imp_for_uas_pre_authentication!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -2602,6 +2635,7 @@ default_imp_for_uas_post_authentication!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -2676,6 +2710,7 @@ default_imp_for_uas_authentication!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs index 9f0b319bfa1..51607778eca 100644 --- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs +++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs @@ -217,6 +217,7 @@ default_imp_for_new_connector_integration_payment!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -294,6 +295,7 @@ default_imp_for_new_connector_integration_refund!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -366,6 +368,7 @@ default_imp_for_new_connector_integration_connector_access_token!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -444,6 +447,7 @@ default_imp_for_new_connector_integration_accept_dispute!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Datatrans, @@ -520,6 +524,7 @@ default_imp_for_new_connector_integration_submit_evidence!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Datatrans, @@ -596,6 +601,7 @@ default_imp_for_new_connector_integration_defend_dispute!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -683,6 +689,7 @@ default_imp_for_new_connector_integration_file_upload!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -762,6 +769,7 @@ default_imp_for_new_connector_integration_payouts_create!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -841,6 +849,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -920,6 +929,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -999,6 +1009,7 @@ default_imp_for_new_connector_integration_payouts_cancel!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -1078,6 +1089,7 @@ default_imp_for_new_connector_integration_payouts_quote!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -1157,6 +1169,7 @@ default_imp_for_new_connector_integration_payouts_recipient!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -1236,6 +1249,7 @@ default_imp_for_new_connector_integration_payouts_sync!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -1315,6 +1329,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -1392,6 +1407,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -1471,6 +1487,7 @@ default_imp_for_new_connector_integration_frm_sale!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -1550,6 +1567,7 @@ default_imp_for_new_connector_integration_frm_checkout!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -1629,6 +1647,7 @@ default_imp_for_new_connector_integration_frm_transaction!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -1708,6 +1727,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -1787,6 +1807,7 @@ default_imp_for_new_connector_integration_frm_record_return!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, @@ -1863,6 +1884,7 @@ default_imp_for_new_connector_integration_revoking_mandates!( connectors::Cashtocode, connectors::Chargebee, connectors::Coinbase, + connectors::Coingate, connectors::Cryptopay, connectors::CtpMastercard, connectors::Cybersource, diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs index efd41aaa4ac..c832507f92e 100644 --- a/crates/hyperswitch_interfaces/src/configs.rs +++ b/crates/hyperswitch_interfaces/src/configs.rs @@ -27,6 +27,7 @@ pub struct Connectors { pub chargebee: ConnectorParams, pub checkout: ConnectorParams, pub coinbase: ConnectorParams, + pub coingate: ConnectorParams, pub cryptopay: ConnectorParams, pub ctp_mastercard: NoParams, pub cybersource: ConnectorParams, diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs index c926401107c..a8cdf2b6cf8 100644 --- a/crates/router/src/connector.rs +++ b/crates/router/src/connector.rs @@ -37,22 +37,22 @@ pub use hyperswitch_connectors::connectors::{ bamboraapac, bamboraapac::Bamboraapac, bankofamerica, bankofamerica::Bankofamerica, billwerk, billwerk::Billwerk, bitpay, bitpay::Bitpay, bluesnap, bluesnap::Bluesnap, boku, boku::Boku, cashtocode, cashtocode::Cashtocode, chargebee::Chargebee, coinbase, coinbase::Coinbase, - cryptopay, cryptopay::Cryptopay, ctp_mastercard, ctp_mastercard::CtpMastercard, cybersource, - cybersource::Cybersource, datatrans, datatrans::Datatrans, deutschebank, - deutschebank::Deutschebank, digitalvirgo, digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, - elavon, elavon::Elavon, fiserv, fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, - fiuu::Fiuu, forte, forte::Forte, globepay, globepay::Globepay, gocardless, - gocardless::Gocardless, helcim, helcim::Helcim, inespay, inespay::Inespay, jpmorgan, - jpmorgan::Jpmorgan, mollie, mollie::Mollie, multisafepay, multisafepay::Multisafepay, nexinets, - nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nomupay, nomupay::Nomupay, novalnet, - novalnet::Novalnet, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payu, payu::Payu, - placetopay, placetopay::Placetopay, powertranz, powertranz::Powertranz, prophetpay, - prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, razorpay::Razorpay, redsys, - redsys::Redsys, shift4, shift4::Shift4, square, square::Square, stax, stax::Stax, taxjar, - taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, unified_authentication_service, - unified_authentication_service::UnifiedAuthenticationService, volt, volt::Volt, wellsfargo, - wellsfargo::Wellsfargo, worldline, worldline::Worldline, worldpay, worldpay::Worldpay, xendit, - xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, + coingate, coingate::Coingate, cryptopay, cryptopay::Cryptopay, ctp_mastercard, + ctp_mastercard::CtpMastercard, cybersource, cybersource::Cybersource, datatrans, + datatrans::Datatrans, deutschebank, deutschebank::Deutschebank, digitalvirgo, + digitalvirgo::Digitalvirgo, dlocal, dlocal::Dlocal, elavon, elavon::Elavon, fiserv, + fiserv::Fiserv, fiservemea, fiservemea::Fiservemea, fiuu, fiuu::Fiuu, forte, forte::Forte, + globepay, globepay::Globepay, gocardless, gocardless::Gocardless, helcim, helcim::Helcim, + inespay, inespay::Inespay, jpmorgan, jpmorgan::Jpmorgan, mollie, mollie::Mollie, multisafepay, + multisafepay::Multisafepay, nexinets, nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, + nomupay, nomupay::Nomupay, novalnet, novalnet::Novalnet, paybox, paybox::Paybox, payeezy, + payeezy::Payeezy, payu, payu::Payu, placetopay, placetopay::Placetopay, powertranz, + powertranz::Powertranz, prophetpay, prophetpay::Prophetpay, rapyd, rapyd::Rapyd, razorpay, + razorpay::Razorpay, redsys, redsys::Redsys, shift4, shift4::Shift4, square, square::Square, + stax, stax::Stax, taxjar, taxjar::Taxjar, thunes, thunes::Thunes, tsys, tsys::Tsys, + unified_authentication_service, unified_authentication_service::UnifiedAuthenticationService, + volt, volt::Volt, wellsfargo, wellsfargo::Wellsfargo, worldline, worldline::Worldline, + worldpay, worldpay::Worldpay, xendit, xendit::Xendit, zen, zen::Zen, zsl, zsl::Zsl, }; #[cfg(feature = "dummy_connector")] diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs index 0c80c5a70e2..852b5d95209 100644 --- a/crates/router/src/core/payments/flows.rs +++ b/crates/router/src/core/payments/flows.rs @@ -435,6 +435,7 @@ default_imp_for_connector_request_id!( connector::Chargebee, connector::Checkout, connector::Coinbase, + connector::Coingate, connector::Cryptopay, connector::Cybersource, connector::Datatrans, @@ -1528,6 +1529,7 @@ default_imp_for_fraud_check!( connector::Cryptopay, connector::Cybersource, connector::Coinbase, + connector::Coingate, connector::Datatrans, connector::Deutschebank, connector::Digitalvirgo, @@ -2117,6 +2119,7 @@ default_imp_for_connector_authentication!( connector::Checkout, connector::Cryptopay, connector::Coinbase, + connector::Coingate, connector::Cybersource, connector::Datatrans, connector::Deutschebank, diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs index 4dc5da6475f..addb34eb973 100644 --- a/crates/router/src/types/api.rs +++ b/crates/router/src/types/api.rs @@ -368,6 +368,7 @@ impl ConnectorData { enums::Connector::Coinbase => { Ok(ConnectorEnum::Old(Box::new(&connector::Coinbase))) } + // enums::Connector::Coingate => Ok(ConnectorEnum::Old(Box::new(connector::Coingate))), enums::Connector::Cryptopay => { Ok(ConnectorEnum::Old(Box::new(connector::Cryptopay::new()))) } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index c8222163b52..3e81d939c14 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -228,6 +228,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors { // api_enums::Connector::Chargebee => Self::Chargebee, api_enums::Connector::Checkout => Self::Checkout, api_enums::Connector::Coinbase => Self::Coinbase, + // api_enums::Connector::Coingate => Self::Coingate, api_enums::Connector::Cryptopay => Self::Cryptopay, api_enums::Connector::CtpMastercard => { Err(common_utils::errors::ValidationError::InvalidValue { diff --git a/crates/router/tests/connectors/coingate.rs b/crates/router/tests/connectors/coingate.rs new file mode 100644 index 00000000000..572aecb3dd7 --- /dev/null +++ b/crates/router/tests/connectors/coingate.rs @@ -0,0 +1,420 @@ +use masking::Secret; +use router::types::{self, api, storage::enums}; + +use crate::utils::{self, ConnectorActions}; +use test_utils::connector_auth; + +#[derive(Clone, Copy)] +struct CoingateTest; +impl ConnectorActions for CoingateTest {} +impl utils::Connector for CoingateTest { + fn get_data(&self) -> api::ConnectorData { + use router::connector::Coingate; + api::ConnectorData { + connector: Box::new(Coingate::new()), + connector_name: types::Connector::Coingate, + get_token: types::api::GetToken::Connector, + merchant_connector_id: None, + } + } + + fn get_auth_token(&self) -> types::ConnectorAuthType { + utils::to_connector_auth_type( + connector_auth::ConnectorAuthentication::new() + .coingate + .expect("Missing connector authentication configuration") + .into(), + ) + } + + fn get_name(&self) -> String { + "coingate".to_string() + } +} + +static CONNECTOR: CoingateTest = CoingateTest {}; + +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: 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: 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: 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/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs index 3b02661c5ce..0a3aa4bcff0 100644 --- a/crates/test_utils/src/connector_auth.rs +++ b/crates/test_utils/src/connector_auth.rs @@ -30,6 +30,7 @@ pub struct ConnectorAuthentication { pub chargebee: Option<HeaderKey>, pub checkout: Option<SignatureKey>, pub coinbase: Option<HeaderKey>, + pub coingate: Option<HeaderKey>, pub cryptopay: Option<BodyKey>, pub cybersource: Option<SignatureKey>, pub datatrans: Option<HeaderKey>, diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml index 4d9c686f23b..2fecba27bab 100644 --- a/loadtest/config/development.toml +++ b/loadtest/config/development.toml @@ -94,6 +94,7 @@ cashtocode.base_url = "https://cluster05.api-test.cashtocode.com" chargebee.base_url = "https://$.chargebee.com/api/" checkout.base_url = "https://api.sandbox.checkout.com/" coinbase.base_url = "https://api.commerce.coinbase.com" +coingate.base_url = "https://api-sandbox.coingate.com/v2" cryptopay.base_url = "https://business-sandbox.cryptopay.me" cybersource.base_url = "https://apitest.cybersource.com/" datatrans.base_url = "https://api.sandbox.datatrans.com/" @@ -199,6 +200,7 @@ cards = [ "braintree", "checkout", "coinbase", + "coingate", "cryptopay", "cybersource", "datatrans", diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index 32d24fe47eb..8dee6cd21f9 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 amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay inespay itaubank jpmorgan klarna mifinity mollie multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay redsys shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys unified_authentication_service volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") + connectors=(aci adyen adyenplatform airwallex amazonpay applepay authorizedotnet bambora bamboraapac bankofamerica billwerk bitpay bluesnap boku braintree cashtocode chargebee checkout coinbase coingate cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte globalpay globepay gocardless gpayments helcim iatapay inespay itaubank jpmorgan klarna mifinity mollie multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal payu placetopay plaid powertranz prophetpay rapyd razorpay redsys shift4 square stax stripe taxjar threedsecureio thunes trustpay tsys unified_authentication_service volt wellsfargo wellsfargopayout wise worldline worldpay xendit zsl "$1") IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS res="$(echo ${sorted[@]})" sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
feat
[COINGATE] Add Template PR (#7052)
00e913c75c14a45fdd513b233f67db7edbaf7380
2024-09-20 16:46:57
DEEPANSHU BANSAL
feat(connector): [DEUTSCHEBANK] Implement SEPA recurring payments (#5925)
false
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs index b0866cfb265..535a5abffce 100644 --- a/crates/api_models/src/payments.rs +++ b/crates/api_models/src/payments.rs @@ -1042,6 +1042,7 @@ pub struct ConnectorMandateReferenceId { pub connector_mandate_id: Option<String>, pub payment_method_id: Option<String>, pub update_history: Option<Vec<UpdateHistory>>, + pub mandate_metadata: Option<serde_json::Value>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs index 30e67babe89..a861155afb3 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank.rs @@ -50,7 +50,10 @@ use transformers as deutschebank; use crate::{ constants::headers, types::ResponseRouterData, - utils::{self, PaymentsCompleteAuthorizeRequestData, RefundsRequestData}, + utils::{ + self, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, + RefundsRequestData, + }, }; #[derive(Clone)] @@ -182,6 +185,16 @@ impl ConnectorValidation for Deutschebank { ), } } + + fn validate_mandate_payment( + &self, + pm_type: Option<enums::PaymentMethodType>, + pm_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData, + ) -> CustomResult<(), errors::ConnectorError> { + let mandate_supported_pmd = + std::collections::HashSet::from([utils::PaymentMethodDataType::SepaBankDebit]); + utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id()) + } } impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Deutschebank { @@ -302,13 +315,26 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData fn get_url( &self, - _req: &PaymentsAuthorizeRouterData, + req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { - Ok(format!( - "{}/services/v2.1/managedmandate", - self.base_url(connectors) - )) + if req.request.connector_mandate_id().is_none() { + Ok(format!( + "{}/services/v2.1/managedmandate", + self.base_url(connectors) + )) + } else { + let event_id = req.connector_request_reference_id.clone(); + let tx_action = if req.request.is_auto_capture()? { + "authorization" + } else { + "preauthorization" + }; + Ok(format!( + "{}/services/v2.1/payment/event/{event_id}/directdebit/{tx_action}", + self.base_url(connectors) + )) + } } fn get_request_body( @@ -356,17 +382,31 @@ impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> { - let response: deutschebank::DeutschebankMandatePostResponse = res - .response - .parse_struct("Deutschebank 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, - }) + if data.request.connector_mandate_id().is_none() { + let response: deutschebank::DeutschebankMandatePostResponse = res + .response + .parse_struct("DeutschebankMandatePostResponse") + .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, + }) + } else { + let response: deutschebank::DeutschebankPaymentsResponse = res + .response + .parse_struct("DeutschebankPaymentsAuthorizeResponse") + .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( diff --git a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs index dc146dc38d4..8b3837edd63 100644 --- a/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/deutschebank/transformers.rs @@ -1,7 +1,8 @@ use std::collections::HashMap; use common_enums::enums; -use common_utils::{pii::Email, types::MinorUnit}; +use common_utils::{ext_traits::ValueExt, pii::Email, types::MinorUnit}; +use error_stack::ResultExt; use hyperswitch_domain_models::{ payment_method_data::{BankDebitData, PaymentMethodData}, router_data::{AccessToken, ConnectorAuthType, RouterData}, @@ -13,7 +14,9 @@ use hyperswitch_domain_models::{ CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCaptureData, PaymentsSyncData, ResponseId, }, - router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, + router_response_types::{ + MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData, + }, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, RefundsRouterData, @@ -26,8 +29,8 @@ use serde::{Deserialize, Serialize}; use crate::{ types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData}, utils::{ - AddressDetailsData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, - RefundsRequestData, RouterData as OtherRouterData, + self, AddressDetailsData, PaymentsAuthorizeRequestData, + PaymentsCompleteAuthorizeRequestData, RefundsRequestData, RouterData as OtherRouterData, }, }; @@ -113,7 +116,7 @@ pub enum DeutschebankSEPAApproval { } #[derive(Debug, Serialize, PartialEq)] -pub struct DeutschebankPaymentsRequest { +pub struct DeutschebankMandatePostRequest { approval_by: DeutschebankSEPAApproval, email_address: Email, iban: Secret<String>, @@ -121,6 +124,13 @@ pub struct DeutschebankPaymentsRequest { last_name: Secret<String>, } +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum DeutschebankPaymentsRequest { + MandatePost(DeutschebankMandatePostRequest), + DirectDebit(DeutschebankDirectDebitRequest), +} + impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> for DeutschebankPaymentsRequest { @@ -128,16 +138,71 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsAuthorizeRouterData>> fn try_from( item: &DeutschebankRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { - let billing_address = item.router_data.get_billing_address()?; - match item.router_data.request.payment_method_data.clone() { - PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. }) => Ok(Self { - approval_by: DeutschebankSEPAApproval::Click, - email_address: item.router_data.request.get_email()?, - iban, - first_name: billing_address.get_first_name()?.clone(), - last_name: billing_address.get_last_name()?.clone(), - }), - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + match item + .router_data + .request + .mandate_id + .clone() + .and_then(|mandate_id| mandate_id.mandate_reference_id) + { + None => { + if item.router_data.request.is_mandate_payment() { + match item.router_data.request.payment_method_data.clone() { + PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { + iban, .. + }) => { + let billing_address = item.router_data.get_billing_address()?; + Ok(Self::MandatePost(DeutschebankMandatePostRequest { + approval_by: DeutschebankSEPAApproval::Click, + email_address: item.router_data.request.get_email()?, + iban, + first_name: billing_address.get_first_name()?.clone(), + last_name: billing_address.get_last_name()?.clone(), + })) + } + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("deutschebank"), + ) + .into()), + } + } else { + Err(errors::ConnectorError::MissingRequiredField { + field_name: "setup_future_usage or customer_acceptance.acceptance_type", + } + .into()) + } + } + Some(api_models::payments::MandateReferenceId::ConnectorMandateId(mandate_data)) => { + let mandate_metadata: DeutschebankMandateMetadata = mandate_data + .mandate_metadata + .ok_or(errors::ConnectorError::MissingConnectorMandateMetadata)? + .clone() + .parse_value("DeutschebankMandateMetadata") + .change_context(errors::ConnectorError::ParsingFailed)?; + Ok(Self::DirectDebit(DeutschebankDirectDebitRequest { + amount_total: DeutschebankAmount { + amount: item.amount, + currency: item.router_data.request.currency, + }, + means_of_payment: DeutschebankMeansOfPayment { + bank_account: DeutschebankBankAccount { + account_holder: mandate_metadata.account_holder, + iban: mandate_metadata.iban, + }, + }, + mandate: DeutschebankMandate { + reference: mandate_metadata.reference, + signed_on: mandate_metadata.signed_on, + }, + })) + } + Some(api_models::payments::MandateReferenceId::NetworkTokenWithNTI(_)) + | Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => { + Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("deutschebank"), + ) + .into()) + } } } } @@ -176,6 +241,14 @@ impl From<DeutschebankSEPAMandateStatus> for common_enums::AttemptStatus { } } +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] +pub struct DeutschebankMandateMetadata { + account_holder: Secret<String>, + iban: Secret<String>, + reference: Secret<String>, + signed_on: String, +} + #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DeutschebankMandatePostResponse { rc: String, @@ -207,14 +280,14 @@ impl PaymentsResponseData, >, ) -> Result<Self, Self::Error> { - let signed_on = match item.response.approval_date { + let signed_on = match item.response.approval_date.clone() { Some(date) => date.chars().take(10).collect(), None => time::OffsetDateTime::now_utc().date().to_string(), }; - match item.response.reference { + match item.response.reference.clone() { Some(reference) => Ok(Self { status: if item.response.rc == "0" { - match item.response.state { + match item.response.state.clone() { Some(state) => common_enums::AttemptStatus::from(state), None => common_enums::AttemptStatus::Failure, } @@ -227,11 +300,29 @@ impl endpoint: item.data.request.get_complete_authorize_url()?, method: common_utils::request::Method::Get, form_fields: HashMap::from([ - ("reference".to_string(), reference), - ("signed_on".to_string(), signed_on), + ("reference".to_string(), reference.clone()), + ("signed_on".to_string(), signed_on.clone()), ]), }), - mandate_reference: None, + mandate_reference: Some(MandateReference { + connector_mandate_id: item.response.mandate_id, + payment_method_id: None, + mandate_metadata: Some(serde_json::json!(DeutschebankMandateMetadata { + account_holder: item.data.get_billing_address()?.get_full_name()?, + iban: match item.data.request.payment_method_data.clone() { + PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { + iban, + .. + }) => Ok(iban), + _ => Err(errors::ConnectorError::MissingRequiredField { + field_name: + "payment_method_data.bank_debit.sepa_bank_debit.iban" + }), + }?, + reference: Secret::from(reference), + signed_on, + })), + }), connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, @@ -248,6 +339,49 @@ impl } } +impl + TryFrom< + ResponseRouterData< + Authorize, + DeutschebankPaymentsResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + > for RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: ResponseRouterData< + Authorize, + DeutschebankPaymentsResponse, + PaymentsAuthorizeData, + PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + status: if item.response.rc == "0" { + match item.data.request.is_auto_capture()? { + true => common_enums::AttemptStatus::Charged, + false => common_enums::AttemptStatus::Authorized, + } + } else { + common_enums::AttemptStatus::Failure + }, + response: Ok(PaymentsResponseData::TransactionResponse { + resource_id: ResponseId::ConnectorTransactionId(item.response.tx_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 + }) + } +} + #[derive(Debug, Serialize, Deserialize, PartialEq)] pub struct DeutschebankAmount { amount: MinorUnit, @@ -268,7 +402,7 @@ pub struct DeutschebankBankAccount { #[derive(Debug, Serialize, PartialEq)] pub struct DeutschebankMandate { reference: Secret<String>, - signed_on: Secret<String>, + signed_on: String, } #[derive(Debug, Serialize, PartialEq)] @@ -319,14 +453,12 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>> })? .to_owned(), ); - let signed_on = Secret::from( - queries_params - .get("signed_on") - .ok_or(errors::ConnectorError::MissingRequiredField { - field_name: "signed_on", - })? - .to_owned(), - ); + let signed_on = queries_params + .get("signed_on") + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "signed_on", + })? + .to_owned(); match item.router_data.request.payment_method_data.clone() { Some(PaymentMethodData::BankDebit(BankDebitData::SepaBankDebit { iban, .. })) => { @@ -349,7 +481,10 @@ impl TryFrom<&DeutschebankRouterData<&PaymentsCompleteAuthorizeRouterData>> }, }) } - _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()), + _ => Err(errors::ConnectorError::NotImplemented( + utils::get_unimplemented_payment_method_error_message("deutschebank"), + ) + .into()), } } } diff --git a/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs index fdec3d0e1eb..7f88903e867 100644 --- a/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs @@ -170,13 +170,6 @@ pub enum ResponseType { UnsupportedMediaType, } -#[derive(Debug, Serialize, Deserialize)] -#[serde(rename_all = "camelCase")] -pub enum FiservemeaResponseType { - TransactionResponse, - ErrorResponse, -} - #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum FiservemeaTransactionType { @@ -329,7 +322,7 @@ fn map_status( pub struct FiservemeaPaymentsResponse { response_type: Option<ResponseType>, #[serde(rename = "type")] - fiservemea_type: Option<FiservemeaResponseType>, + fiservemea_type: Option<String>, client_request_id: Option<String>, api_trace_id: Option<String>, ipg_transaction_id: String, @@ -526,7 +519,7 @@ pub struct FiservemeaError { #[derive(Debug, Serialize, Deserialize)] pub struct FiservemeaErrorResponse { #[serde(rename = "type")] - fiservemea_type: Option<FiservemeaResponseType>, + fiservemea_type: Option<String>, client_request_id: Option<String>, api_trace_id: Option<String>, pub response_type: Option<String>, diff --git a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs index b400555305d..56da53c2873 100644 --- a/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs +++ b/crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs @@ -787,6 +787,7 @@ impl<F> MandateReference { connector_mandate_id: Some(id.clone()), payment_method_id: None, + mandate_metadata: None, } }), connector_metadata: None, diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs index df0b63833d9..a9451f6156a 100644 --- a/crates/hyperswitch_domain_models/src/router_data.rs +++ b/crates/hyperswitch_domain_models/src/router_data.rs @@ -242,6 +242,7 @@ pub struct RecurringMandatePaymentData { pub payment_method_type: Option<common_enums::enums::PaymentMethodType>, //required for making recurring payment using saved payment method through stripe pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<common_enums::enums::Currency>, + pub mandate_metadata: Option<serde_json::Value>, } #[derive(Debug, Clone)] diff --git a/crates/hyperswitch_domain_models/src/router_response_types.rs b/crates/hyperswitch_domain_models/src/router_response_types.rs index cb682514c83..79a78efb538 100644 --- a/crates/hyperswitch_domain_models/src/router_response_types.rs +++ b/crates/hyperswitch_domain_models/src/router_response_types.rs @@ -82,6 +82,7 @@ pub struct TaxCalculationResponseData { pub struct MandateReference { pub connector_mandate_id: Option<String>, pub payment_method_id: Option<String>, + pub mandate_metadata: Option<serde_json::Value>, } #[derive(Debug, Clone)] diff --git a/crates/hyperswitch_interfaces/src/errors.rs b/crates/hyperswitch_interfaces/src/errors.rs index e36707af6b0..06f197ebf0b 100644 --- a/crates/hyperswitch_interfaces/src/errors.rs +++ b/crates/hyperswitch_interfaces/src/errors.rs @@ -56,6 +56,8 @@ pub enum ConnectorError { CaptureMethodNotSupported, #[error("Missing connector mandate ID")] MissingConnectorMandateID, + #[error("Missing connector mandate metadata")] + MissingConnectorMandateMetadata, #[error("Missing connector transaction ID")] MissingConnectorTransactionID, #[error("Missing connector refund ID")] diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs index 5842143ad44..46f312b38f2 100644 --- a/crates/router/src/connector/aci/transformers.rs +++ b/crates/router/src/connector/aci/transformers.rs @@ -746,6 +746,7 @@ impl<F, T> .map(|id| types::MandateReference { connector_mandate_id: Some(id.expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(Self { diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index e915d05c358..361ebece299 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -3294,6 +3294,7 @@ pub fn get_adyen_response( .map(|mandate_id| types::MandateReference { connector_mandate_id: Some(mandate_id.expose()), payment_method_id: None, + mandate_metadata: None, }); let network_txn_id = response.additional_data.and_then(|additional_data| { additional_data diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs index 57563c276f5..868409dafc7 100644 --- a/crates/router/src/connector/authorizedotnet/transformers.rs +++ b/crates/router/src/connector/authorizedotnet/transformers.rs @@ -398,6 +398,7 @@ impl<F, T> format!("{customer_profile_id}-{payment_profile_id}") }), payment_method_id: None, + mandate_metadata: None, }, ), connector_metadata: None, @@ -1109,6 +1110,7 @@ impl<F, T> }, ), payment_method_id: None, + mandate_metadata: None, } }); diff --git a/crates/router/src/connector/bamboraapac/transformers.rs b/crates/router/src/connector/bamboraapac/transformers.rs index 3c197699309..819c918338e 100644 --- a/crates/router/src/connector/bamboraapac/transformers.rs +++ b/crates/router/src/connector/bamboraapac/transformers.rs @@ -280,6 +280,7 @@ impl<F> Some(types::MandateReference { connector_mandate_id, payment_method_id: None, + mandate_metadata: None, }) } else { None @@ -463,6 +464,7 @@ impl<F> mandate_reference: Some(types::MandateReference { connector_mandate_id: Some(connector_mandate_id), payment_method_id: None, + mandate_metadata: None, }), connector_metadata: None, network_txn_id: None, diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index 46a522c7378..f47ab4139e8 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -359,6 +359,7 @@ impl<F, T> .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, + mandate_metadata: None, } }); let mut mandate_status = @@ -1487,6 +1488,7 @@ fn get_payment_response( .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(types::PaymentsResponseData::TransactionResponse { diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs index 22982ceb213..05d8c1c559d 100644 --- a/crates/router/src/connector/braintree/transformers.rs +++ b/crates/router/src/connector/braintree/transformers.rs @@ -443,6 +443,7 @@ impl<F> MandateReference { connector_mandate_id: Some(pm.id.clone().expose()), payment_method_id: None, + mandate_metadata: None, } }), connector_metadata: None, @@ -617,6 +618,7 @@ impl<F> MandateReference { connector_mandate_id: Some(pm.id.clone().expose()), payment_method_id: None, + mandate_metadata: None, } }), connector_metadata: None, @@ -698,6 +700,7 @@ impl<F> MandateReference { connector_mandate_id: Some(pm.id.clone().expose()), payment_method_id: None, + mandate_metadata: None, } }), connector_metadata: None, @@ -761,6 +764,7 @@ impl<F> MandateReference { connector_mandate_id: Some(pm.id.clone().expose()), payment_method_id: None, + mandate_metadata: None, } }), connector_metadata: None, diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs index fc35cab773a..9ad4f0604a4 100644 --- a/crates/router/src/connector/cybersource/transformers.rs +++ b/crates/router/src/connector/cybersource/transformers.rs @@ -2227,6 +2227,7 @@ fn get_payment_response( .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(types::PaymentsResponseData::TransactionResponse { @@ -2947,6 +2948,7 @@ impl .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, + mandate_metadata: None, }); let mut mandate_status = enums::AttemptStatus::foreign_from(( item.response diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index efc6661b447..19568ae4671 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -261,6 +261,7 @@ fn get_payment_response( .map(|id| types::MandateReference { connector_mandate_id: Some(id.expose()), payment_method_id: None, + mandate_metadata: None, }) }); match status { diff --git a/crates/router/src/connector/gocardless/transformers.rs b/crates/router/src/connector/gocardless/transformers.rs index f3250602dbc..ff2f9d95026 100644 --- a/crates/router/src/connector/gocardless/transformers.rs +++ b/crates/router/src/connector/gocardless/transformers.rs @@ -512,6 +512,7 @@ impl<F> let mandate_reference = Some(MandateReference { connector_mandate_id: Some(item.response.mandates.id.clone().expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(Self { response: Ok(types::PaymentsResponseData::TransactionResponse { @@ -664,6 +665,7 @@ impl<F> let mandate_reference = MandateReference { connector_mandate_id: Some(item.data.request.get_connector_mandate_id()?), payment_method_id: None, + mandate_metadata: None, }; Ok(Self { status: enums::AttemptStatus::from(item.response.payments.status), diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index c44cf14ab65..547a38ad849 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -982,6 +982,7 @@ impl<F, T> .map(|id| types::MandateReference { connector_mandate_id: Some(id.expose()), payment_method_id: None, + mandate_metadata: None, }), connector_metadata: None, network_txn_id: None, diff --git a/crates/router/src/connector/nexinets/transformers.rs b/crates/router/src/connector/nexinets/transformers.rs index 43cb4cecec8..55b2fbe4176 100644 --- a/crates/router/src/connector/nexinets/transformers.rs +++ b/crates/router/src/connector/nexinets/transformers.rs @@ -358,6 +358,7 @@ impl<F, T> .map(|id| types::MandateReference { connector_mandate_id: Some(id.expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(Self { status: enums::AttemptStatus::foreign_from(( diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs index b7df6829da4..5d987174273 100644 --- a/crates/router/src/connector/noon/transformers.rs +++ b/crates/router/src/connector/noon/transformers.rs @@ -574,6 +574,7 @@ impl<F, T> .map(|subscription_data| types::MandateReference { connector_mandate_id: Some(subscription_data.identifier.expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(Self { status, diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 2547443484e..f280d3a42a2 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -1602,6 +1602,7 @@ where .map(|id| types::MandateReference { connector_mandate_id: Some(id), payment_method_id: None, + mandate_metadata: None, }), // we don't need to save session token for capture, void flow so ignoring if it is not present connector_metadata: if let Some(token) = response.session_token { diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs index 0bb10c9845a..8c2ad2ef979 100644 --- a/crates/router/src/connector/payeezy/transformers.rs +++ b/crates/router/src/connector/payeezy/transformers.rs @@ -418,6 +418,7 @@ impl<F, T> .map(|id| types::MandateReference { connector_mandate_id: Some(id.expose()), payment_method_id: None, + mandate_metadata: None, }); let status = enums::AttemptStatus::foreign_from(( item.response.transaction_status, diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index c12e478b08e..e0ab598d76d 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -250,6 +250,7 @@ impl TryFrom<&PaymePaySaleResponse> for types::PaymentsResponseData { mandate_reference: value.buyer_key.clone().map(|buyer_key| MandateReference { connector_mandate_id: Some(buyer_key.expose()), payment_method_id: None, + mandate_metadata: None, }), connector_metadata: None, network_txn_id: None, diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 910cb94e929..2129ad327c2 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -2389,6 +2389,7 @@ impl<F, T> types::MandateReference { connector_mandate_id, payment_method_id, + mandate_metadata: None, } }); @@ -2583,6 +2584,7 @@ impl<F, T> types::MandateReference { connector_mandate_id, payment_method_id: Some(payment_method_id), + mandate_metadata: None, } }); @@ -2673,6 +2675,7 @@ impl<F, T> types::MandateReference { connector_mandate_id, payment_method_id, + mandate_metadata: None, } }); let status = enums::AttemptStatus::from(item.response.status); diff --git a/crates/router/src/connector/wellsfargo/transformers.rs b/crates/router/src/connector/wellsfargo/transformers.rs index 761fc43982b..be3cf4a1cef 100644 --- a/crates/router/src/connector/wellsfargo/transformers.rs +++ b/crates/router/src/connector/wellsfargo/transformers.rs @@ -1778,6 +1778,7 @@ fn get_payment_response( .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, + mandate_metadata: None, }); Ok(types::PaymentsResponseData::TransactionResponse { @@ -1963,6 +1964,7 @@ impl .payment_instrument .map(|payment_instrument| payment_instrument.id.expose()), payment_method_id: None, + mandate_metadata: None, }); let mut mandate_status = enums::AttemptStatus::foreign_from(( item.response diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs index d2812447ed8..549857494f0 100644 --- a/crates/router/src/core/errors/utils.rs +++ b/crates/router/src/core/errors/utils.rs @@ -189,6 +189,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> | errors::ConnectorError::FlowNotSupported { .. } | errors::ConnectorError::CaptureMethodNotSupported | errors::ConnectorError::MissingConnectorMandateID + | errors::ConnectorError::MissingConnectorMandateMetadata | errors::ConnectorError::MissingConnectorTransactionID | errors::ConnectorError::MissingConnectorRefundID | errors::ConnectorError::MissingApplePayTokenData @@ -288,6 +289,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> errors::ConnectorError::FailedToObtainCertificateKey | errors::ConnectorError::CaptureMethodNotSupported | errors::ConnectorError::MissingConnectorMandateID | + errors::ConnectorError::MissingConnectorMandateMetadata | errors::ConnectorError::MissingConnectorTransactionID | errors::ConnectorError::MissingConnectorRefundID | errors::ConnectorError::MissingApplePayTokenData | @@ -376,6 +378,7 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError> | errors::ConnectorError::FlowNotSupported { .. } | errors::ConnectorError::CaptureMethodNotSupported | errors::ConnectorError::MissingConnectorMandateID + | errors::ConnectorError::MissingConnectorMandateMetadata | errors::ConnectorError::MissingConnectorTransactionID | errors::ConnectorError::MissingConnectorRefundID | errors::ConnectorError::MissingApplePayTokenData diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index 85ae8641373..3a55bf77771 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -4093,6 +4093,9 @@ where payment_method_info.get_id().clone(), ), update_history: None, + mandate_metadata: mandate_reference_record + .mandate_metadata + .clone(), }, )); payment_data.set_recurring_mandate_payment_data( @@ -4103,6 +4106,8 @@ where .original_payment_authorized_amount, original_payment_authorized_currency: mandate_reference_record .original_payment_authorized_currency, + mandate_metadata: mandate_reference_record + .mandate_metadata.clone(), }); connector_choice = Some((connector_data, mandate_reference_id.clone())); diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index e9dca13dc80..ac6c236f536 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -802,6 +802,7 @@ pub async fn get_token_for_recurring_mandate( payment_method_type, original_payment_authorized_amount, original_payment_authorized_currency, + mandate_metadata: None, }), payment_method_type: payment_method.payment_method_type, mandate_connector: Some(mandate_connector_details), @@ -816,6 +817,7 @@ pub async fn get_token_for_recurring_mandate( payment_method_type, original_payment_authorized_amount, original_payment_authorized_currency, + mandate_metadata: None, }), payment_method_type: payment_method.payment_method_type, mandate_connector: Some(mandate_connector_details), diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs index c75cc29ce51..658a02f7d08 100644 --- a/crates/router/src/core/payments/operations/payment_confirm.rs +++ b/crates/router/src/core/payments/operations/payment_confirm.rs @@ -681,6 +681,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa ), payment_method_id: None, update_history: None, + mandate_metadata: None, }, ), ), diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 0731def9453..4b931d68f1e 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -398,7 +398,8 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa api_models::payments::ConnectorMandateReferenceId{ connector_mandate_id: connector_id.connector_mandate_id, payment_method_id: connector_id.payment_method_id, - update_history: None + update_history: None, + mandate_metadata: None, } )) } @@ -437,6 +438,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa ), payment_method_id: None, update_history: None, + mandate_metadata: None, }, ), ), diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs index 90ca49c9746..09292224cae 100644 --- a/crates/router/src/core/payments/operations/payment_response.rs +++ b/crates/router/src/core/payments/operations/payment_response.rs @@ -1504,21 +1504,24 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( let flow_name = core_utils::get_flow_name::<F>()?; if flow_name == "PSync" || flow_name == "CompleteAuthorize" { - let connector_mandate_id = match router_data.response.clone() { + let (connector_mandate_id, mandate_metadata) = match router_data.response.clone() { Ok(resp) => match resp { types::PaymentsResponseData::TransactionResponse { ref mandate_reference, .. } => { if let Some(mandate_ref) = mandate_reference { - mandate_ref.connector_mandate_id.clone() + ( + mandate_ref.connector_mandate_id.clone(), + mandate_ref.mandate_metadata.clone(), + ) } else { - None + (None, None) } } - _ => None, + _ => (None, None), }, - Err(_) => None, + Err(_) => (None, None), }; if let Some(payment_method) = payment_data.payment_method_info.clone() { let connector_mandate_details = @@ -1529,6 +1532,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>( payment_data.payment_attempt.currency, payment_data.payment_attempt.merchant_connector_id.clone(), connector_mandate_id, + mandate_metadata, )?; payment_methods::cards::update_payment_method_connector_mandate_details( state, diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs index c5e7cebac34..c69595d1893 100644 --- a/crates/router/src/core/payments/operations/payment_update.rs +++ b/crates/router/src/core/payments/operations/payment_update.rs @@ -329,7 +329,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa api_models::payments::MandateIds { mandate_id: Some(mandate_obj.mandate_id), mandate_reference_id: Some(api_models::payments::MandateReferenceId::ConnectorMandateId( - api_models::payments::ConnectorMandateReferenceId {connector_mandate_id:connector_id.connector_mandate_id,payment_method_id:connector_id.payment_method_id, update_history: None }, + api_models::payments::ConnectorMandateReferenceId {connector_mandate_id:connector_id.connector_mandate_id,payment_method_id:connector_id.payment_method_id, update_history: None, mandate_metadata:connector_id.mandate_metadata, }, )) } }), diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs index 2d81aecb30e..ca8c6718aa7 100644 --- a/crates/router/src/core/payments/tokenization.rs +++ b/crates/router/src/core/payments/tokenization.rs @@ -148,18 +148,21 @@ where .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Unable to serialize customer acceptance to value")?; - let connector_mandate_id = match responses { + let (connector_mandate_id, mandate_metadata) = match responses { types::PaymentsResponseData::TransactionResponse { ref mandate_reference, .. } => { if let Some(mandate_ref) = mandate_reference { - mandate_ref.connector_mandate_id.clone() + ( + mandate_ref.connector_mandate_id.clone(), + mandate_ref.mandate_metadata.clone(), + ) } else { - None + (None, None) } } - _ => None, + _ => (None, None), }; let check_for_mit_mandates = save_payment_method_data .request @@ -178,6 +181,7 @@ where currency, merchant_connector_id.clone(), connector_mandate_id.clone(), + mandate_metadata.clone(), ) } else { None @@ -373,6 +377,7 @@ where currency, merchant_connector_id.clone(), connector_mandate_id.clone(), + mandate_metadata.clone(), )?; payment_methods::cards::update_payment_method_connector_mandate_details(state, @@ -479,6 +484,7 @@ where currency, merchant_connector_id.clone(), connector_mandate_id.clone(), + mandate_metadata.clone(), )?; payment_methods::cards::update_payment_method_connector_mandate_details( state, @@ -1160,6 +1166,7 @@ pub fn add_connector_mandate_details_in_payment_method( authorized_currency: Option<storage_enums::Currency>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, connector_mandate_id: Option<String>, + mandate_metadata: Option<serde_json::Value>, ) -> Option<storage::PaymentsMandateReference> { let mut mandate_details = HashMap::new(); @@ -1173,6 +1180,7 @@ pub fn add_connector_mandate_details_in_payment_method( payment_method_type, original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, + mandate_metadata, }, ); Some(storage::PaymentsMandateReference(mandate_details)) @@ -1188,6 +1196,7 @@ pub fn update_connector_mandate_details_in_payment_method( authorized_currency: Option<storage_enums::Currency>, merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, connector_mandate_id: Option<String>, + mandate_metadata: Option<serde_json::Value>, ) -> RouterResult<Option<serde_json::Value>> { let mandate_reference = match payment_method.connector_mandate_details { Some(_) => { @@ -1208,6 +1217,7 @@ pub fn update_connector_mandate_details_in_payment_method( payment_method_type, original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, + mandate_metadata: mandate_metadata.clone(), }; mandate_details.map(|mut payment_mandate_reference| { payment_mandate_reference @@ -1218,6 +1228,7 @@ pub fn update_connector_mandate_details_in_payment_method( payment_method_type, original_payment_authorized_amount: authorized_amount, original_payment_authorized_currency: authorized_currency, + mandate_metadata: mandate_metadata.clone(), }); payment_mandate_reference }) @@ -1231,6 +1242,7 @@ pub fn update_connector_mandate_details_in_payment_method( authorized_currency, merchant_connector_id, connector_mandate_id, + mandate_metadata, ), }; let connector_mandate_details = mandate_reference diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs index 34c5714e126..bb1b801edb6 100644 --- a/crates/router/src/types/storage/payment_method.rs +++ b/crates/router/src/types/storage/payment_method.rs @@ -124,6 +124,7 @@ pub struct PaymentsMandateReferenceRecord { pub payment_method_type: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<common_enums::Currency>, + pub mandate_metadata: Option<serde_json::Value>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
feat
[DEUTSCHEBANK] Implement SEPA recurring payments (#5925)
05a475271a2c37ba6ced90b85e53015c47d573bc
2024-03-06 13:00:12
Apoorv Dixit
fix(user): improve role validation to prevent duplicate groups (#3949)
false
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs index 169b3fab123..ae2fb28aae5 100644 --- a/crates/common_enums/src/enums.rs +++ b/crates/common_enums/src/enums.rs @@ -2329,6 +2329,7 @@ pub enum RoleScope { Debug, Eq, PartialEq, + Hash, serde::Serialize, serde::Deserialize, strum::Display, diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs index a0ac1400582..8c2c293da91 100644 --- a/crates/router/src/utils/user_role.rs +++ b/crates/router/src/utils/user_role.rs @@ -1,3 +1,5 @@ +use std::collections::HashSet; + use api_models::user_role as user_role_api; use common_enums::PermissionGroup; use diesel_models::user_role::UserRole; @@ -51,11 +53,18 @@ pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> { .attach_printable("Role groups cannot be empty"); } - if groups.contains(&PermissionGroup::OrganizationManage) { + let unique_groups: HashSet<_> = groups.iter().cloned().collect(); + + if unique_groups.contains(&PermissionGroup::OrganizationManage) { return Err(UserErrors::InvalidRoleOperation.into()) .attach_printable("Organization manage group cannot be added to role"); } + if unique_groups.len() != groups.len() { + return Err(UserErrors::InvalidRoleOperation.into()) + .attach_printable("Duplicate permission group found"); + } + Ok(()) }
fix
improve role validation to prevent duplicate groups (#3949)
c883aa59aae4ddbcf8c754052ed60b4514043d47
2024-12-17 15:53:00
Uzair Khan
feat(analytics): Analytics Request Validator and config driven forex feature (#6733)
false
diff --git a/config/config.example.toml b/config/config.example.toml index 0fe6b8caa2c..5c55d57cf77 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -661,6 +661,7 @@ pm_auth_key = "Some_pm_auth_key" # Analytics configuration. [analytics] source = "sqlx" # The Analytics source/strategy to be used +forex_enabled = false # Enable or disable forex conversion for analytics [analytics.clickhouse] username = "" # Clickhouse username diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml index 848a2305ae4..02d3fe66c09 100644 --- a/config/deployments/env_specific.toml +++ b/config/deployments/env_specific.toml @@ -9,6 +9,7 @@ database_name = "clickhouse_db_name" # Clickhouse database name # Analytics configuration. [analytics] source = "sqlx" # The Analytics source/strategy to be used +forex_enabled = false # Boolean to enable or disable forex conversion [analytics.sqlx] username = "db_user" # Analytics DB Username diff --git a/config/development.toml b/config/development.toml index 077e09f0463..fd84d626d37 100644 --- a/config/development.toml +++ b/config/development.toml @@ -719,6 +719,7 @@ authentication_analytics_topic = "hyperswitch-authentication-events" [analytics] source = "sqlx" +forex_enabled = false [analytics.clickhouse] username = "default" diff --git a/crates/analytics/docs/README.md b/crates/analytics/docs/README.md index eb5c26a6ba3..e24dc6c5af7 100644 --- a/crates/analytics/docs/README.md +++ b/crates/analytics/docs/README.md @@ -104,6 +104,12 @@ To use Forex services, you need to sign up and get your API keys from the follow - It will be in dashboard, labeled as `access key`. ### Configuring Forex APIs +To enable Forex functionality, update the `config/development.toml` or `config/docker_compose.toml` file: + +```toml +[analytics] +forex_enabled = true # default set to false +``` To configure the Forex APIs, update the `config/development.toml` or `config/docker_compose.toml` file with your API keys: diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs index 6d694caadf5..0ad8886b820 100644 --- a/crates/analytics/src/lib.rs +++ b/crates/analytics/src/lib.rs @@ -969,21 +969,25 @@ impl AnalyticsProvider { tenant: &dyn storage_impl::config::TenantConfig, ) -> Self { match config { - AnalyticsConfig::Sqlx { sqlx } => { + AnalyticsConfig::Sqlx { sqlx, .. } => { Self::Sqlx(SqlxClient::from_conf(sqlx, tenant.get_schema()).await) } - AnalyticsConfig::Clickhouse { clickhouse } => Self::Clickhouse(ClickhouseClient { + AnalyticsConfig::Clickhouse { clickhouse, .. } => Self::Clickhouse(ClickhouseClient { config: Arc::new(clickhouse.clone()), database: tenant.get_clickhouse_database().to_string(), }), - AnalyticsConfig::CombinedCkh { sqlx, clickhouse } => Self::CombinedCkh( + AnalyticsConfig::CombinedCkh { + sqlx, clickhouse, .. + } => Self::CombinedCkh( SqlxClient::from_conf(sqlx, tenant.get_schema()).await, ClickhouseClient { config: Arc::new(clickhouse.clone()), database: tenant.get_clickhouse_database().to_string(), }, ), - AnalyticsConfig::CombinedSqlx { sqlx, clickhouse } => Self::CombinedSqlx( + AnalyticsConfig::CombinedSqlx { + sqlx, clickhouse, .. + } => Self::CombinedSqlx( SqlxClient::from_conf(sqlx, tenant.get_schema()).await, ClickhouseClient { config: Arc::new(clickhouse.clone()), @@ -1000,20 +1004,35 @@ impl AnalyticsProvider { pub enum AnalyticsConfig { Sqlx { sqlx: Database, + forex_enabled: bool, }, Clickhouse { clickhouse: ClickhouseConfig, + forex_enabled: bool, }, CombinedCkh { sqlx: Database, clickhouse: ClickhouseConfig, + forex_enabled: bool, }, CombinedSqlx { sqlx: Database, clickhouse: ClickhouseConfig, + forex_enabled: bool, }, } +impl AnalyticsConfig { + pub fn get_forex_enabled(&self) -> bool { + match self { + Self::Sqlx { forex_enabled, .. } + | Self::Clickhouse { forex_enabled, .. } + | Self::CombinedCkh { forex_enabled, .. } + | Self::CombinedSqlx { forex_enabled, .. } => *forex_enabled, + } + } +} + #[async_trait::async_trait] impl SecretsHandler for AnalyticsConfig { async fn convert_to_raw_secret( @@ -1024,7 +1043,7 @@ impl SecretsHandler for AnalyticsConfig { let decrypted_password = match analytics_config { // Todo: Perform kms decryption of clickhouse password Self::Clickhouse { .. } => masking::Secret::new(String::default()), - Self::Sqlx { sqlx } + Self::Sqlx { sqlx, .. } | Self::CombinedCkh { sqlx, .. } | Self::CombinedSqlx { sqlx, .. } => { secret_management_client @@ -1034,26 +1053,46 @@ impl SecretsHandler for AnalyticsConfig { }; Ok(value.transition_state(|conf| match conf { - Self::Sqlx { sqlx } => Self::Sqlx { + Self::Sqlx { + sqlx, + forex_enabled, + } => Self::Sqlx { sqlx: Database { password: decrypted_password, ..sqlx }, + forex_enabled, }, - Self::Clickhouse { clickhouse } => Self::Clickhouse { clickhouse }, - Self::CombinedCkh { sqlx, clickhouse } => Self::CombinedCkh { + Self::Clickhouse { + clickhouse, + forex_enabled, + } => Self::Clickhouse { + clickhouse, + forex_enabled, + }, + Self::CombinedCkh { + sqlx, + clickhouse, + forex_enabled, + } => Self::CombinedCkh { sqlx: Database { password: decrypted_password, ..sqlx }, clickhouse, + forex_enabled, }, - Self::CombinedSqlx { sqlx, clickhouse } => Self::CombinedSqlx { + Self::CombinedSqlx { + sqlx, + clickhouse, + forex_enabled, + } => Self::CombinedSqlx { sqlx: Database { password: decrypted_password, ..sqlx }, clickhouse, + forex_enabled, }, })) } @@ -1063,6 +1102,7 @@ impl Default for AnalyticsConfig { fn default() -> Self { Self::Sqlx { sqlx: Database::default(), + forex_enabled: false, } } } diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs index 00a59d82870..0a512c419ec 100644 --- a/crates/analytics/src/payment_intents/core.rs +++ b/crates/analytics/src/payment_intents/core.rs @@ -68,7 +68,7 @@ pub async fn get_sankey( #[instrument(skip_all)] pub async fn get_metrics( pool: &AnalyticsProvider, - ex_rates: &ExchangeRates, + ex_rates: &Option<ExchangeRates>, auth: &AuthInfo, req: GetPaymentIntentMetricRequest, ) -> AnalyticsResult<PaymentIntentsMetricsResponse<MetricsBucketResponse>> { @@ -201,22 +201,25 @@ pub async fn get_metrics( total += total_count; } if let Some(retried_amount) = collected_values.smart_retried_amount { - let amount_in_usd = id - .currency - .and_then(|currency| { - i64::try_from(retried_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(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + id.currency + .and_then(|currency| { + i64::try_from(retried_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() + } else { + None + }; collected_values.smart_retried_amount_in_usd = amount_in_usd; total_smart_retried_amount += retried_amount; total_smart_retried_amount_in_usd += amount_in_usd.unwrap_or(0); @@ -224,44 +227,50 @@ pub async fn get_metrics( if let Some(retried_amount) = collected_values.smart_retried_amount_without_smart_retries { - let amount_in_usd = id - .currency - .and_then(|currency| { - i64::try_from(retried_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(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + id.currency + .and_then(|currency| { + i64::try_from(retried_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() + } else { + None + }; collected_values.smart_retried_amount_without_smart_retries_in_usd = amount_in_usd; total_smart_retried_amount_without_smart_retries += retried_amount; total_smart_retried_amount_without_smart_retries_in_usd += amount_in_usd.unwrap_or(0); } if let Some(amount) = collected_values.payment_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(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + 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() + } else { + None + }; collected_values.payment_processed_amount_in_usd = amount_in_usd; total_payment_processed_amount_in_usd += amount_in_usd.unwrap_or(0); total_payment_processed_amount += amount; @@ -270,22 +279,25 @@ pub async fn get_metrics( total_payment_processed_count += count; } if let Some(amount) = collected_values.payment_processed_amount_without_smart_retries { - 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(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + 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() + } else { + None + }; collected_values.payment_processed_amount_without_smart_retries_in_usd = amount_in_usd; total_payment_processed_amount_without_smart_retries_in_usd += @@ -322,14 +334,26 @@ pub async fn get_metrics( total_payment_processed_amount_without_smart_retries: Some( total_payment_processed_amount_without_smart_retries, ), - total_smart_retried_amount_in_usd: Some(total_smart_retried_amount_in_usd), - total_smart_retried_amount_without_smart_retries_in_usd: Some( - total_smart_retried_amount_without_smart_retries_in_usd, - ), - total_payment_processed_amount_in_usd: Some(total_payment_processed_amount_in_usd), - total_payment_processed_amount_without_smart_retries_in_usd: Some( - total_payment_processed_amount_without_smart_retries_in_usd, - ), + total_smart_retried_amount_in_usd: if ex_rates.is_some() { + Some(total_smart_retried_amount_in_usd) + } else { + None + }, + total_smart_retried_amount_without_smart_retries_in_usd: if ex_rates.is_some() { + Some(total_smart_retried_amount_without_smart_retries_in_usd) + } else { + None + }, + total_payment_processed_amount_in_usd: if ex_rates.is_some() { + Some(total_payment_processed_amount_in_usd) + } else { + None + }, + total_payment_processed_amount_without_smart_retries_in_usd: if ex_rates.is_some() { + Some(total_payment_processed_amount_without_smart_retries_in_usd) + } else { + None + }, total_payment_processed_count: Some(total_payment_processed_count), total_payment_processed_count_without_smart_retries: Some( total_payment_processed_count_without_smart_retries, diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs index 86192265d07..7291d2f1fcc 100644 --- a/crates/analytics/src/payments/core.rs +++ b/crates/analytics/src/payments/core.rs @@ -48,7 +48,7 @@ pub enum TaskType { #[instrument(skip_all)] pub async fn get_metrics( pool: &AnalyticsProvider, - ex_rates: &ExchangeRates, + ex_rates: &Option<ExchangeRates>, auth: &AuthInfo, req: GetPaymentMetricRequest, ) -> AnalyticsResult<PaymentsMetricsResponse<MetricsBucketResponse>> { @@ -234,22 +234,25 @@ pub async fn get_metrics( .map(|(id, val)| { let mut collected_values = val.collect(); if let Some(amount) = collected_values.payment_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(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + 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() + } else { + None + }; collected_values.payment_processed_amount_in_usd = amount_in_usd; total_payment_processed_amount += amount; total_payment_processed_amount_in_usd += amount_in_usd.unwrap_or(0); @@ -258,22 +261,25 @@ pub async fn get_metrics( total_payment_processed_count += count; } if let Some(amount) = collected_values.payment_processed_amount_without_smart_retries { - 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(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + 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() + } else { + None + }; collected_values.payment_processed_amount_without_smart_retries_usd = amount_in_usd; total_payment_processed_amount_without_smart_retries += amount; total_payment_processed_amount_without_smart_retries_usd += @@ -298,13 +304,19 @@ pub async fn get_metrics( query_data, meta_data: [PaymentsAnalyticsMetadata { total_payment_processed_amount: Some(total_payment_processed_amount), - total_payment_processed_amount_in_usd: Some(total_payment_processed_amount_in_usd), + total_payment_processed_amount_in_usd: if ex_rates.is_some() { + Some(total_payment_processed_amount_in_usd) + } else { + None + }, total_payment_processed_amount_without_smart_retries: Some( total_payment_processed_amount_without_smart_retries, ), - total_payment_processed_amount_without_smart_retries_usd: Some( - total_payment_processed_amount_without_smart_retries_usd, - ), + total_payment_processed_amount_without_smart_retries_usd: if ex_rates.is_some() { + Some(total_payment_processed_amount_without_smart_retries_usd) + } else { + None + }, total_payment_processed_count: Some(total_payment_processed_count), total_payment_processed_count_without_smart_retries: Some( total_payment_processed_count_without_smart_retries, diff --git a/crates/analytics/src/refunds/core.rs b/crates/analytics/src/refunds/core.rs index 04badd06bd2..15ae14206cc 100644 --- a/crates/analytics/src/refunds/core.rs +++ b/crates/analytics/src/refunds/core.rs @@ -47,7 +47,7 @@ pub enum TaskType { pub async fn get_metrics( pool: &AnalyticsProvider, - ex_rates: &ExchangeRates, + ex_rates: &Option<ExchangeRates>, auth: &AuthInfo, req: GetRefundMetricRequest, ) -> AnalyticsResult<RefundsMetricsResponse<RefundMetricsBucketResponse>> { @@ -217,22 +217,25 @@ pub async fn get_metrics( total += total_count; } 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(); + let amount_in_usd = if let Some(ex_rates) = ex_rates { + 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() + } else { + None + }; 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); @@ -261,7 +264,11 @@ pub async fn get_metrics( meta_data: [RefundsAnalyticsMetadata { total_refund_success_rate, total_refund_processed_amount: Some(total_refund_processed_amount), - total_refund_processed_amount_in_usd: Some(total_refund_processed_amount_in_usd), + total_refund_processed_amount_in_usd: if ex_rates.is_some() { + Some(total_refund_processed_amount_in_usd) + } else { + None + }, total_refund_processed_count: Some(total_refund_processed_count), total_refund_reason_count: Some(total_refund_reason_count), total_refund_error_message_count: Some(total_refund_error_message_count), diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs index 7f58c6b00d7..132272f0e49 100644 --- a/crates/api_models/src/analytics.rs +++ b/crates/api_models/src/analytics.rs @@ -62,7 +62,42 @@ pub enum Granularity { #[serde(rename = "G_ONEDAY")] OneDay, } - +pub trait ForexMetric { + fn is_forex_metric(&self) -> bool; +} + +#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] +#[serde(rename_all = "camelCase")] +pub struct AnalyticsRequest { + pub payment_intent: Option<GetPaymentIntentMetricRequest>, + pub payment_attempt: Option<GetPaymentMetricRequest>, + pub refund: Option<GetRefundMetricRequest>, + pub dispute: Option<GetDisputeMetricRequest>, +} + +impl AnalyticsRequest { + pub fn requires_forex_functionality(&self) -> bool { + self.payment_attempt + .as_ref() + .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) + .unwrap_or_default() + || self + .payment_intent + .as_ref() + .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) + .unwrap_or_default() + || self + .refund + .as_ref() + .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) + .unwrap_or_default() + || self + .dispute + .as_ref() + .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) + .unwrap_or_default() + } +} #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentMetricRequest { diff --git a/crates/api_models/src/analytics/disputes.rs b/crates/api_models/src/analytics/disputes.rs index 2509d83e132..e373704b87c 100644 --- a/crates/api_models/src/analytics/disputes.rs +++ b/crates/api_models/src/analytics/disputes.rs @@ -3,7 +3,7 @@ use std::{ hash::{Hash, Hasher}, }; -use super::{NameDescription, TimeRange}; +use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::DisputeStage; #[derive( @@ -28,6 +28,14 @@ pub enum DisputeMetrics { SessionizedTotalAmountDisputed, SessionizedTotalDisputeLostAmount, } +impl ForexMetric for DisputeMetrics { + fn is_forex_metric(&self) -> bool { + matches!( + self, + Self::TotalAmountDisputed | Self::TotalDisputeLostAmount + ) + } +} #[derive( Debug, diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs index 365abd71edc..15c107dfb66 100644 --- a/crates/api_models/src/analytics/payment_intents.rs +++ b/crates/api_models/src/analytics/payment_intents.rs @@ -5,7 +5,7 @@ use std::{ use common_utils::id_type; -use super::{NameDescription, TimeRange}; +use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::{ AuthenticationType, Connector, Currency, IntentStatus, PaymentMethod, PaymentMethodType, }; @@ -106,6 +106,17 @@ pub enum PaymentIntentMetrics { SessionizedPaymentProcessedAmount, SessionizedPaymentsDistribution, } +impl ForexMetric for PaymentIntentMetrics { + fn is_forex_metric(&self) -> bool { + matches!( + self, + Self::PaymentProcessedAmount + | Self::SmartRetriedAmount + | Self::SessionizedPaymentProcessedAmount + | Self::SessionizedSmartRetriedAmount + ) + } +} #[derive(Debug, Default, serde::Serialize)] pub struct ErrorResult { diff --git a/crates/api_models/src/analytics/payments.rs b/crates/api_models/src/analytics/payments.rs index 8fd24f15124..691e827043f 100644 --- a/crates/api_models/src/analytics/payments.rs +++ b/crates/api_models/src/analytics/payments.rs @@ -5,7 +5,7 @@ use std::{ use common_utils::id_type; -use super::{NameDescription, TimeRange}; +use super::{ForexMetric, NameDescription, TimeRange}; use crate::enums::{ AttemptStatus, AuthenticationType, CardNetwork, Connector, Currency, PaymentMethod, PaymentMethodType, @@ -119,6 +119,17 @@ pub enum PaymentMetrics { FailureReasons, } +impl ForexMetric for PaymentMetrics { + fn is_forex_metric(&self) -> bool { + matches!( + self, + Self::PaymentProcessedAmount + | Self::AvgTicketSize + | Self::SessionizedPaymentProcessedAmount + | Self::SessionizedAvgTicketSize + ) + } +} #[derive(Debug, Default, serde::Serialize)] pub struct ErrorResult { pub reason: String, diff --git a/crates/api_models/src/analytics/refunds.rs b/crates/api_models/src/analytics/refunds.rs index 0afca6c1ef6..84954e70910 100644 --- a/crates/api_models/src/analytics/refunds.rs +++ b/crates/api_models/src/analytics/refunds.rs @@ -30,7 +30,7 @@ pub enum RefundType { RetryRefund, } -use super::{NameDescription, TimeRange}; +use super::{ForexMetric, NameDescription, TimeRange}; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct RefundFilters { #[serde(default)] @@ -137,6 +137,14 @@ pub enum RefundDistributions { #[strum(serialize = "refund_error_message")] SessionizedRefundErrorMessage, } +impl ForexMetric for RefundMetrics { + fn is_forex_metric(&self) -> bool { + matches!( + self, + Self::RefundProcessedAmount | Self::SessionizedRefundProcessedAmount + ) + } +} pub mod metric_behaviour { pub struct RefundSuccessRate; diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs index ff2744b824e..8fe30aa59d4 100644 --- a/crates/router/src/analytics.rs +++ b/crates/router/src/analytics.rs @@ -18,12 +18,12 @@ pub mod routes { search::{ GetGlobalSearchRequest, GetSearchRequest, GetSearchRequestWithIndex, SearchIndex, }, - GenerateReportRequest, GetActivePaymentsMetricRequest, GetApiEventFiltersRequest, - GetApiEventMetricRequest, GetAuthEventMetricRequest, GetDisputeMetricRequest, - GetFrmFilterRequest, GetFrmMetricRequest, GetPaymentFiltersRequest, - GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, GetPaymentMetricRequest, - GetRefundFilterRequest, GetRefundMetricRequest, GetSdkEventFiltersRequest, - GetSdkEventMetricRequest, ReportRequest, + AnalyticsRequest, GenerateReportRequest, GetActivePaymentsMetricRequest, + GetApiEventFiltersRequest, GetApiEventMetricRequest, GetAuthEventMetricRequest, + GetDisputeMetricRequest, GetFrmFilterRequest, GetFrmMetricRequest, + GetPaymentFiltersRequest, GetPaymentIntentFiltersRequest, GetPaymentIntentMetricRequest, + GetPaymentMetricRequest, GetRefundFilterRequest, GetRefundMetricRequest, + GetSdkEventFiltersRequest, GetSdkEventMetricRequest, ReportRequest, }; use common_enums::EntityType; use common_utils::types::TimeRange; @@ -31,11 +31,9 @@ pub mod routes { use futures::{stream::FuturesUnordered, StreamExt}; use crate::{ + analytics_validator::request_validator, consts::opensearch::SEARCH_INDEXES, - core::{ - api_locking, currency::get_forex_exchange_rates, errors::user::UserErrors, - verification::utils, - }, + core::{api_locking, errors::user::UserErrors, verification::utils}, db::{user::UserInterface, user_role::ListUserRolesByUserIdPayload}, routes::AppState, services::{ @@ -405,7 +403,15 @@ pub mod routes { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + let validator_response = request_validator( + AnalyticsRequest { + payment_attempt: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -444,7 +450,16 @@ pub mod routes { let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + payment_attempt: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -491,7 +506,16 @@ pub mod routes { merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + payment_attempt: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::payments::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -532,7 +556,16 @@ pub mod routes { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + payment_intent: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -571,7 +604,16 @@ pub mod routes { let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + payment_intent: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -618,7 +660,16 @@ pub mod routes { merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + payment_intent: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -659,7 +710,16 @@ pub mod routes { org_id: org_id.clone(), merchant_ids: vec![merchant_id.clone()], }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + refund: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -698,7 +758,16 @@ pub mod routes { let auth: AuthInfo = AuthInfo::OrgLevel { org_id: org_id.clone(), }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + refund: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) @@ -745,7 +814,16 @@ pub mod routes { merchant_id: merchant_id.clone(), profile_ids: vec![profile_id.clone()], }; - let ex_rates = get_forex_exchange_rates(state.clone()).await?; + + let validator_response = request_validator( + AnalyticsRequest { + refund: Some(req.clone()), + ..Default::default() + }, + &state, + ) + .await?; + let ex_rates = validator_response; analytics::refunds::get_metrics(&state.pool, &ex_rates, &auth, req) .await .map(ApplicationResponse::Json) diff --git a/crates/router/src/analytics_validator.rs b/crates/router/src/analytics_validator.rs new file mode 100644 index 00000000000..d50308cc848 --- /dev/null +++ b/crates/router/src/analytics_validator.rs @@ -0,0 +1,24 @@ +use analytics::errors::AnalyticsError; +use api_models::analytics::AnalyticsRequest; +use common_utils::errors::CustomResult; +use currency_conversion::types::ExchangeRates; +use router_env::logger; + +use crate::core::currency::get_forex_exchange_rates; + +pub async fn request_validator( + req_type: AnalyticsRequest, + state: &crate::routes::SessionState, +) -> CustomResult<Option<ExchangeRates>, AnalyticsError> { + let forex_enabled = state.conf.analytics.get_inner().get_forex_enabled(); + let require_forex_functionality = req_type.requires_forex_functionality(); + + let ex_rates = if forex_enabled && require_forex_functionality { + logger::info!("Fetching forex exchange rates"); + Some(get_forex_exchange_rates(state.clone()).await?) + } else { + None + }; + + Ok(ex_rates) +} diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs index 839dd472423..d43fa054313 100644 --- a/crates/router/src/lib.rs +++ b/crates/router/src/lib.rs @@ -16,6 +16,7 @@ pub mod workflows; #[cfg(feature = "olap")] pub mod analytics; +pub mod analytics_validator; pub mod events; pub mod middleware; pub mod services;
feat
Analytics Request Validator and config driven forex feature (#6733)
d6e13dd0c87537e6696dd6dfc02280f825d116ab
2025-02-19 05:57:19
github-actions
chore(version): 2025.02.19.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 704fda9678b..28565b08385 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,18 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2025.02.19.0 + +### Features + +- **connector:** [Moneris] Add payments flow ([#7249](https://github.com/juspay/hyperswitch/pull/7249)) ([`d18d98a`](https://github.com/juspay/hyperswitch/commit/d18d98a1f687aef1e0f21f6a26387cb9ca7a347d)) +- **core:** Api ,domain and diesel model changes for extended authorization ([#6607](https://github.com/juspay/hyperswitch/pull/6607)) ([`e14d6c4`](https://github.com/juspay/hyperswitch/commit/e14d6c4465bb1276a348a668051c084af72de8e3)) +- **payments:** [Payment links] Add configs for payment link ([#7288](https://github.com/juspay/hyperswitch/pull/7288)) ([`72080c6`](https://github.com/juspay/hyperswitch/commit/72080c67c7927b53d5ca013983f379e9b027c51f)) + +**Full Changelog:** [`2025.02.18.0...2025.02.19.0`](https://github.com/juspay/hyperswitch/compare/2025.02.18.0...2025.02.19.0) + +- - - + ## 2025.02.18.0 ### Features
chore
2025.02.19.0
0db3aed1533856b9892369d7bb2430d90d091756
2024-11-25 17:58:13
Pa1NarK
chore(deps): update cypress packages to address CVE (#6624)
false
diff --git a/cypress-tests-v2/package-lock.json b/cypress-tests-v2/package-lock.json index 36f801468a9..cac88cab055 100644 --- a/cypress-tests-v2/package-lock.json +++ b/cypress-tests-v2/package-lock.json @@ -10,7 +10,7 @@ "license": "ISC", "devDependencies": { "@types/fs-extra": "^11.0.4", - "cypress": "^13.15.2", + "cypress": "^13.16.0", "cypress-mochawesome-reporter": "^3.8.2", "jsqr": "^1.4.0", "nanoid": "^5.0.8", @@ -727,8 +727,8 @@ "license": "MIT" }, "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", "dev": true, "license": "MIT", @@ -742,9 +742,9 @@ } }, "node_modules/cypress": { - "version": "13.15.2", - "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.15.2.tgz", - "integrity": "sha512-ARbnUorjcCM3XiPwgHKuqsyr5W9Qn+pIIBPaoilnoBkLdSC2oLQjV1BUpnmc7KR+b7Avah3Ly2RMFnfxr96E/A==", + "version": "13.16.0", + "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.16.0.tgz", + "integrity": "sha512-g6XcwqnvzXrqiBQR/5gN+QsyRmKRhls1y5E42fyOvsmU7JuY+wM6uHJWj4ZPttjabzbnRvxcik2WemR8+xT6FA==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -1057,7 +1057,7 @@ "dev": true, "license": "MIT", "dependencies": { - "cross-spawn": "^7.0.0", + "cross-spawn": "^7.0.6", "get-stream": "^5.0.0", "human-signals": "^1.1.1", "is-stream": "^2.0.0", diff --git a/cypress-tests-v2/package.json b/cypress-tests-v2/package.json index 20403f9e777..37a51db93cb 100644 --- a/cypress-tests-v2/package.json +++ b/cypress-tests-v2/package.json @@ -15,7 +15,7 @@ "license": "ISC", "devDependencies": { "@types/fs-extra": "^11.0.4", - "cypress": "^13.15.2", + "cypress": "^13.16.0", "cypress-mochawesome-reporter": "^3.8.2", "jsqr": "^1.4.0", "prettier": "^3.3.2", diff --git a/cypress-tests/package-lock.json b/cypress-tests/package-lock.json index abac33d9e32..04390f76f1d 100644 --- a/cypress-tests/package-lock.json +++ b/cypress-tests/package-lock.json @@ -8,13 +8,11 @@ "name": "test", "version": "1.0.0", "license": "ISC", - "dependencies": { - "prettier": "^3.3.2" - }, "devDependencies": { - "cypress": "^13.14.1", + "cypress": "^13.16.0", "cypress-mochawesome-reporter": "^3.8.2", - "jsqr": "^1.4.0" + "jsqr": "^1.4.0", + "prettier": "^3.3.2" } }, "node_modules/@colors/colors": { @@ -29,9 +27,9 @@ } }, "node_modules/@cypress/request": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/@cypress/request/-/request-3.0.1.tgz", - "integrity": "sha512-TWivJlJi8ZDx2wGOw1dbLuHJKUYX7bWySw377nlnGOW3hP9/MUKIsEdXT/YngWxVdgNCHRBmFlBipE+5/2ZZlQ==", + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/@cypress/request/-/request-3.0.6.tgz", + "integrity": "sha512-fi0eVdCOtKu5Ed6+E8mYxUF6ZTFJDZvHogCBelM0xVXmrDEkyM22gRArQzq1YcHPm1V47Vf/iAD+WgVdUlJCGg==", "dev": true, "license": "Apache-2.0", "dependencies": { @@ -41,16 +39,16 @@ "combined-stream": "~1.0.6", "extend": "~3.0.2", "forever-agent": "~0.6.1", - "form-data": "~2.3.2", - "http-signature": "~1.3.6", + "form-data": "~4.0.0", + "http-signature": "~1.4.0", "is-typedarray": "~1.0.0", "isstream": "~0.1.2", "json-stringify-safe": "~5.0.1", "mime-types": "~2.1.19", "performance-now": "^2.1.0", - "qs": "6.10.4", + "qs": "6.13.0", "safe-buffer": "^5.1.2", - "tough-cookie": "^4.1.3", + "tough-cookie": "^5.0.0", "tunnel-agent": "^0.6.0", "uuid": "^8.3.2" }, @@ -290,9 +288,9 @@ } }, "node_modules/aws4": { - "version": "1.13.1", - "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.1.tgz", - "integrity": "sha512-u5w79Rd7SU4JaIlA/zFqG+gOiuq25q5VLyZ8E+ijJeILuTxVzZgp2CaGw/UTw6pXYN9XMO9yiqj/nEHmhTG5CA==", + "version": "1.13.2", + "resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.2.tgz", + "integrity": "sha512-lHe62zvbTB5eEABUVi/AwVh0ZKY9rMMDhmm+eeyuuUQbQ3+J+fONVQOZyj+DdrvD4BY33uYniyRJ4UJIaSKAfw==", "dev": true, "license": "MIT" }, @@ -548,9 +546,9 @@ } }, "node_modules/ci-info": { - "version": "3.9.0", - "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-3.9.0.tgz", - "integrity": "sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ==", + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/ci-info/-/ci-info-4.1.0.tgz", + "integrity": "sha512-HutrvTNsF48wnxkzERIXOe5/mlcfFcbfCmwcg6CJnizbSue78AbDt+1cgl26zwn61WFxhcPykPfZrbqjGmBb4A==", "dev": true, "funding": [ { @@ -707,9 +705,9 @@ "license": "MIT" }, "node_modules/cross-spawn": { - "version": "7.0.3", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.3.tgz", - "integrity": "sha512-iRDPJKUPVEND7dHPO8rkbOnPpyDygcDFtWjpeWNCgy8WP2rXcxXL8TskReQl6OrB2G7+UJrags1q15Fudc7G6w==", + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", "dev": true, "license": "MIT", "dependencies": { @@ -722,14 +720,14 @@ } }, "node_modules/cypress": { - "version": "13.14.1", - "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.14.1.tgz", - "integrity": "sha512-Wo+byPmjps66hACEH5udhXINEiN3qS3jWNGRzJOjrRJF3D0+YrcP2LVB1T7oYaVQM/S+eanqEvBWYc8cf7Vcbg==", + "version": "13.16.0", + "resolved": "https://registry.npmjs.org/cypress/-/cypress-13.16.0.tgz", + "integrity": "sha512-g6XcwqnvzXrqiBQR/5gN+QsyRmKRhls1y5E42fyOvsmU7JuY+wM6uHJWj4ZPttjabzbnRvxcik2WemR8+xT6FA==", "dev": true, "hasInstallScript": true, "license": "MIT", "dependencies": { - "@cypress/request": "^3.0.1", + "@cypress/request": "^3.0.6", "@cypress/xvfb": "^1.2.4", "@types/sinonjs__fake-timers": "8.1.1", "@types/sizzle": "^2.3.2", @@ -740,6 +738,7 @@ "cachedir": "^2.3.0", "chalk": "^4.1.0", "check-more-types": "^2.24.0", + "ci-info": "^4.0.0", "cli-cursor": "^3.1.0", "cli-table3": "~0.6.1", "commander": "^6.2.1", @@ -754,7 +753,6 @@ "figures": "^3.2.0", "fs-extra": "^9.1.0", "getos": "^3.2.1", - "is-ci": "^3.0.1", "is-installed-globally": "~0.4.0", "lazy-ass": "^1.6.0", "listr2": "^3.8.3", @@ -769,6 +767,7 @@ "semver": "^7.5.3", "supports-color": "^8.1.1", "tmp": "~0.2.3", + "tree-kill": "1.2.2", "untildify": "^4.0.0", "yauzl": "^2.10.0" }, @@ -1036,7 +1035,7 @@ "dev": true, "license": "MIT", "dependencies": { - "cross-spawn": "^7.0.0", + "cross-spawn": "^7.0.6", "get-stream": "^5.0.0", "human-signals": "^1.1.1", "is-stream": "^2.0.0", @@ -1184,18 +1183,18 @@ } }, "node_modules/form-data": { - "version": "2.3.3", - "resolved": "https://registry.npmjs.org/form-data/-/form-data-2.3.3.tgz", - "integrity": "sha512-1lLKB2Mu3aGP1Q/2eCOx0fNbRMe7XdwktwOruhfqqd0rIJWwN4Dh+E3hrPSlDCXnSR7UtZ1N38rVXm+6+MEhJQ==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.1.tgz", + "integrity": "sha512-tzN8e4TX8+kkxGPK8D5u0FNmjPUjw3lwC9lSLxxoB/+GtsJG91CO8bSWy73APlgAZzZbXEYZJuxjkHH2w+Ezhw==", "dev": true, "license": "MIT", "dependencies": { "asynckit": "^0.4.0", - "combined-stream": "^1.0.6", + "combined-stream": "^1.0.8", "mime-types": "^2.1.12" }, "engines": { - "node": ">= 0.12" + "node": ">= 6" } }, "node_modules/fs-extra": { @@ -1466,15 +1465,15 @@ } }, "node_modules/http-signature": { - "version": "1.3.6", - "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.3.6.tgz", - "integrity": "sha512-3adrsD6zqo4GsTqtO7FyrejHNv+NgiIfAfv68+jVlFmSr9OGy7zrxONceFRLKvnnZA5jbxQBX1u9PpB6Wi32Gw==", + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/http-signature/-/http-signature-1.4.0.tgz", + "integrity": "sha512-G5akfn7eKbpDN+8nPS/cb57YeA1jLTVxjpCj7tmm3QKPdyDy7T+qSC40e9ptydSWvkwjSXw1VbkpyEm39ukeAg==", "dev": true, "license": "MIT", "dependencies": { "assert-plus": "^1.0.0", "jsprim": "^2.0.2", - "sshpk": "^1.14.1" + "sshpk": "^1.18.0" }, "engines": { "node": ">=0.10" @@ -1564,19 +1563,6 @@ "node": ">=8" } }, - "node_modules/is-ci": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/is-ci/-/is-ci-3.0.1.tgz", - "integrity": "sha512-ZYvCgrefwqoQ6yTyYUbQu64HsITZ3NfKX1lzaEYdkTDcfKzzCI/wthRRYKkdjHKFVgNiXKAKm65Zo1pk2as/QQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "ci-info": "^3.2.0" - }, - "bin": { - "is-ci": "bin.js" - } - }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -2481,9 +2467,9 @@ } }, "node_modules/object-inspect": { - "version": "1.13.2", - "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.2.tgz", - "integrity": "sha512-IRZSRuzJiynemAXPYtPe5BoI/RESNYR7TYm50MC5Mqbd3Jmw5y790sErYw3V6SryFJD64b74qQQs9wn5Bg/k3g==", + "version": "1.13.3", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.3.tgz", + "integrity": "sha512-kDCGIbxkDSXE3euJZZXzc6to7fCrKHNI/hSRQnRuQ+BWjFNzZwiFF8fj/6o2t2G9/jTj8PSIYTfCLelLZEeRpA==", "dev": true, "license": "MIT", "engines": { @@ -2668,6 +2654,7 @@ "version": "3.3.3", "resolved": "https://registry.npmjs.org/prettier/-/prettier-3.3.3.tgz", "integrity": "sha512-i2tDNA0O5IrMO757lfrdQZCc2jPNDVntV0m/+4whiDfWaTKfMNgR7Qz0NAeGz/nRqF4m5/6CLzbP4/liHt12Ew==", + "dev": true, "license": "MIT", "bin": { "prettier": "bin/prettier.cjs" @@ -2721,13 +2708,6 @@ "dev": true, "license": "MIT" }, - "node_modules/psl": { - "version": "1.9.0", - "resolved": "https://registry.npmjs.org/psl/-/psl-1.9.0.tgz", - "integrity": "sha512-E/ZsdU4HLs/68gYzgGTkMicWTLPdAftJLfJFlLUAAKZGkStNU72sZjT66SnMDVOfOWY/YAoiD7Jxa9iHvngcag==", - "dev": true, - "license": "MIT" - }, "node_modules/pump": { "version": "3.0.0", "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.0.tgz", @@ -2739,24 +2719,14 @@ "once": "^1.3.1" } }, - "node_modules/punycode": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", - "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=6" - } - }, "node_modules/qs": { - "version": "6.10.4", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.10.4.tgz", - "integrity": "sha512-OQiU+C+Ds5qiH91qh/mg0w+8nwQuLjM4F4M/PbmhDOoYehPh+Fb0bDjtR1sOvy7YKxvj28Y/M0PhP5uVX0kB+g==", + "version": "6.13.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", + "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", "dev": true, "license": "BSD-3-Clause", "dependencies": { - "side-channel": "^1.0.4" + "side-channel": "^1.0.6" }, "engines": { "node": ">=0.6" @@ -2765,13 +2735,6 @@ "url": "https://github.com/sponsors/ljharb" } }, - "node_modules/querystringify": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/querystringify/-/querystringify-2.2.0.tgz", - "integrity": "sha512-FIqgj2EUvTa7R50u0rGsyTftzjYmv/a3hO345bZNrqabNqjtgiDMgmo4mkUjd+nzU5oF3dClKqFIPUKybUyqoQ==", - "dev": true, - "license": "MIT" - }, "node_modules/randombytes": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", @@ -2831,13 +2794,6 @@ "dev": true, "license": "ISC" }, - "node_modules/requires-port": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/requires-port/-/requires-port-1.0.0.tgz", - "integrity": "sha512-KigOCHcocU3XODJxsu8i/j8T9tzT4adHiecwORRQ0ZZFcp7ahwXuRU1m+yuO90C5ZUyGeGfocHDI14M3L3yDAQ==", - "dev": true, - "license": "MIT" - }, "node_modules/restore-cursor": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-3.1.0.tgz", @@ -3138,6 +3094,26 @@ "dev": true, "license": "MIT" }, + "node_modules/tldts": { + "version": "6.1.62", + "resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.62.tgz", + "integrity": "sha512-TF+wo3MgTLbf37keEwQD0IxvOZO8UZxnpPJDg5iFGAASGxYzbX/Q0y944ATEjrfxG/pF1TWRHCPbFp49Mz1Y1w==", + "dev": true, + "license": "MIT", + "dependencies": { + "tldts-core": "^6.1.62" + }, + "bin": { + "tldts": "bin/cli.js" + } + }, + "node_modules/tldts-core": { + "version": "6.1.62", + "resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.62.tgz", + "integrity": "sha512-ohONqbfobpuaylhqFbtCzc0dFFeNz85FVKSesgT8DS9OV3a25Yj730pTj7/dDtCqmgoCgEj6gDiU9XxgHKQlBw==", + "dev": true, + "license": "MIT" + }, "node_modules/tmp": { "version": "0.2.3", "resolved": "https://registry.npmjs.org/tmp/-/tmp-0.2.3.tgz", @@ -3163,29 +3139,26 @@ } }, "node_modules/tough-cookie": { - "version": "4.1.4", - "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-4.1.4.tgz", - "integrity": "sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag==", + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.0.0.tgz", + "integrity": "sha512-FRKsF7cz96xIIeMZ82ehjC3xW2E+O2+v11udrDYewUbszngYhsGa8z6YUMMzO9QJZzzyd0nGGXnML/TReX6W8Q==", "dev": true, "license": "BSD-3-Clause", "dependencies": { - "psl": "^1.1.33", - "punycode": "^2.1.1", - "universalify": "^0.2.0", - "url-parse": "^1.5.3" + "tldts": "^6.1.32" }, "engines": { - "node": ">=6" + "node": ">=16" } }, - "node_modules/tough-cookie/node_modules/universalify": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.2.0.tgz", - "integrity": "sha512-CJ1QgKmNg3CwvAv/kOFmtnEN05f0D/cn9QntgNOQlQF9dgvVTHj3t+8JPdjqawCHk7V/KA+fbUqzZ9XWhcqPUg==", + "node_modules/tree-kill": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz", + "integrity": "sha512-L0Orpi8qGpRG//Nd+H90vFB+3iHnue1zSSGmNOOCh1GLJ7rUKVwV2HvijphGQS2UmhUZewS9VgvxYIdgr+fG1A==", "dev": true, "license": "MIT", - "engines": { - "node": ">= 4.0.0" + "bin": { + "tree-kill": "cli.js" } }, "node_modules/tslib": { @@ -3256,17 +3229,6 @@ "node": ">=8" } }, - "node_modules/url-parse": { - "version": "1.5.10", - "resolved": "https://registry.npmjs.org/url-parse/-/url-parse-1.5.10.tgz", - "integrity": "sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==", - "dev": true, - "license": "MIT", - "dependencies": { - "querystringify": "^2.1.1", - "requires-port": "^1.0.0" - } - }, "node_modules/uuid": { "version": "8.3.2", "resolved": "https://registry.npmjs.org/uuid/-/uuid-8.3.2.tgz", diff --git a/cypress-tests/package.json b/cypress-tests/package.json index 7bb40354efd..204e3393d0a 100644 --- a/cypress-tests/package.json +++ b/cypress-tests/package.json @@ -15,11 +15,9 @@ "author": "", "license": "ISC", "devDependencies": { - "cypress": "^13.14.1", + "cypress": "^13.16.0", "cypress-mochawesome-reporter": "^3.8.2", - "jsqr": "^1.4.0" - }, - "dependencies": { + "jsqr": "^1.4.0", "prettier": "^3.3.2" } }
chore
update cypress packages to address CVE (#6624)
980aa448634de86f11fb67aabefc15884f1b8ced
2023-10-05 20:56:44
ItsMeShashank
refactor(router): remove the payment type column in payment intent (#2462)
false
diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/data_models/src/payments/payment_intent.rs index db182839b95..b3bf8af8c36 100644 --- a/crates/data_models/src/payments/payment_intent.rs +++ b/crates/data_models/src/payments/payment_intent.rs @@ -105,7 +105,6 @@ pub struct PaymentIntent { // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, - pub payment_type: Option<storage_enums::PaymentType>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] @@ -145,7 +144,6 @@ pub struct PaymentIntentNew { pub profile_id: Option<String>, pub merchant_decision: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, - pub payment_type: Option<storage_enums::PaymentType>, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index a6de1137de2..1212c9d5242 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -47,7 +47,6 @@ pub struct PaymentIntent { // Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, - pub payment_type: Option<storage_enums::PaymentType>, } #[derive( @@ -99,7 +98,6 @@ pub struct PaymentIntentNew { pub profile_id: Option<String>, pub merchant_decision: Option<String>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, - pub payment_type: Option<storage_enums::PaymentType>, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index f1ebcdb4346..3a6e2cd2a93 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -609,7 +609,6 @@ diesel::table! { #[max_length = 64] merchant_decision -> Nullable<Varchar>, payment_confirm_source -> Nullable<PaymentSource>, - payment_type -> Nullable<PaymentType>, } } diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index f5428592da1..bcb52164471 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -861,6 +861,19 @@ pub async fn list_payment_methods( .await .transpose()?; + let payment_type = payment_attempt.as_ref().map(|pa| { + let amount = api::Amount::from(pa.amount); + let mandate_type = if pa.mandate_id.is_some() { + Some(api::MandateTransactionType::RecurringMandateTransaction) + } else if pa.mandate_details.is_some() { + Some(api::MandateTransactionType::NewMandateTransaction) + } else { + None + }; + + helpers::infer_payment_type(&amount, mandate_type.as_ref()) + }); + let all_mcas = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( &merchant_account.merchant_id, @@ -1280,8 +1293,8 @@ pub async fn list_payment_methods( api::PaymentMethodListResponse { redirect_url: merchant_account.return_url, merchant_name: merchant_account.merchant_name, + payment_type, payment_methods: payment_method_responses, - payment_type: payment_intent.as_ref().and_then(|pi| pi.payment_type), mandate_payment: payment_attempt.and_then(|inner| inner.mandate_details).map( |d| match d { data_models::mandates::MandateDataType::SingleUse(i) => { diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 3417e9db4e2..440d284d0cc 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -2398,7 +2398,6 @@ mod tests { profile_id: None, merchant_decision: None, payment_confirm_source: None, - payment_type: Some(api_enums::PaymentType::Normal), }; let req_cs = Some("1".to_string()); let merchant_fulfillment_time = Some(900); @@ -2446,7 +2445,6 @@ mod tests { profile_id: None, merchant_decision: None, payment_confirm_source: None, - payment_type: Some(api_enums::PaymentType::Normal), }; let req_cs = Some("1".to_string()); let merchant_fulfillment_time = Some(10); @@ -2494,7 +2492,6 @@ mod tests { profile_id: None, merchant_decision: None, payment_confirm_source: None, - payment_type: Some(api_enums::PaymentType::Normal), }; let req_cs = Some("1".to_string()); let merchant_fulfillment_time = Some(10); diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs index 8971aaeed33..17d8d5f6c3d 100644 --- a/crates/router/src/core/payments/operations/payment_create.rs +++ b/crates/router/src/core/payments/operations/payment_create.rs @@ -77,8 +77,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa core_utils::validate_and_get_business_profile(db, request.profile_id.as_ref(), merchant_id) .await?; - let payment_type = helpers::infer_payment_type(&amount, mandate_type.as_ref()); - let ( token, payment_method, @@ -147,7 +145,6 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa request, shipping_address.clone().map(|x| x.address_id), billing_address.clone().map(|x| x.address_id), - payment_type, attempt_id, state, ) @@ -606,7 +603,6 @@ impl PaymentCreate { request: &api::PaymentsRequest, shipping_address_id: Option<String>, billing_address_id: Option<String>, - payment_type: enums::PaymentType, active_attempt_id: String, state: &AppState, ) -> RouterResult<storage::PaymentIntentNew> { @@ -681,7 +677,6 @@ impl PaymentCreate { profile_id: Some(profile_id), merchant_decision: None, payment_confirm_source: None, - payment_type: Some(payment_type), }) } diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs index ff8ae44758a..43d7207d452 100644 --- a/crates/storage_impl/src/mock_db/payment_intent.rs +++ b/crates/storage_impl/src/mock_db/payment_intent.rs @@ -106,7 +106,6 @@ impl PaymentIntentInterface for MockDb { profile_id: new.profile_id, merchant_decision: new.merchant_decision, payment_confirm_source: new.payment_confirm_source, - payment_type: new.payment_type, }; payment_intents.push(payment_intent.clone()); Ok(payment_intent) diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs index f30d26e30d7..8352158be05 100644 --- a/crates/storage_impl/src/payments/payment_intent.rs +++ b/crates/storage_impl/src/payments/payment_intent.rs @@ -91,7 +91,6 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> { profile_id: new.profile_id.clone(), merchant_decision: new.merchant_decision.clone(), payment_confirm_source: new.payment_confirm_source, - payment_type: new.payment_type, }; match self @@ -708,7 +707,6 @@ impl DataModelExt for PaymentIntentNew { profile_id: self.profile_id, merchant_decision: self.merchant_decision, payment_confirm_source: self.payment_confirm_source, - payment_type: self.payment_type, } } @@ -746,7 +744,6 @@ impl DataModelExt for PaymentIntentNew { profile_id: storage_model.profile_id, merchant_decision: storage_model.merchant_decision, payment_confirm_source: storage_model.payment_confirm_source, - payment_type: storage_model.payment_type, } } } @@ -789,7 +786,6 @@ impl DataModelExt for PaymentIntent { profile_id: self.profile_id, merchant_decision: self.merchant_decision, payment_confirm_source: self.payment_confirm_source, - payment_type: self.payment_type, } } @@ -828,7 +824,6 @@ impl DataModelExt for PaymentIntent { profile_id: storage_model.profile_id, merchant_decision: storage_model.merchant_decision, payment_confirm_source: storage_model.payment_confirm_source, - payment_type: storage_model.payment_type, } } } diff --git a/migrations/2023-10-04-120026_add_payment_type_column_in_payment_intent/down.sql b/migrations/2023-10-04-120026_add_payment_type_column_in_payment_intent/down.sql deleted file mode 100644 index 74f43b254fd..00000000000 --- a/migrations/2023-10-04-120026_add_payment_type_column_in_payment_intent/down.sql +++ /dev/null @@ -1,6 +0,0 @@ --- This file should undo anything in `up.sql` - -ALTER TABLE payment_intent -DROP COLUMN payment_type; - -DROP TYPE "PaymentType"; diff --git a/migrations/2023-10-04-120026_add_payment_type_column_in_payment_intent/up.sql b/migrations/2023-10-04-120026_add_payment_type_column_in_payment_intent/up.sql deleted file mode 100644 index 622f24b48b3..00000000000 --- a/migrations/2023-10-04-120026_add_payment_type_column_in_payment_intent/up.sql +++ /dev/null @@ -1,11 +0,0 @@ --- Your SQL goes here - -CREATE TYPE "PaymentType" AS ENUM ( - 'normal', - 'new_mandate', - 'setup_mandate', - 'recurring_mandate' -); - -ALTER TABLE payment_intent -ADD COLUMN payment_type "PaymentType";
refactor
remove the payment type column in payment intent (#2462)
ea54b3dd135b74b83537a5df8674c0928c6d4057
2024-02-09 14:23:22
github-actions
chore(version): 2024.02.09.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index daba38c30eb..eb13a21ef7e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,21 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.02.09.1 + +### Bug Fixes + +- **core:** Add column mandate_data for storing the details of a mandate in PaymentAttempt ([#3606](https://github.com/juspay/hyperswitch/pull/3606)) ([`74f3721`](https://github.com/juspay/hyperswitch/commit/74f3721ccd0cceac6ae8e751cb83784d2f00a283)) +- **postman:** Fix failing postman tests and send a proper error message ([#3601](https://github.com/juspay/hyperswitch/pull/3601)) ([`3cef73b`](https://github.com/juspay/hyperswitch/commit/3cef73b9d8b35cb337757e29e78d22bcbe72faac)) + +### Miscellaneous Tasks + +- **postman:** Update Postman collection files ([`155aa9d`](https://github.com/juspay/hyperswitch/commit/155aa9d1192c3632c5678a958c4bb89f7861c636)) + +**Full Changelog:** [`2024.02.09.0...2024.02.09.1`](https://github.com/juspay/hyperswitch/compare/2024.02.09.0...2024.02.09.1) + +- - - + ## 2024.02.09.0 ### Features
chore
2024.02.09.1
40f6776c46abc4b9c89fb2aa195f4ce64b312cf6
2024-05-20 18:31:35
Sanchith Hegde
docs: update Docker Compose setup guide to checkout `latest` tag (#4695)
false
diff --git a/.github/workflows/release-stable-version.yml b/.github/workflows/release-stable-version.yml index 64609aed863..54a4d2b1a4e 100644 --- a/.github/workflows/release-stable-version.yml +++ b/.github/workflows/release-stable-version.yml @@ -118,7 +118,7 @@ jobs: echo "PREVIOUS_TAG=${PREVIOUS_TAG}" >> $GITHUB_ENV echo "NEXT_TAG=${NEXT_TAG}" >> $GITHUB_ENV - # We make use of GitHub API calls to create the tag to have signed tags + # We make use of GitHub API calls to create and update tags - name: Create SemVer tag shell: bash env: @@ -133,6 +133,18 @@ jobs: --raw-field "ref=refs/tags/${NEXT_TAG}" \ --raw-field 'sha=${{ github.sha }}' + - name: Update `latest` tag to point to newly created SemVer tag + shell: bash + env: + GH_TOKEN: ${{ steps.generate_app_token.outputs.token }} + run: | + gh api \ + --method PATCH \ + --header 'Accept: application/vnd.github+json' \ + --header 'X-GitHub-Api-Version: 2022-11-28' \ + '/repos/{owner}/{repo}/git/refs/tags/latest' \ + --raw-field 'sha=${{ github.sha }}' + - name: Generate changelog shell: bash run: | diff --git a/README.md b/README.md index 2be649b1db6..5bfcfdfd62b 100644 --- a/README.md +++ b/README.md @@ -75,10 +75,12 @@ The fastest and easiest way to try Hyperswitch is via our CDK scripts You can run Hyperswitch on your system using Docker Compose after cloning this repository: ```shell +git clone --depth 1 --branch latest https://github.com/juspay/hyperswitch +cd hyperswitch docker compose up -d ``` -This will start the payments router, the primary component within Hyperswitch. +This will start the app server, web client and control center. Check out the [local setup guide][local-setup-guide] for a more comprehensive setup, which includes the [scheduler and monitoring services][docker-compose-scheduler-monitoring]. diff --git a/docs/try_local_system.md b/docs/try_local_system.md index a13d04ade83..a05e9b9f44e 100644 --- a/docs/try_local_system.md +++ b/docs/try_local_system.md @@ -36,7 +36,7 @@ Check the Table Of Contents to jump to the relevant section. 2. Clone the repository and switch to the project directory: ```shell - git clone https://github.com/juspay/hyperswitch + git clone --depth 1 --branch latest https://github.com/juspay/hyperswitch cd hyperswitch ``` @@ -51,13 +51,13 @@ Check the Table Of Contents to jump to the relevant section. docker compose up -d ``` - This should run the hyperswitch payments router, the primary component within - hyperswitch. + This should run the hyperswitch app server, web client and control center. Wait for the `migration_runner` container to finish installing `diesel_cli` - and running migrations (approximately 2 minutes) before proceeding further. + and running migrations (approximately 2 minutes), and for the + `hyperswitch-web` container to finish compiling before proceeding further. You can also choose to [run the scheduler and monitoring services](#run-the-scheduler-and-monitoring-services) - in addition to the payments router. + in addition to the app server, web client and control center. 5. Verify that the server is up and running by hitting the health endpoint:
docs
update Docker Compose setup guide to checkout `latest` tag (#4695)
a791391e2ac125ef7bb6a92de5f1419e673bdfe0
2024-07-30 12:45:48
Hrithikesh
feat: rename columns in organization for v2 (#5424)
false
diff --git a/crates/analytics/Cargo.toml b/crates/analytics/Cargo.toml index 91bc16f2779..70038e98271 100644 --- a/crates/analytics/Cargo.toml +++ b/crates/analytics/Cargo.toml @@ -16,7 +16,7 @@ v2 = ["api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "stor 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" } -diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } +diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false } hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces", default-features = false } masking = { version = "0.1.0", path = "../masking" } diff --git a/crates/diesel_models/src/organization.rs b/crates/diesel_models/src/organization.rs index f5a67bd70b9..ed90e641f37 100644 --- a/crates/diesel_models/src/organization.rs +++ b/crates/diesel_models/src/organization.rs @@ -1,33 +1,189 @@ use common_utils::{id_type, pii}; use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable}; +#[cfg(all( + any(any(feature = "v1", feature = "v2"), feature = "v2"), + not(feature = "merchant_account_v2") +))] use crate::schema::organization; +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +use crate::schema_v2::organization; +pub trait OrganizationBridge { + fn get_organization_id(&self) -> id_type::OrganizationId; + fn get_organization_name(&self) -> Option<String>; + fn set_organization_name(&mut self, organization_name: String); +} +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] +#[derive(Clone, Debug, Identifiable, Queryable, Selectable)] +#[diesel( + table_name = organization, + primary_key(org_id), + check_for_backend(diesel::pg::Pg) +)] +pub struct Organization { + org_id: id_type::OrganizationId, + org_name: Option<String>, + pub organization_details: Option<pii::SecretSerdeValue>, + pub metadata: Option<pii::SecretSerdeValue>, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, + #[allow(dead_code)] + id: Option<id_type::OrganizationId>, + #[allow(dead_code)] + organization_name: Option<String>, +} + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] -#[diesel(table_name = organization, primary_key(org_id), check_for_backend(diesel::pg::Pg))] +#[diesel( + table_name = organization, + primary_key(id), + check_for_backend(diesel::pg::Pg) +)] pub struct Organization { - pub org_id: id_type::OrganizationId, - pub org_name: Option<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, + id: id_type::OrganizationId, + organization_name: Option<String>, } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] +impl Organization { + pub fn new(org_new: OrganizationNew) -> Self { + let OrganizationNew { + org_id, + org_name, + organization_details, + metadata, + created_at, + modified_at, + id: _, + organization_name: _, + } = org_new; + Self { + id: Some(org_id.clone()), + organization_name: org_name.clone(), + org_id, + org_name, + organization_details, + metadata, + created_at, + modified_at, + } + } +} + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +impl Organization { + pub fn new(org_new: OrganizationNew) -> Self { + let OrganizationNew { + id, + organization_name, + organization_details, + metadata, + created_at, + modified_at, + } = org_new; + Self { + id, + organization_name, + organization_details, + metadata, + created_at, + modified_at, + } + } +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] #[derive(Clone, Debug, Insertable)] #[diesel(table_name = organization, primary_key(org_id))] pub struct OrganizationNew { - pub org_id: id_type::OrganizationId, - pub org_name: Option<String>, + org_id: id_type::OrganizationId, + org_name: Option<String>, + id: Option<id_type::OrganizationId>, + organization_name: Option<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub created_at: time::PrimitiveDateTime, pub modified_at: time::PrimitiveDateTime, } +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +#[derive(Clone, Debug, Insertable)] +#[diesel(table_name = organization, primary_key(id))] +pub struct OrganizationNew { + id: id_type::OrganizationId, + organization_name: Option<String>, + pub organization_details: Option<pii::SecretSerdeValue>, + pub metadata: Option<pii::SecretSerdeValue>, + pub created_at: time::PrimitiveDateTime, + pub modified_at: time::PrimitiveDateTime, +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] +impl OrganizationNew { + pub fn new(id: id_type::OrganizationId, organization_name: Option<String>) -> Self { + Self { + org_id: id.clone(), + org_name: organization_name.clone(), + id: Some(id), + organization_name, + organization_details: None, + metadata: None, + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + } + } +} + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +impl OrganizationNew { + pub fn new(id: id_type::OrganizationId, organization_name: Option<String>) -> Self { + Self { + id, + organization_name, + organization_details: None, + metadata: None, + created_at: common_utils::date_time::now(), + modified_at: common_utils::date_time::now(), + } + } +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] #[derive(Clone, Debug, AsChangeset)] #[diesel(table_name = organization)] pub struct OrganizationUpdateInternal { org_name: Option<String>, + organization_name: Option<String>, + organization_details: Option<pii::SecretSerdeValue>, + metadata: Option<pii::SecretSerdeValue>, + modified_at: time::PrimitiveDateTime, +} + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +#[derive(Clone, Debug, AsChangeset)] +#[diesel(table_name = organization)] +pub struct OrganizationUpdateInternal { + organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, modified_at: time::PrimitiveDateTime, @@ -35,21 +191,44 @@ pub struct OrganizationUpdateInternal { pub enum OrganizationUpdate { Update { - org_name: Option<String>, + organization_name: Option<String>, organization_details: Option<pii::SecretSerdeValue>, metadata: Option<pii::SecretSerdeValue>, }, } +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] +impl From<OrganizationUpdate> for OrganizationUpdateInternal { + fn from(value: OrganizationUpdate) -> Self { + match value { + OrganizationUpdate::Update { + organization_name, + organization_details, + metadata, + } => Self { + org_name: organization_name.clone(), + organization_name, + organization_details, + metadata, + modified_at: common_utils::date_time::now(), + }, + } + } +} +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] + impl From<OrganizationUpdate> for OrganizationUpdateInternal { fn from(value: OrganizationUpdate) -> Self { match value { OrganizationUpdate::Update { - org_name, + organization_name, organization_details, metadata, } => Self { - org_name, + organization_name, organization_details, metadata, modified_at: common_utils::date_time::now(), @@ -57,3 +236,61 @@ impl From<OrganizationUpdate> for OrganizationUpdateInternal { } } } + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] +impl OrganizationBridge for Organization { + fn get_organization_id(&self) -> id_type::OrganizationId { + self.org_id.clone() + } + fn get_organization_name(&self) -> Option<String> { + self.org_name.clone() + } + fn set_organization_name(&mut self, organization_name: String) { + self.org_name = Some(organization_name); + } +} + +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] +impl OrganizationBridge for OrganizationNew { + fn get_organization_id(&self) -> id_type::OrganizationId { + self.org_id.clone() + } + fn get_organization_name(&self) -> Option<String> { + self.org_name.clone() + } + fn set_organization_name(&mut self, organization_name: String) { + self.org_name = Some(organization_name); + } +} + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +impl OrganizationBridge for Organization { + fn get_organization_id(&self) -> id_type::OrganizationId { + self.id.clone() + } + fn get_organization_name(&self) -> Option<String> { + self.organization_name.clone() + } + fn set_organization_name(&mut self, organization_name: String) { + self.organization_name = Some(organization_name); + } +} + +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +impl OrganizationBridge for OrganizationNew { + fn get_organization_id(&self) -> id_type::OrganizationId { + self.id.clone() + } + fn get_organization_name(&self) -> Option<String> { + self.organization_name.clone() + } + fn set_organization_name(&mut self, organization_name: String) { + self.organization_name = Some(organization_name); + } +} diff --git a/crates/diesel_models/src/query/organization.rs b/crates/diesel_models/src/query/organization.rs index 671f742d88c..c05445191b0 100644 --- a/crates/diesel_models/src/query/organization.rs +++ b/crates/diesel_models/src/query/organization.rs @@ -1,9 +1,14 @@ use common_utils::id_type; use diesel::{associations::HasTable, ExpressionMethods}; -use crate::{ - organization::*, query::generics, schema::organization::dsl, PgPooledConn, StorageResult, -}; +#[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") +))] +use crate::schema::organization::dsl; +#[cfg(all(feature = "v2", feature = "merchant_account_v2"))] +use crate::schema_v2::organization::dsl; +use crate::{organization::*, query::generics, PgPooledConn, StorageResult}; impl OrganizationNew { pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Organization> { @@ -16,8 +21,17 @@ impl Organization { conn: &PgPooledConn, org_id: id_type::OrganizationId, ) -> StorageResult<Self> { - generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, dsl::org_id.eq(org_id)) - .await + generics::generic_find_one::<<Self as HasTable>::Table, _, _>( + conn, + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] + dsl::org_id.eq(org_id), + #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] + dsl::id.eq(org_id), + ) + .await } pub async fn update_by_org_id( @@ -32,7 +46,13 @@ impl Organization { _, >( conn, + #[cfg(all( + any(feature = "v1", feature = "v2"), + not(feature = "merchant_account_v2") + ))] dsl::org_id.eq(org_id), + #[cfg(all(feature = "v2", feature = "merchant_account_v2"))] + dsl::id.eq(org_id), OrganizationUpdateInternal::from(update), ) .await diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index 185677c4c75..3077fd86f3f 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -730,6 +730,9 @@ diesel::table! { metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, + #[max_length = 32] + id -> Nullable<Varchar>, + organization_name -> Nullable<Text>, } } diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs index ca6a7208252..433284f4d7f 100644 --- a/crates/diesel_models/src/schema_v2.rs +++ b/crates/diesel_models/src/schema_v2.rs @@ -728,14 +728,14 @@ diesel::table! { use diesel::sql_types::*; use crate::enums::diesel_exports::*; - organization (org_id) { - #[max_length = 32] - org_id -> Varchar, - org_name -> Nullable<Text>, + organization (id) { organization_details -> Nullable<Jsonb>, metadata -> Nullable<Jsonb>, created_at -> Timestamp, modified_at -> Timestamp, + #[max_length = 32] + id -> Varchar, + organization_name -> Nullable<Text>, } } diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml index 93e5512222b..d02917148e0 100644 --- a/crates/drainer/Cargo.toml +++ b/crates/drainer/Cargo.toml @@ -10,7 +10,7 @@ license.workspace = true [features] release = ["vergen", "external_services/aws_kms"] vergen = ["router_env/vergen"] -v1 = ["diesel_models/v1"] +v1 = ["diesel_models/v1", "hyperswitch_interfaces/v1"] [dependencies] actix-web = "4.5.1" @@ -32,7 +32,7 @@ tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] } # First Party Crates common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals"] } -diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } +diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false } external_services = { version = "0.1.0", path = "../external_services" } hyperswitch_interfaces = { version = "0.1.0", path = "../hyperswitch_interfaces" } masking = { version = "0.1.0", path = "../masking" } diff --git a/crates/hyperswitch_domain_models/Cargo.toml b/crates/hyperswitch_domain_models/Cargo.toml index d10d72ab3ad..adbea0effb5 100644 --- a/crates/hyperswitch_domain_models/Cargo.toml +++ b/crates/hyperswitch_domain_models/Cargo.toml @@ -25,7 +25,7 @@ api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils", features = ["async_ext", "metrics", "encryption_service", "keymanager"] } -diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } +diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false } masking = { version = "0.1.0", path = "../masking" } router_derive = { version = "0.1.0", path = "../router_derive" } router_env = { version = "0.1.0", path = "../router_env" } diff --git a/crates/hyperswitch_interfaces/Cargo.toml b/crates/hyperswitch_interfaces/Cargo.toml index 7830415e5d8..887062d6255 100644 --- a/crates/hyperswitch_interfaces/Cargo.toml +++ b/crates/hyperswitch_interfaces/Cargo.toml @@ -9,6 +9,7 @@ license.workspace = true [features] default = ["dummy_connector", "frm", "payouts"] dummy_connector = [] +v1 = ["hyperswitch_domain_models/v1"] payouts = ["hyperswitch_domain_models/payouts"] frm = ["hyperswitch_domain_models/frm"] diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml index e01be51a68c..53842b38ab5 100644 --- a/crates/router/Cargo.toml +++ b/crates/router/Cargo.toml @@ -32,7 +32,7 @@ payout_retry = ["payouts"] recon = ["email", "api_models/recon"] retry = [] v2 = ["api_models/v2", "diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "kgraph_utils/v2"] -v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1"] +v1 = ["api_models/v1", "diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "hyperswitch_interfaces/v1"] customer_v2 = ["api_models/customer_v2", "diesel_models/customer_v2", "hyperswitch_domain_models/customer_v2"] merchant_account_v2 = ["api_models/merchant_account_v2", "diesel_models/merchant_account_v2", "hyperswitch_domain_models/merchant_account_v2"] payment_v2 = ["api_models/payment_v2", "diesel_models/payment_v2", "hyperswitch_domain_models/payment_v2"] @@ -118,13 +118,13 @@ x509-parser = "0.16.0" # First party crates -analytics = { version = "0.1.0", path = "../analytics", optional = true } +analytics = { version = "0.1.0", path = "../analytics", optional = true, default-features = false } api_models = { version = "0.1.0", path = "../api_models", features = ["errors"] } cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext", "logs", "metrics", "keymanager", "encryption_service"] } currency_conversion = { version = "0.1.0", path = "../currency_conversion" } -diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } +diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] , default-features = false } euclid = { version = "0.1.0", path = "../euclid", features = ["valued_jit"] } events = { version = "0.1.0", path = "../events" } external_services = { version = "0.1.0", path = "../external_services" } diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 3035e30b0bf..8e77aa95d10 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -12,6 +12,8 @@ use common_utils::{ types::keymanager::{self as km_types, KeyManagerState}, }; use diesel_models::configs; +#[cfg(all(any(feature = "v1", feature = "v2"), feature = "olap"))] +use diesel_models::organization::OrganizationBridge; use error_stack::{report, FutureExt, ResultExt}; use futures::future::try_join_all; use masking::{ExposeInterface, PeekInterface, Secret}; @@ -134,7 +136,7 @@ pub async fn update_organization( req: api::OrganizationRequest, ) -> RouterResponse<api::OrganizationResponse> { let organization_update = diesel_models::organization::OrganizationUpdate::Update { - org_name: req.organization_name, + organization_name: req.organization_name, organization_details: req.organization_details, metadata: req.metadata, }; @@ -387,7 +389,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { payout_routing_algorithm: self.payout_routing_algorithm, #[cfg(not(feature = "payouts"))] payout_routing_algorithm: None, - organization_id: organization.org_id, + organization_id: organization.get_organization_id(), is_recon_enabled: false, default_profile: None, recon_status: diesel_models::enums::ReconStatus::NotRequested, @@ -638,7 +640,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { }, )?; - CreateOrValidateOrganization::new(self.organization_id.clone()) + let organization = CreateOrValidateOrganization::new(self.organization_id.clone()) .create_or_validate(db) .await?; @@ -692,7 +694,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate { intent_fulfillment_time: None, frm_routing_algorithm: None, payout_routing_algorithm: None, - organization_id: self.organization_id, + organization_id: organization.get_organization_id(), is_recon_enabled: false, default_profile: None, recon_status: diesel_models::enums::ReconStatus::NotRequested, diff --git a/crates/router/src/db/organization.rs b/crates/router/src/db/organization.rs index 22e720d71df..bc79fdc0a06 100644 --- a/crates/router/src/db/organization.rs +++ b/crates/router/src/db/organization.rs @@ -1,5 +1,5 @@ use common_utils::{errors::CustomResult, id_type}; -use diesel_models::organization as storage; +use diesel_models::{organization as storage, organization::OrganizationBridge}; use error_stack::report; use router_env::{instrument, tracing}; @@ -73,21 +73,14 @@ impl OrganizationInterface for super::MockDb { if organizations .iter() - .any(|org| org.org_id == organization.org_id) + .any(|org| org.get_organization_id() == organization.get_organization_id()) { Err(errors::StorageError::DuplicateValue { entity: "org_id", key: None, })? } - let org = storage::Organization { - org_id: organization.org_id.clone(), - org_name: organization.org_name, - organization_details: organization.organization_details, - metadata: organization.metadata, - created_at: common_utils::date_time::now(), - modified_at: common_utils::date_time::now(), - }; + let org = storage::Organization::new(organization); organizations.push(org.clone()); Ok(org) } @@ -100,7 +93,7 @@ impl OrganizationInterface for super::MockDb { organizations .iter() - .find(|org| org.org_id == *org_id) + .find(|org| org.get_organization_id() == *org_id) .cloned() .ok_or( errors::StorageError::ValueNotFound(format!( @@ -120,18 +113,20 @@ impl OrganizationInterface for super::MockDb { organizations .iter_mut() - .find(|org| org.org_id == *org_id) + .find(|org| org.get_organization_id() == *org_id) .map(|org| match &update { storage::OrganizationUpdate::Update { - org_name, + organization_name, organization_details, metadata, - } => storage::Organization { - org_name: org_name.clone(), - organization_details: organization_details.clone(), - metadata: metadata.clone(), - ..org.to_owned() - }, + } => { + organization_name + .as_ref() + .map(|org_name| org.set_organization_name(org_name.to_owned())); + organization_details.clone_into(&mut org.organization_details); + metadata.clone_into(&mut org.metadata); + org + } }) .ok_or( errors::StorageError::ValueNotFound(format!( @@ -140,5 +135,6 @@ impl OrganizationInterface for super::MockDb { )) .into(), ) + .cloned() } } diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs index 9669b8326d9..acbca54f4b1 100644 --- a/crates/router/src/types/api/admin.rs +++ b/crates/router/src/types/api/admin.rs @@ -15,6 +15,7 @@ use common_utils::{ ext_traits::{AsyncExt, Encode, ValueExt}, types::keymanager::Identifier, }; +use diesel_models::organization::OrganizationBridge; use error_stack::{report, ResultExt}; use hyperswitch_domain_models::{ merchant_key_store::MerchantKeyStore, type_encryption::decrypt_optional, @@ -30,8 +31,8 @@ use crate::{ impl ForeignFrom<diesel_models::organization::Organization> for OrganizationResponse { fn foreign_from(org: diesel_models::organization::Organization) -> Self { Self { - organization_id: org.org_id, - organization_name: org.org_name, + organization_id: org.get_organization_id(), + organization_name: org.get_organization_name(), organization_details: org.organization_details, metadata: org.metadata, modified_at: org.modified_at, diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs index 8b973a8cf44..2de6bc44fb6 100644 --- a/crates/router/src/types/domain/user.rs +++ b/crates/router/src/types/domain/user.rs @@ -10,7 +10,7 @@ use common_utils::{ }; use diesel_models::{ enums::{TotpStatus, UserRoleVersion, UserStatus}, - organization::{self as diesel_org, Organization}, + organization::{self as diesel_org, Organization, OrganizationBridge}, user as storage_user, user_role::{UserRole, UserRoleNew}, }; @@ -254,7 +254,7 @@ impl NewUserOrganization { } pub fn get_organization_id(&self) -> id_type::OrganizationId { - self.0.org_id.clone() + self.0.get_organization_id() } } @@ -300,14 +300,10 @@ impl From<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for Ne impl From<UserMerchantCreateRequestWithToken> for NewUserOrganization { fn from(value: UserMerchantCreateRequestWithToken) -> Self { - Self(diesel_org::OrganizationNew { - org_id: value.2.org_id, - org_name: Some(value.1.company_name), - organization_details: None, - metadata: None, - created_at: common_utils::date_time::now(), - modified_at: common_utils::date_time::now(), - }) + Self(diesel_org::OrganizationNew::new( + value.2.org_id, + Some(value.1.company_name), + )) } } diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs index 11aebf5b98d..edc5b5e40d8 100644 --- a/crates/router/src/types/transformers.rs +++ b/crates/router/src/types/transformers.rs @@ -1389,14 +1389,7 @@ impl ForeignFrom<api_models::organization::OrganizationNew> for diesel_models::organization::OrganizationNew { fn foreign_from(item: api_models::organization::OrganizationNew) -> Self { - Self { - org_id: item.org_id, - org_name: item.org_name, - organization_details: None, - metadata: None, - created_at: common_utils::date_time::now(), - modified_at: common_utils::date_time::now(), - } + Self::new(item.org_id, item.org_name) } } @@ -1405,14 +1398,15 @@ impl ForeignFrom<api_models::organization::OrganizationRequest> { fn foreign_from(item: api_models::organization::OrganizationRequest) -> Self { let org_new = api_models::organization::OrganizationNew::new(None); - Self { - org_id: org_new.org_id, - org_name: item.organization_name, - organization_details: item.organization_details, - metadata: item.metadata, - created_at: common_utils::date_time::now(), - modified_at: common_utils::date_time::now(), - } + let api_models::organization::OrganizationRequest { + organization_name, + organization_details, + metadata, + } = item; + let mut org_new_db = Self::new(org_new.org_id, organization_name); + org_new_db.organization_details = organization_details; + org_new_db.metadata = metadata; + org_new_db } } diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.toml index 25a297a8bc8..e9628869088 100644 --- a/crates/scheduler/Cargo.toml +++ b/crates/scheduler/Cargo.toml @@ -30,7 +30,7 @@ uuid = { version = "1.8.0", features = ["v4"] } # First party crates common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext"] } -diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"] } +diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false } external_services = { version = "0.1.0", path = "../external_services" } hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } redis_interface = { version = "0.1.0", path = "../redis_interface" } diff --git a/crates/storage_impl/Cargo.toml b/crates/storage_impl/Cargo.toml index d42f64931ff..386f442db6e 100644 --- a/crates/storage_impl/Cargo.toml +++ b/crates/storage_impl/Cargo.toml @@ -21,7 +21,7 @@ payment_v2 = ["hyperswitch_domain_models/payment_v2", "diesel_models/payment_v2" api_models = { version = "0.1.0", path = "../api_models" } common_enums = { version = "0.1.0", path = "../common_enums" } common_utils = { version = "0.1.0", path = "../common_utils" } -diesel_models = { version = "0.1.0", path = "../diesel_models" } +diesel_models = { version = "0.1.0", path = "../diesel_models", default-features = false } hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } masking = { version = "0.1.0", path = "../masking" } redis_interface = { version = "0.1.0", path = "../redis_interface" } diff --git a/migrations/2024-07-29-062548_add-organization_name-and-id-fields-in-organization/down.sql b/migrations/2024-07-29-062548_add-organization_name-and-id-fields-in-organization/down.sql new file mode 100644 index 00000000000..d6c99615aea --- /dev/null +++ b/migrations/2024-07-29-062548_add-organization_name-and-id-fields-in-organization/down.sql @@ -0,0 +1,5 @@ +-- This file should undo anything in `up.sql` +ALTER TABLE organization +DROP COLUMN id; +ALTER TABLE organization +DROP COLUMN organization_name; \ No newline at end of file diff --git a/migrations/2024-07-29-062548_add-organization_name-and-id-fields-in-organization/up.sql b/migrations/2024-07-29-062548_add-organization_name-and-id-fields-in-organization/up.sql new file mode 100644 index 00000000000..81d8cf44c9c --- /dev/null +++ b/migrations/2024-07-29-062548_add-organization_name-and-id-fields-in-organization/up.sql @@ -0,0 +1,6 @@ +-- Your SQL goes here +ALTER TABLE organization +ADD COLUMN id VARCHAR(32); +ALTER TABLE organization +ADD COLUMN organization_name TEXT; + \ No newline at end of file diff --git a/v2_migrations/2024-07-29-063217_drop-org_id-and-org_name-from-organization/down.sql b/v2_migrations/2024-07-29-063217_drop-org_id-and-org_name-from-organization/down.sql new file mode 100644 index 00000000000..a41a6c32bef --- /dev/null +++ b/v2_migrations/2024-07-29-063217_drop-org_id-and-org_name-from-organization/down.sql @@ -0,0 +1,22 @@ +-- Alter queries +ALTER TABLE organization +ADD COLUMN org_id VARCHAR(32); + +ALTER TABLE organization +ADD COLUMN org_name TEXT; + +-- back fill +UPDATE organization +SET org_id = id +WHERE org_id is NULL; + +ALTER TABLE organization +DROP CONSTRAINT organization_pkey_id; + +ALTER TABLE organization +ADD CONSTRAINT organization_pkey PRIMARY KEY (org_id); + +-- back fill +UPDATE organization +SET org_name = organization_name +WHERE org_name IS NULL AND organization_name IS NOT NULL; \ No newline at end of file diff --git a/v2_migrations/2024-07-29-063217_drop-org_id-and-org_name-from-organization/up.sql b/v2_migrations/2024-07-29-063217_drop-org_id-and-org_name-from-organization/up.sql new file mode 100644 index 00000000000..3ae4a3c3d34 --- /dev/null +++ b/v2_migrations/2024-07-29-063217_drop-org_id-and-org_name-from-organization/up.sql @@ -0,0 +1,18 @@ +-- Backfill +UPDATE organization +SET id = org_id +WHERE id is NULL; + +UPDATE organization +SET organization_name = org_name +WHERE organization_name IS NULL AND org_name IS NOT NULL; + +-- Alter queries +ALTER TABLE organization +DROP COLUMN org_id; + +ALTER TABLE organization +DROP COLUMN org_name; + +ALTER TABLE organization +ADD CONSTRAINT organization_pkey_id PRIMARY KEY (id); \ No newline at end of file
feat
rename columns in organization for v2 (#5424)
bb593ab0cd1a30190b6c305f2432de83ac7fde93
2023-11-29 13:42:36
chikke srujan
fix: remove `dummy_connector` from `default` features in `common_enums` (#3005)
false
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml index 73c2d673c97..cb2e243745d 100644 --- a/crates/api_models/Cargo.toml +++ b/crates/api_models/Cargo.toml @@ -14,7 +14,7 @@ connector_choice_bcompat = [] errors = ["dep:actix-web", "dep:reqwest"] backwards_compatibility = ["connector_choice_bcompat"] connector_choice_mca_id = ["euclid/connector_choice_mca_id"] -dummy_connector = ["euclid/dummy_connector"] +dummy_connector = ["euclid/dummy_connector", "common_enums/dummy_connector"] detailed_errors = [] payouts = [] diff --git a/crates/common_enums/Cargo.toml b/crates/common_enums/Cargo.toml index cd061970bff..72d9f6bb0bb 100644 --- a/crates/common_enums/Cargo.toml +++ b/crates/common_enums/Cargo.toml @@ -8,7 +8,6 @@ readme = "README.md" license.workspace = true [features] -default = ["dummy_connector"] dummy_connector = [] [dependencies]
fix
remove `dummy_connector` from `default` features in `common_enums` (#3005)
3854d58270937ac4d2e5901eeb215bc19fffc838
2023-10-10 19:31:58
Shankar Singh C
ci(create-hotfix-tag): exit workflow on an error (#2536)
false
diff --git a/.github/workflows/create-hotfix-tag.yml b/.github/workflows/create-hotfix-tag.yml index 378f4d71de0..45699bda24d 100644 --- a/.github/workflows/create-hotfix-tag.yml +++ b/.github/workflows/create-hotfix-tag.yml @@ -24,9 +24,10 @@ jobs: shell: bash run: | if [[ ${{github.ref}} =~ ^refs/heads/hotfix-[0-9]+\.[0-9]+\.[0-9]+$ ]]; then - echo "::notice::${{github.ref}} is a valid branch." + echo "::notice::${{github.ref}} is a valid branch." else - echo "::error::${{github.ref}} is not a valid branch." + echo "::error::${{github.ref}} is not a valid branch." + exit 1 fi - name: Check if the latest commit is tag @@ -36,6 +37,7 @@ jobs: echo "::notice::The latest commit is not a tag " else echo "::error::The latest commit on the branch is already a tag" + exit 1 fi - name: Determine current and next tag
ci
exit workflow on an error (#2536)
94cd7b689758a71e13a3eaa655335e658d13afc8
2024-01-31 17:30:02
Pritish Budhiraja
feat(dashboard_metadata): Add email alert for Prod Intent (#3482)
false
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs index c570aca7603..1cda969f780 100644 --- a/crates/router/src/consts/user.rs +++ b/crates/router/src/consts/user.rs @@ -1,2 +1,3 @@ pub const MAX_NAME_LENGTH: usize = 70; pub const MAX_COMPANY_NAME_LENGTH: usize = 70; +pub const BUSINESS_EMAIL: &str = "[email protected]"; diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs index b537aa3ec73..24ff292870e 100644 --- a/crates/router/src/core/user/dashboard_metadata.rs +++ b/crates/router/src/core/user/dashboard_metadata.rs @@ -3,7 +3,11 @@ use diesel_models::{ enums::DashboardMetadata as DBEnum, user::dashboard_metadata::DashboardMetadata, }; use error_stack::ResultExt; +#[cfg(feature = "email")] +use router_env::logger; +#[cfg(feature = "email")] +use crate::services::email::types as email_types; use crate::{ core::errors::{UserErrors, UserResponse, UserResult}, routes::AppState, @@ -434,15 +438,31 @@ async fn insert_metadata( if utils::is_update_required(&metadata) { metadata = utils::update_user_scoped_metadata( state, - user.user_id, + user.user_id.clone(), user.merchant_id, user.org_id, metadata_key, - data, + data.clone(), ) .await .change_context(UserErrors::InternalServerError); } + + #[cfg(feature = "email")] + { + if utils::is_prod_email_required(&data) { + let email_contents = email_types::BizEmailProd::new(state, data)?; + let send_email_result = state + .email_client + .compose_and_send_email( + Box::new(email_contents), + state.conf.proxy.https_url.as_ref(), + ) + .await; + logger::info!(?send_email_result); + } + } + metadata } types::MetaData::SPTestPayment(data) => { diff --git a/crates/router/src/services/email/assets/bizemailprod.html b/crates/router/src/services/email/assets/bizemailprod.html new file mode 100644 index 00000000000..c705608ec72 --- /dev/null +++ b/crates/router/src/services/email/assets/bizemailprod.html @@ -0,0 +1,138 @@ +<meta content="text/html; charset=UTF-8" http-equiv="Content-Type" /> +<title>Welcome to HyperSwitch!</title> +<body style="background-color: #ececec"> + <div + id="wrapper" + style=" + background-color: none; + margin: 0 auto; + text-align: center; + width: 90%; + -premailer-height: 200; + " + > + <table + align="center" + class="main-table" + style=" + -premailer-cellpadding: 0; + -premailer-cellspacing: 0; + background-color: #fff; + border: 0; + border-top: 5px solid #0165ef; + margin: 0 auto; + mso-table-lspace: 0; + mso-table-rspace: 0; + padding: 0 40; + text-align: center; + width: 100%; + " + bgcolor="#ffffff" + cellpadding="0" + cellspacing="0" + > + <tr> + <td + class="spacer-sm" + style=" + -premailer-height: 20; + -premailer-width: 80%; + line-height: 10px; + margin: 0 auto; + padding: 0; + " + width="100%" + ></td> + </tr> + <tr> + <td + class="spacer-sm" + style=" + -premailer-height: 20; + -premailer-width: 80%; + line-height: 10px; + margin: 0 auto; + padding: 0; + " + width="100%" + ></td> + </tr> + <tr> + <td + class="copy" + style=" + color: #666; + font-family: Roboto, Helvetica, Arial, san-serif; + font-size: 14px; + text-align: left; + line-height: 20px; + margin-top: 20px; + padding: 15px; + " + > + <br /> + <p>Hi Team,</p> + <p> + A Production Account Intent has been initiated by {username} - + please find more details below: + </p> + <ol> + <li><strong>Name:</strong> {username}</li> + <li><strong>Point of Contact Email (POC):</strong> {poc_email}</li> + <li><strong>Legal Business Name:</strong> {legal_business_name}</li> + <li><strong>Business Location:</strong> {business_location}</li> + <li><strong>Business Website:</strong> {business_website}</li> + </ol> + <br /> + </td> + </tr> + <tr> + <td + class="spacer-sm" + style=" + -premailer-height: 20; + -premailer-width: 80%; + line-height: 10px; + margin: 0 auto; + padding: 0; + " + width="100%" + ></td> + </tr> + + <tr> + <td + class="headline" + style=" + color: #444; + font-family: Roboto, Helvetica, Arial, san-serif; + font-size: 18px; + font-weight: 100; + line-height: 36px; + margin: 0 auto; + padding: 0; + text-align: center; + " + align="center" + > + Regards,<br /> + Hyperswitch Dashboard Team + </td> + </tr> + <tr> + <td + class="spacer-lg" + style=" + -premailer-height: 75; + -premailer-width: 100%; + line-height: 30px; + margin: 0 auto; + padding: 0; + " + height="75" + width="100%" + ></td> + </tr> + </table> + </div> +</body> diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs index c68907c2846..6ad1a0eb99a 100644 --- a/crates/router/src/services/email/types.rs +++ b/crates/router/src/services/email/types.rs @@ -1,11 +1,16 @@ +use api_models::user::dashboard_metadata::ProdIntent; use common_utils::errors::CustomResult; use error_stack::ResultExt; use external_services::email::{EmailContents, EmailData, EmailError}; -use masking::{ExposeInterface, PeekInterface}; +use masking::{ExposeInterface, PeekInterface, Secret}; -use crate::{configs, consts}; +use crate::{configs, consts, routes::AppState}; #[cfg(feature = "olap")] -use crate::{core::errors::UserErrors, services::jwt, types::domain}; +use crate::{ + core::errors::{UserErrors, UserResult}, + services::jwt, + types::domain, +}; pub enum EmailBody { Verify { @@ -23,6 +28,13 @@ pub enum EmailBody { link: String, user_name: String, }, + BizEmailProd { + user_name: String, + poc_email: String, + legal_business_name: String, + business_location: String, + business_website: String, + }, ReconActivation { user_name: String, }, @@ -69,6 +81,22 @@ pub mod html { username = user_name, ) } + EmailBody::BizEmailProd { + user_name, + poc_email, + legal_business_name, + business_location, + business_website, + } => { + format!( + include_str!("assets/bizemailprod.html"), + poc_email = poc_email, + legal_business_name = legal_business_name, + business_location = business_location, + business_website = business_website, + username = user_name, + ) + } EmailBody::ProFeatureRequest { feature_name, merchant_id, @@ -275,6 +303,56 @@ impl EmailData for ReconActivation { } } +pub struct BizEmailProd { + pub recipient_email: domain::UserEmail, + pub user_name: Secret<String>, + pub poc_email: Secret<String>, + pub legal_business_name: String, + pub business_location: String, + pub business_website: String, + pub settings: std::sync::Arc<configs::settings::Settings>, + pub subject: &'static str, +} + +impl BizEmailProd { + pub fn new(state: &AppState, data: ProdIntent) -> UserResult<Self> { + Ok(Self { + recipient_email: (domain::UserEmail::new( + consts::user::BUSINESS_EMAIL.to_string().into(), + ))?, + settings: state.conf.clone(), + subject: "New Prod Intent", + user_name: data.poc_name.unwrap_or_default().into(), + poc_email: data.poc_email.unwrap_or_default().into(), + legal_business_name: data.legal_business_name.unwrap_or_default(), + business_location: data + .business_location + .unwrap_or(common_enums::CountryAlpha2::AD) + .to_string(), + business_website: data.business_website.unwrap_or_default(), + }) + } +} + +#[async_trait::async_trait] +impl EmailData for BizEmailProd { + async fn get_email_data(&self) -> CustomResult<EmailContents, EmailError> { + let body = html::get_html_body(EmailBody::BizEmailProd { + user_name: self.user_name.clone().expose(), + poc_email: self.poc_email.clone().expose(), + legal_business_name: self.legal_business_name.clone(), + business_location: self.business_location.clone(), + business_website: self.business_website.clone(), + }); + + Ok(EmailContents { + subject: self.subject.to_string(), + body: external_services::email::IntermediateString::new(body), + recipient: self.recipient_email.clone().into_inner(), + }) + } +} + pub struct ProFeatureRequest { pub recipient_email: domain::UserEmail, pub feature_name: String, diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs index 09fb5ccd24b..bcf270010ea 100644 --- a/crates/router/src/utils/user/dashboard_metadata.rs +++ b/crates/router/src/utils/user/dashboard_metadata.rs @@ -2,7 +2,7 @@ use std::{net::IpAddr, str::FromStr}; use actix_web::http::header::HeaderMap; use api_models::user::dashboard_metadata::{ - GetMetaDataRequest, GetMultipleMetaDataPayload, SetMetaDataRequest, + GetMetaDataRequest, GetMultipleMetaDataPayload, ProdIntent, SetMetaDataRequest, }; use diesel_models::{ enums::DashboardMetadata as DBEnum, @@ -276,3 +276,10 @@ pub fn parse_string_to_enums(query: String) -> UserResult<GetMultipleMetaDataPay .attach_printable("Error Parsing to DashboardMetadata enums")?, }) } + +pub fn is_prod_email_required(data: &ProdIntent) -> bool { + !(data + .poc_email + .as_ref() + .map_or(true, |mail| mail.contains("juspay"))) +}
feat
Add email alert for Prod Intent (#3482)
5cb4f2e137a4a3527a08b93e08d2fc983aa5c7ba
2024-03-06 05:49:12
github-actions
chore(version): 2024.03.06.0
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 0d19ed47c70..2aa1ce09f85 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,38 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.03.06.0 + +### Features + +- **api_models:** Add api_models for external 3ds authentication flow ([#3858](https://github.com/juspay/hyperswitch/pull/3858)) ([`0a43ceb`](https://github.com/juspay/hyperswitch/commit/0a43ceb14e27d998794941ecb7605b9e7175c757)) +- **connector:** [Checkout] accept connector_transaction_id in 2xx and 4xx error_response of connector flows ([#3959](https://github.com/juspay/hyperswitch/pull/3959)) ([`f6f6a0c`](https://github.com/juspay/hyperswitch/commit/f6f6a0c0f727a6f367c6bafb4db9a89cb46f667a)) +- **core:** External authentication related schema changes for existing tables ([#3904](https://github.com/juspay/hyperswitch/pull/3904)) ([`c09b2b3`](https://github.com/juspay/hyperswitch/commit/c09b2b3a2ae9a71d4a73063faf4796e0c8732bb4)) +- **payouts:** Implement Single Connector Retry for Payouts ([#3908](https://github.com/juspay/hyperswitch/pull/3908)) ([`0cb95a4`](https://github.com/juspay/hyperswitch/commit/0cb95a4911054e089e6ed3c528645ee1b881ebc6)) +- **roles:** Add caching for custom roles ([#3946](https://github.com/juspay/hyperswitch/pull/3946)) ([`19c5023`](https://github.com/juspay/hyperswitch/commit/19c502398f980d20b9e0a4fe98c33a2239c90c5b)) +- **router:** Add incoming header request logs ([#3939](https://github.com/juspay/hyperswitch/pull/3939)) ([`050df50`](https://github.com/juspay/hyperswitch/commit/050df5022cd3d44db23ca75f81158fb7c2429f86)) + +### Bug Fixes + +- **core:** Fix metadata validation for update payment connector ([#3834](https://github.com/juspay/hyperswitch/pull/3834)) ([`54938ad`](https://github.com/juspay/hyperswitch/commit/54938ad345a2b899360b608d8845fd7f885f82ba)) +- **router:** [nuvei] Nuvei error handling for payment declined status and included tests ([#3832](https://github.com/juspay/hyperswitch/pull/3832)) ([`087932f`](https://github.com/juspay/hyperswitch/commit/087932f06044454570c971def0e82dc3d838598c)) + +### Refactors + +- **connector:** + - [Fiserv] Mask PII data ([#3821](https://github.com/juspay/hyperswitch/pull/3821)) ([`03cfb73`](https://github.com/juspay/hyperswitch/commit/03cfb735af29f00bccf729013e7e06684611b30d)) + - Remove default cases for Authorizedotnet, Braintree and Fiserv Connector ([#2796](https://github.com/juspay/hyperswitch/pull/2796)) ([`dbac556`](https://github.com/juspay/hyperswitch/commit/dbac55683a8f95e0efdbac43f8c2ae793063a032)) + +### Miscellaneous Tasks + +- **configs:** [BOA] Add USD Currency Filter Configuration ([#3961](https://github.com/juspay/hyperswitch/pull/3961)) ([`8a0e468`](https://github.com/juspay/hyperswitch/commit/8a0e468e6a574717b29ccbdd143908727c251dfb)) +- **postman:** Update Postman collection files ([`6305bb5`](https://github.com/juspay/hyperswitch/commit/6305bb57269fb5f6803edbad58d6e574ad4f6509)) +- **tests:** Add unit tests for backwards compatibility ([#3822](https://github.com/juspay/hyperswitch/pull/3822)) ([`c65729a`](https://github.com/juspay/hyperswitch/commit/c65729adc9009f046398312a16841532fdc177da)) + +**Full Changelog:** [`2024.03.05.0...2024.03.06.0`](https://github.com/juspay/hyperswitch/compare/2024.03.05.0...2024.03.06.0) + +- - - + ## 2024.03.05.0 ### Features
chore
2024.03.06.0
b42052269455051fe15163217ee83d80a1470f84
2024-06-12 16:50:56
Amisha Prabhat
fix(core): fix the multitenancy prefix in routing cache (#4963)
false
diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rs index 4a92dbbc814..f732f8a7926 100644 --- a/crates/router/src/core/payment_methods/utils.rs +++ b/crates/router/src/core/payment_methods/utils.rs @@ -45,7 +45,7 @@ pub async fn get_merchant_pm_filter_graph<'a>( .get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<'_, dir::DirValue>>>( CacheKey { key: key.to_string(), - prefix: state.tenant.clone(), + prefix: state.tenant.redis_key_prefix.clone(), }, ) .await @@ -61,7 +61,7 @@ pub async fn refresh_pm_filters_cache( .push( CacheKey { key: key.to_string(), - prefix: state.tenant.clone(), + prefix: state.tenant.redis_key_prefix.clone(), }, pm_filter_graph.clone(), ) diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs index 15eda58c913..fa64d9882d2 100644 --- a/crates/router/src/core/payments/routing.rs +++ b/crates/router/src/core/payments/routing.rs @@ -368,7 +368,7 @@ async fn ensure_algorithm_cached_v1( let cached_algorithm = ROUTING_CACHE .get_val::<Arc<CachedAlgorithm>>(CacheKey { key: key.clone(), - prefix: state.tenant.clone(), + prefix: state.tenant.redis_key_prefix.clone(), }) .await; @@ -490,7 +490,7 @@ pub async fn refresh_routing_cache_v1( .push( CacheKey { key, - prefix: state.tenant.clone(), + prefix: state.tenant.redis_key_prefix.clone(), }, arc_cached_algorithm.clone(), ) @@ -567,7 +567,7 @@ pub async fn get_merchant_cgraph<'a>( .get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<'_, euclid_dir::DirValue>>>( CacheKey { key: key.clone(), - prefix: state.tenant.clone(), + prefix: state.tenant.redis_key_prefix.clone(), }, ) .await; @@ -668,7 +668,7 @@ pub async fn refresh_cgraph_cache<'a>( .push( CacheKey { key, - prefix: state.tenant.clone(), + prefix: state.tenant.redis_key_prefix.clone(), }, Arc::clone(&cgraph), ) diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs index 8d88d9c4b26..92ca3c264fe 100644 --- a/crates/router/src/routes/app.rs +++ b/crates/router/src/routes/app.rs @@ -18,6 +18,7 @@ use scheduler::SchedulerInterface; use storage_impl::{config::TenantConfig, redis::RedisStore, MockDb}; use tokio::sync::oneshot; +use self::settings::Tenant; #[cfg(feature = "olap")] use super::blocklist; #[cfg(feature = "dummy_connector")] @@ -85,7 +86,7 @@ pub struct SessionState { pub file_storage_client: Arc<dyn FileStorageInterface>, pub request_id: Option<RequestId>, pub base_url: String, - pub tenant: String, + pub tenant: Tenant, #[cfg(feature = "olap")] pub opensearch_client: Arc<OpenSearchClient>, } @@ -380,6 +381,7 @@ impl AppState { where F: FnOnce() -> E + Copy, { + let tenant_conf = self.conf.multitenancy.get_tenant(tenant).ok_or_else(err)?; Ok(SessionState { store: self.stores.get(tenant).ok_or_else(err)?.clone(), global_store: self.global_store.clone(), @@ -390,15 +392,8 @@ impl AppState { pool: self.pools.get(tenant).ok_or_else(err)?.clone(), file_storage_client: self.file_storage_client.clone(), request_id: self.request_id, - base_url: self - .conf - .multitenancy - .get_tenant(tenant) - .ok_or_else(err)? - .clone() - .base_url - .clone(), - tenant: tenant.to_string().clone(), + base_url: tenant_conf.base_url.clone(), + tenant: tenant_conf.clone(), #[cfg(feature = "email")] email_client: Arc::clone(&self.email_client), #[cfg(feature = "olap")]
fix
fix the multitenancy prefix in routing cache (#4963)
e9bd345464f28133aeaab638c33b77f31dd1fcb5
2024-08-02 18:58:51
Sarthak Soni
fix(pm_auth): Added mca status check in pml (#5421)
false
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs index 8cb64d1e0d8..b919541adef 100644 --- a/crates/router/src/core/payment_methods/cards.rs +++ b/crates/router/src/core/payment_methods/cards.rs @@ -2356,7 +2356,8 @@ pub async fn list_payment_methods( .await?; // filter out connectors based on the business country - let filtered_mcas = helpers::filter_mca_based_on_business_profile(all_mcas, profile_id.clone()); + let filtered_mcas = + helpers::filter_mca_based_on_business_profile(all_mcas.clone(), profile_id.clone()); logger::debug!(mca_before_filtering=?filtered_mcas); @@ -2663,33 +2664,34 @@ pub async fn list_payment_methods( }); if let Some(config) = pm_auth_config { - config - .enabled_payment_methods - .iter() - .for_each(|inner_config| { - if inner_config.payment_method_type == *payment_method_type { - let pm = pmt_to_auth_connector - .get(&inner_config.payment_method) - .cloned(); - - let inner_map = if let Some(mut inner_map) = pm { - inner_map.insert( - *payment_method_type, - inner_config.connector_name.clone(), - ); - inner_map - } else { - HashMap::from([( - *payment_method_type, - inner_config.connector_name.clone(), - )]) - }; - - pmt_to_auth_connector - .insert(inner_config.payment_method, inner_map); - val.push(inner_config.clone()); - } - }); + for inner_config in config.enabled_payment_methods.iter() { + let is_active_mca = all_mcas + .iter() + .any(|mca| mca.merchant_connector_id == inner_config.mca_id); + + if inner_config.payment_method_type == *payment_method_type && is_active_mca + { + let pm = pmt_to_auth_connector + .get(&inner_config.payment_method) + .cloned(); + + let inner_map = if let Some(mut inner_map) = pm { + inner_map.insert( + *payment_method_type, + inner_config.connector_name.clone(), + ); + inner_map + } else { + HashMap::from([( + *payment_method_type, + inner_config.connector_name.clone(), + )]) + }; + + pmt_to_auth_connector.insert(inner_config.payment_method, inner_map); + val.push(inner_config.clone()); + } + } }; } }
fix
Added mca status check in pml (#5421)
4c2e97273ab07917477ce016f7f04400e7e5df9a
2024-04-14 22:56:04
Swangi Kumari
refactor(router): change stack size (#4355)
false
diff --git a/crates/router/build.rs b/crates/router/build.rs index 99d6de0fda4..b33c168833d 100644 --- a/crates/router/build.rs +++ b/crates/router/build.rs @@ -2,7 +2,7 @@ fn main() { // Set thread stack size to 8 MiB for debug builds // Reference: https://doc.rust-lang.org/std/thread/#stack-size #[cfg(debug_assertions)] - println!("cargo:rustc-env=RUST_MIN_STACK=18388608"); // 8 * 1024 * 1024 = 8 MiB + println!("cargo:rustc-env=RUST_MIN_STACK=8388608"); // 8 * 1024 * 1024 = 8 MiB #[cfg(feature = "vergen")] router_env::vergen::generate_cargo_instructions();
refactor
change stack size (#4355)
0302c3033fbff4bfbdb18df44fabc3513b063fb0
2024-11-20 01:07:36
Sandeep Kumar
fix(analytics): fix `authentication_type` and `card_last_4` fields serialization for payment_intent_filters (#6595)
false
diff --git a/crates/api_models/src/analytics/payment_intents.rs b/crates/api_models/src/analytics/payment_intents.rs index dd51c97d935..365abd71edc 100644 --- a/crates/api_models/src/analytics/payment_intents.rs +++ b/crates/api_models/src/analytics/payment_intents.rs @@ -63,11 +63,15 @@ pub enum PaymentIntentDimensions { Currency, ProfileId, Connector, + #[strum(serialize = "authentication_type")] + #[serde(rename = "authentication_type")] AuthType, PaymentMethod, PaymentMethodType, CardNetwork, MerchantId, + #[strum(serialize = "card_last_4")] + #[serde(rename = "card_last_4")] CardLast4, CardIssuer, ErrorReason,
fix
fix `authentication_type` and `card_last_4` fields serialization for payment_intent_filters (#6595)
ef0df7195d9a7c7cd384f6df9eb5a8b886914e2d
2023-09-26 13:41:15
Sai Harsha Vardhan
fix(router): fix refunds and payment_attempts kv flow (#2362)
false
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index cb7a46dfb45..67980730f8f 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -629,13 +629,9 @@ mod storage { } 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_refund(&lookup.sk_id); - self.get_redis_conn() .map_err(Into::<errors::StorageError>::into)? - .hscan_and_deserialize(&key, &pattern, None) + .hscan_and_deserialize(&key, "pa_*_ref_*", None) .await .change_context(errors::StorageError::KVError) } diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index 84e119fd7c1..f99a23ba539 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -29,10 +29,7 @@ use crate::{ diesel_error_to_data_error, 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, - }, + utils::{pg_connection_read, pg_connection_write, try_redis_get_else_try_database_get}, DataModelExt, DatabaseStore, KVRouterStore, RouterStore, }; @@ -800,16 +797,13 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> { } 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) + .hscan_and_deserialize(&key, "pa_*", None) .await .change_context(errors::StorageError::KVError) } diff --git a/crates/storage_impl/src/utils.rs b/crates/storage_impl/src/utils.rs index 92fd11debe8..6d6e1cd5402 100644 --- a/crates/storage_impl/src/utils.rs +++ b/crates/storage_impl/src/utils.rs @@ -68,13 +68,3 @@ 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("_") -}
fix
fix refunds and payment_attempts kv flow (#2362)
5535159d5c2cc7278c9e189dcf3629efd67e6fb5
2023-06-14 17:43:27
Arjun Karthik
feat(connector): mask pii information in connector request and response for stripe, bluesnap, checkout, zen (#1435)
false
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs index 944f9cc3d3d..edc72b08228 100644 --- a/crates/router/src/connector/bluesnap/transformers.rs +++ b/crates/router/src/connector/bluesnap/transformers.rs @@ -10,7 +10,9 @@ use masking::ExposeInterface; use serde::{Deserialize, Serialize}; use crate::{ - connector::utils::{self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData}, + connector::utils::{ + self, AddressDetailsData, ApplePay, PaymentsAuthorizeRequestData, RouterData, + }, consts, core::errors, pii::Secret, @@ -80,7 +82,7 @@ pub struct Card { #[serde(rename_all = "camelCase")] pub struct BluesnapWallet { wallet_type: BluesnapWalletTypes, - encoded_payment_token: String, + encoded_payment_token: Secret<String>, } #[derive(Debug, Serialize)] @@ -182,21 +184,22 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BluesnapPaymentsRequest { Ok(( PaymentMethodDetails::Wallet(BluesnapWallet { wallet_type: BluesnapWalletTypes::GooglePay, - encoded_payment_token: consts::BASE64_ENGINE.encode(gpay_object), + encoded_payment_token: Secret::new( + consts::BASE64_ENGINE.encode(gpay_object), + ), }), None, )) } api_models::payments::WalletData::ApplePay(payment_method_data) => { - let apple_pay_payment_data = consts::BASE64_ENGINE - .decode(payment_method_data.payment_data) - .into_report() - .change_context(errors::ConnectorError::ParsingFailed)?; - + let apple_pay_payment_data = payment_method_data + .get_applepay_decoded_payment_data() + .change_context(errors::ConnectorError::RequestEncodingFailed)?; let apple_pay_payment_data: ApplePayEncodedPaymentData = apple_pay_payment_data - [..] + .expose()[..] + .as_bytes() .parse_struct("ApplePayEncodedPaymentData") - .change_context(errors::ConnectorError::ParsingFailed)?; + .change_context(errors::ConnectorError::RequestEncodingFailed)?; let billing = item .address @@ -249,7 +252,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BluesnapPaymentsRequest { Ok(( PaymentMethodDetails::Wallet(BluesnapWallet { wallet_type: BluesnapWalletTypes::ApplePay, - encoded_payment_token: consts::BASE64_ENGINE.encode(apple_pay_object), + encoded_payment_token: Secret::new( + consts::BASE64_ENGINE.encode(apple_pay_object), + ), }), None, )) @@ -528,7 +533,7 @@ impl TryFrom<&types::ConnectorCustomerRouterData> for BluesnapCustomerRequest { #[derive(Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BluesnapCustomerResponse { - vaulted_shopper_id: u64, + vaulted_shopper_id: Secret<u64>, } impl<F, T> TryFrom<types::ResponseRouterData<F, BluesnapCustomerResponse, T, types::PaymentsResponseData>> @@ -545,7 +550,7 @@ impl<F, T> ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::PaymentsResponseData::ConnectorCustomerResponse { - connector_customer_id: item.response.vaulted_shopper_id.to_string(), + connector_customer_id: item.response.vaulted_shopper_id.expose().to_string(), }), ..item.data }) @@ -636,7 +641,7 @@ pub struct Refund { pub struct ProcessingInfoResponse { processing_status: BluesnapProcessingStatus, authorization_code: Option<String>, - network_transaction_id: Option<String>, + network_transaction_id: Option<Secret<String>>, } impl<F, T> diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/router/src/connector/checkout/transformers.rs index 35b599717ea..9f58c3d439e 100644 --- a/crates/router/src/connector/checkout/transformers.rs +++ b/crates/router/src/connector/checkout/transformers.rs @@ -1,5 +1,6 @@ use common_utils::errors::CustomResult; use error_stack::{IntoReport, ResultExt}; +use masking::ExposeInterface; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use url::Url; @@ -73,7 +74,7 @@ impl TryFrom<&types::TokenizationRouterData> for TokenRequest { #[derive(Debug, Eq, PartialEq, Deserialize)] pub struct CheckoutTokenResponse { - token: String, + token: pii::Secret<String>, } impl<F, T> @@ -86,7 +87,7 @@ impl<F, T> ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(types::PaymentsResponseData::TokenizationResponse { - token: item.response.token, + token: item.response.token.expose(), }), ..item.data }) diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index 221130ed8bf..22b37abe7b8 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1,7 +1,6 @@ use std::ops::Deref; use api_models::{self, enums as api_enums, payments}; -use base64::Engine; use common_utils::{ errors::CustomResult, ext_traits::{ByteSliceExt, BytesExt}, @@ -15,7 +14,11 @@ use url::Url; use uuid::Uuid; use crate::{ - collect_missing_value_keys, connector, consts, + collect_missing_value_keys, + connector::{ + self, + utils::{ApplePay, RouterData}, + }, core::errors, services, types::{self, api, storage::enums, transformers::ForeignFrom}, @@ -99,9 +102,9 @@ pub struct PaymentIntentRequest { pub metadata_txn_uuid: String, pub return_url: String, pub confirm: bool, - pub mandate: Option<String>, + pub mandate: Option<Secret<String>>, pub payment_method: Option<String>, - pub customer: Option<String>, + pub customer: Option<Secret<String>>, #[serde(flatten)] pub setup_mandate_details: Option<StripeMandateRequest>, pub description: Option<String>, @@ -127,7 +130,7 @@ pub struct SetupIntentRequest { pub metadata_txn_uuid: String, pub confirm: bool, pub usage: Option<enums::FutureUsage>, - pub customer: Option<String>, + pub customer: Option<Secret<String>>, pub off_session: Option<bool>, pub return_url: Option<String>, #[serde(flatten)] @@ -177,7 +180,7 @@ pub struct CustomerRequest { pub description: Option<String>, pub email: Option<Email>, pub phone: Option<Secret<String>>, - pub name: Option<String>, + pub name: Option<Secret<String>>, pub source: Option<String>, } @@ -187,15 +190,15 @@ pub struct StripeCustomerResponse { pub description: Option<String>, pub email: Option<Email>, pub phone: Option<Secret<String>>, - pub name: Option<String>, + pub name: Option<Secret<String>>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct ChargesRequest { pub amount: String, pub currency: String, - pub customer: String, - pub source: String, + pub customer: Secret<String>, + pub source: Secret<String>, } #[derive(Clone, Debug, Default, Eq, PartialEq, Deserialize)] @@ -407,7 +410,7 @@ pub enum StripeWallet { #[derive(Debug, Eq, PartialEq, Serialize)] pub struct StripeApplePay { - pub pk_token: String, + pub pk_token: Secret<String>, pub pk_token_instrument_name: String, pub pk_token_payment_network: String, pub pk_token_transaction_id: String, @@ -418,13 +421,13 @@ pub struct GooglePayToken { #[serde(rename = "payment_method_data[type]")] pub payment_type: StripePaymentMethodType, #[serde(rename = "payment_method_data[card][token]")] - pub token: String, + pub token: Secret<String>, } #[derive(Debug, Eq, PartialEq, Serialize)] pub struct ApplepayPayment { #[serde(rename = "payment_method_data[card][token]")] - pub token: String, + pub token: Secret<String>, #[serde(rename = "payment_method_data[type]")] pub payment_method_types: StripePaymentMethodType, } @@ -1019,14 +1022,9 @@ fn create_stripe_payment_method( payments::PaymentMethodData::Wallet(wallet_data) => match wallet_data { payments::WalletData::ApplePay(applepay_data) => Ok(( StripePaymentMethodData::Wallet(StripeWallet::ApplepayToken(StripeApplePay { - pk_token: String::from_utf8( - consts::BASE64_ENGINE - .decode(&applepay_data.payment_data) - .into_report() - .change_context(errors::ConnectorError::RequestEncodingFailed)?, - ) - .into_report() - .change_context(errors::ConnectorError::RequestEncodingFailed)?, + pk_token: applepay_data + .get_applepay_decoded_payment_data() + .change_context(errors::ConnectorError::RequestEncodingFailed)?, pk_token_instrument_name: applepay_data.payment_method.pm_type.to_owned(), pk_token_payment_network: applepay_data.payment_method.network.to_owned(), pk_token_transaction_id: applepay_data.transaction_identifier.to_owned(), @@ -1144,13 +1142,15 @@ impl TryFrom<&payments::GooglePayWalletData> for StripePaymentMethodData { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(gpay_data: &payments::GooglePayWalletData) -> Result<Self, Self::Error> { Ok(Self::Wallet(StripeWallet::GooglepayToken(GooglePayToken { - token: gpay_data - .tokenization_data - .token - .as_bytes() - .parse_struct::<StripeGpayToken>("StripeGpayToken") - .change_context(errors::ConnectorError::RequestEncodingFailed)? - .id, + token: Secret::new( + gpay_data + .tokenization_data + .token + .as_bytes() + .parse_struct::<StripeGpayToken>("StripeGpayToken") + .change_context(errors::ConnectorError::RequestEncodingFailed)? + .id, + ), payment_type: StripePaymentMethodType::Card, }))) } @@ -1216,7 +1216,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { mandate_options: None, network_transaction_id: None, mit_exemption: Some(MitExemption { - network_transaction_id, + network_transaction_id: Secret::new(network_transaction_id), }), }); (None, None, None, StripeBillingAddress::default()) @@ -1243,11 +1243,12 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { payment_data = match item.request.payment_method_data { payments::PaymentMethodData::Wallet(payments::WalletData::ApplePay(_)) => Some( StripePaymentMethodData::Wallet(StripeWallet::ApplepayPayment(ApplepayPayment { - token: item - .payment_method_token - .to_owned() - .get_required_value("payment_token") - .change_context(errors::ConnectorError::RequestEncodingFailed)?, + token: Secret::new( + item.payment_method_token + .to_owned() + .get_required_value("payment_token") + .change_context(errors::ConnectorError::RequestEncodingFailed)?, + ), payment_method_types: StripePaymentMethodType::Card, })), ), @@ -1299,10 +1300,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { billing: billing_address, capture_method: StripeCaptureMethod::from(item.request.capture_method), payment_data, - mandate, + mandate: mandate.map(Secret::new), payment_method_options, payment_method, - customer: item.connector_customer.to_owned(), + customer: item.connector_customer.to_owned().map(Secret::new), setup_mandate_details, off_session: item.request.off_session, setup_future_usage: item.request.setup_future_usage, @@ -1335,7 +1336,7 @@ impl TryFrom<&types::VerifyRouterData> for SetupIntentRequest { off_session: item.request.off_session, usage: item.request.setup_future_usage, payment_method_options: None, - customer: item.connector_customer.to_owned(), + customer: item.connector_customer.to_owned().map(Secret::new), }) } } @@ -1362,7 +1363,7 @@ impl TryFrom<&types::ConnectorCustomerRouterData> for CustomerRequest { description: item.request.description.to_owned(), email: item.request.email.to_owned(), phone: item.request.phone.to_owned(), - name: item.request.name.to_owned(), + name: item.request.name.to_owned().map(Secret::new), source: item.request.preprocessing_id.to_owned(), }) } @@ -1774,7 +1775,7 @@ impl ForeignFrom<Option<LatestAttempt>> for Option<String> { StripePaymentMethodOptions::Card { network_transaction_id, .. - } => network_transaction_id, + } => network_transaction_id.map(|network_id| network_id.expose()), _ => None, }), _ => None, @@ -2059,7 +2060,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelRequest { pub enum StripePaymentMethodOptions { Card { mandate_options: Option<StripeMandateOptions>, - network_transaction_id: Option<String>, + network_transaction_id: Option<Secret<String>>, mit_exemption: Option<MitExemption>, // To be used for MIT mandate txns }, Klarna {}, @@ -2087,7 +2088,7 @@ pub enum StripePaymentMethodOptions { #[derive(Clone, Debug, Default, Eq, PartialEq, Serialize, Deserialize)] pub struct MitExemption { - pub network_transaction_id: String, + pub network_transaction_id: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, Deserialize)] @@ -2182,20 +2183,8 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for ChargesRequest { Ok(Self { amount: value.request.amount.to_string(), currency: value.request.currency.to_string(), - customer: value - .connector_customer - .to_owned() - .get_required_value("customer_id") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "customer_id", - })?, - source: value - .preprocessing_id - .to_owned() - .get_required_value("source") - .change_context(errors::ConnectorError::MissingRequiredField { - field_name: "source", - })?, + customer: Secret::new(value.get_connector_customer_id()?), + source: Secret::new(value.get_preprocessing_id()?), }) } } @@ -2506,14 +2495,9 @@ impl api::PaymentMethodData::Wallet(wallet_data) => match wallet_data { payments::WalletData::ApplePay(data) => { let wallet_info = StripeWallet::ApplepayToken(StripeApplePay { - pk_token: String::from_utf8( - consts::BASE64_ENGINE - .decode(data.payment_data) - .into_report() - .change_context(errors::ConnectorError::RequestEncodingFailed)?, - ) - .into_report() - .change_context(errors::ConnectorError::RequestEncodingFailed)?, + pk_token: data + .get_applepay_decoded_payment_data() + .change_context(errors::ConnectorError::RequestEncodingFailed)?, pk_token_instrument_name: data.payment_method.pm_type, pk_token_payment_network: data.payment_method.network, pk_token_transaction_id: data.transaction_identifier, diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs index 155527b4169..4bba26339e7 100644 --- a/crates/router/src/connector/trustpay/transformers.rs +++ b/crates/router/src/connector/trustpay/transformers.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use api_models::payments::BankRedirectData; -use common_utils::{errors::CustomResult, pii::Email}; +use common_utils::{errors::CustomResult, pii}; use error_stack::{IntoReport, ResultExt}; use masking::Secret; use reqwest::Url; @@ -131,9 +131,9 @@ pub struct PaymentRequestCards { #[serde(rename = "billing[postcode]")] pub billing_postcode: Secret<String>, #[serde(rename = "customer[email]")] - pub customer_email: Email, + pub customer_email: pii::Email, #[serde(rename = "customer[ipAddress]")] - pub customer_ip_address: std::net::IpAddr, + pub customer_ip_address: Secret<String, pii::IpAddress>, #[serde(rename = "browser[acceptHeader]")] pub browser_accept_header: String, #[serde(rename = "browser[language]")] diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs index 774f34274ab..873a3c14929 100644 --- a/crates/router/src/connector/utils.rs +++ b/crates/router/src/connector/utils.rs @@ -5,7 +5,7 @@ use base64::Engine; use common_utils::{ date_time, errors::ReportSwitchExt, - pii::{self, Email}, + pii::{self, Email, IpAddress}, }; use error_stack::{report, IntoReport, ResultExt}; use masking::Secret; @@ -64,6 +64,7 @@ pub trait RouterData { fn get_payment_method_token(&self) -> Result<String, Error>; fn get_customer_id(&self) -> Result<String, Error>; fn get_connector_customer_id(&self) -> Result<String, Error>; + fn get_preprocessing_id(&self) -> Result<String, Error>; } impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Response> { @@ -157,6 +158,11 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re .to_owned() .ok_or_else(missing_field_err("connector_customer_id")) } + fn get_preprocessing_id(&self) -> Result<String, Error> { + self.preprocessing_id + .to_owned() + .ok_or_else(missing_field_err("preprocessing_id")) + } } pub trait PaymentsPreProcessingData { @@ -257,13 +263,15 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData { } pub trait BrowserInformationData { - fn get_ip_address(&self) -> Result<std::net::IpAddr, Error>; + fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error>; } impl BrowserInformationData for types::BrowserInformation { - fn get_ip_address(&self) -> Result<std::net::IpAddr, Error> { - self.ip_address - .ok_or_else(missing_field_err("browser_info.ip_address")) + fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error> { + let ip_address = self + .ip_address + .ok_or_else(missing_field_err("browser_info.ip_address"))?; + Ok(Secret::new(ip_address.to_string())) } } @@ -368,7 +376,7 @@ pub struct GooglePayPaymentMethodInfo { pub struct GpayTokenizationData { #[serde(rename = "type")] pub token_type: String, - pub token: String, + pub token: Secret<String>, } impl From<api_models::payments::GooglePayWalletData> for GooglePayWalletData { @@ -382,7 +390,7 @@ impl From<api_models::payments::GooglePayWalletData> for GooglePayWalletData { }, tokenization_data: GpayTokenizationData { token_type: data.tokenization_data.token_type, - token: data.tokenization_data.token, + token: Secret::new(data.tokenization_data.token), }, } } @@ -488,18 +496,18 @@ fn get_card_issuer(card_number: &str) -> Result<CardIssuer, Error> { )) } pub trait WalletData { - fn get_wallet_token(&self) -> Result<String, Error>; + fn get_wallet_token(&self) -> Result<Secret<String>, Error>; fn get_wallet_token_as_json<T>(&self) -> Result<T, Error> where T: serde::de::DeserializeOwned; } impl WalletData for api::WalletData { - fn get_wallet_token(&self) -> Result<String, Error> { + fn get_wallet_token(&self) -> Result<Secret<String>, Error> { match self { - Self::GooglePay(data) => Ok(data.tokenization_data.token.clone()), + Self::GooglePay(data) => Ok(Secret::new(data.tokenization_data.token.clone())), Self::ApplePay(data) => Ok(data.get_applepay_decoded_payment_data()?), - Self::PaypalSdk(data) => Ok(data.token.clone()), + Self::PaypalSdk(data) => Ok(Secret::new(data.token.clone())), _ => Err(errors::ConnectorError::InvalidWallet.into()), } } @@ -507,26 +515,28 @@ impl WalletData for api::WalletData { where T: serde::de::DeserializeOwned, { - serde_json::from_str::<T>(&self.get_wallet_token()?) + serde_json::from_str::<T>(self.get_wallet_token()?.peek()) .into_report() .change_context(errors::ConnectorError::InvalidWalletToken) } } pub trait ApplePay { - fn get_applepay_decoded_payment_data(&self) -> Result<String, Error>; + fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error>; } impl ApplePay for payments::ApplePayWalletData { - fn get_applepay_decoded_payment_data(&self) -> Result<String, Error> { - let token = String::from_utf8( - consts::BASE64_ENGINE - .decode(&self.payment_data) - .into_report() - .change_context(errors::ConnectorError::InvalidWalletToken)?, - ) - .into_report() - .change_context(errors::ConnectorError::InvalidWalletToken)?; + fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error> { + let token = Secret::new( + String::from_utf8( + consts::BASE64_ENGINE + .decode(&self.payment_data) + .into_report() + .change_context(errors::ConnectorError::InvalidWalletToken)?, + ) + .into_report() + .change_context(errors::ConnectorError::InvalidWalletToken)?, + ); Ok(token) } } diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs index fb986efa5c2..2d228cf3936 100644 --- a/crates/router/src/connector/zen/transformers.rs +++ b/crates/router/src/connector/zen/transformers.rs @@ -1,8 +1,6 @@ -use std::net::IpAddr; - use api_models::payments::{ApplePayRedirectData, Card, GooglePayWalletData}; use cards::CardNumber; -use common_utils::{ext_traits::ValueExt, pii::Email}; +use common_utils::{ext_traits::ValueExt, pii}; use error_stack::ResultExt; use masking::{PeekInterface, Secret}; use ring::digest; @@ -82,8 +80,8 @@ pub enum ZenPaymentChannels { #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ZenCustomerDetails { - email: Email, - ip: IpAddr, + email: pii::Email, + ip: Secret<String, pii::IpAddress>, } #[derive(Debug, Serialize)] @@ -93,7 +91,7 @@ pub struct ZenPaymentData { #[serde(rename = "type")] payment_type: ZenPaymentTypes, #[serde(skip_serializing_if = "Option::is_none")] - token: Option<String>, + token: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] card: Option<ZenCardDetails>, descriptor: String, @@ -196,7 +194,9 @@ impl TryFrom<(&types::PaymentsAuthorizeRouterData, &GooglePayWalletData)> for Ze browser_details, //Connector Specific for wallet payment_type: ZenPaymentTypes::ExternalPaymentToken, - token: Some(gpay_pay_redirect_data.tokenization_data.token.clone()), + token: Some(Secret::new( + gpay_pay_redirect_data.tokenization_data.token.clone(), + )), card: None, descriptor: item.get_description()?.chars().take(24).collect(), return_verify_url: item.request.router_return_url.clone(), @@ -323,7 +323,7 @@ fn get_signature_data(checkout_request: &CheckoutRequest) -> String { fn get_customer( item: &types::PaymentsAuthorizeRouterData, - ip: IpAddr, + ip: Secret<String, pii::IpAddress>, ) -> Result<ZenCustomerDetails, error_stack::Report<errors::ConnectorError>> { Ok(ZenCustomerDetails { email: item.request.get_email()?,
feat
mask pii information in connector request and response for stripe, bluesnap, checkout, zen (#1435)
9aabb14a60f821769ccc61013368fb9683711d94
2024-02-26 18:58:03
Sakil Mostak
feat(connector): [Payme] Add Void flow to Payme (#3817)
false
diff --git a/crates/router/src/connector/payme.rs b/crates/router/src/connector/payme.rs index ba11df7d539..0c4543cd8a2 100644 --- a/crates/router/src/connector/payme.rs +++ b/crates/router/src/connector/payme.rs @@ -774,16 +774,103 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData> for Payme { - fn build_request( + fn get_headers( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { + self.build_headers(req, connectors) + } + + fn get_content_type(&self) -> &'static str { + self.common_get_content_type() + } + + fn get_url( + &self, + _req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, + ) -> CustomResult<String, errors::ConnectorError> { + // for void, same endpoint is used as refund for payme + Ok(format!("{}api/refund-sale", self.base_url(connectors))) + } + + fn get_request_body( &self, - _req: &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>, + req: &types::PaymentsCancelRouterData, _connectors: &settings::Connectors, + ) -> CustomResult<RequestContent, errors::ConnectorError> { + let amount = req + .request + .amount + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "amount", + })?; + let currency = + req.request + .currency + .ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "currency", + })?; + let connector_router_data = + payme::PaymeRouterData::try_from((&self.get_currency_unit(), currency, amount, req))?; + let connector_req = payme::PaymeVoidRequest::try_from(&connector_router_data)?; + Ok(RequestContent::Json(Box::new(connector_req))) + } + + fn build_request( + &self, + req: &types::PaymentsCancelRouterData, + connectors: &settings::Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { - Err(errors::ConnectorError::FlowNotSupported { - flow: "Void".to_string(), - connector: "Payme".to_string(), - } - .into()) + let request = services::RequestBuilder::new() + .method(services::Method::Post) + .url(&types::PaymentsVoidType::get_url(self, req, connectors)?) + .attach_default_headers() + .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?) + .set_body(types::PaymentsVoidType::get_request_body( + self, req, connectors, + )?) + .build(); + Ok(Some(request)) + } + + fn handle_response( + &self, + data: &types::PaymentsCancelRouterData, + event_builder: Option<&mut ConnectorEvent>, + res: Response, + ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> { + let response: payme::PaymeVoidResponse = res + .response + .parse_struct("PaymeVoidResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + event_builder.map(|i| i.set_response_body(&response)); + router_env::logger::info!(connector_response=?response); + + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + + fn get_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + self.build_error_response(res, event_builder) + } + + fn get_5xx_error_response( + &self, + res: Response, + event_builder: Option<&mut ConnectorEvent>, + ) -> CustomResult<ErrorResponse, errors::ConnectorError> { + // we are always getting 500 in error scenarios + self.build_error_response(res, event_builder) } } diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs index 2db7034d99e..ee0d52bae50 100644 --- a/crates/router/src/connector/payme/transformers.rs +++ b/crates/router/src/connector/payme/transformers.rs @@ -13,8 +13,9 @@ use url::Url; use crate::{ connector::utils::{ self, is_payment_failure, is_refund_failure, missing_field_err, AddressDetailsData, - CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, - PaymentsPreProcessingData, PaymentsSyncRequestData, RouterData, + CardData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData, + PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingData, PaymentsSyncRequestData, + RouterData, }, consts, core::errors, @@ -254,13 +255,7 @@ impl TryFrom<&PaymePaySaleResponse> for types::PaymentsResponseData { connector_mandate_id: Some(buyer_key.expose()), payment_method_id: None, }), - connector_metadata: Some( - serde_json::to_value(PaymeMetadata { - payme_transaction_id: value.payme_transaction_id.clone(), - }) - .into_report() - .change_context(errors::ConnectorError::ResponseHandlingFailed)?, - ), + connector_metadata: None, network_txn_id: None, connector_response_reference_id: None, incremental_authorization_allowed: None, @@ -983,8 +978,8 @@ impl TryFrom<SaleStatus> for enums::RefundStatus { #[derive(Debug, Deserialize, Serialize)] pub struct PaymeRefundResponse { sale_status: SaleStatus, - payme_transaction_id: String, - status_error_code: i64, + payme_transaction_id: Option<String>, + status_error_code: Option<u32>, } impl TryFrom<types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse>> @@ -997,17 +992,27 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse> let refund_status = enums::RefundStatus::try_from(item.response.sale_status.clone())?; let response = if is_refund_failure(refund_status) { let payme_response = &item.response; + let status_error_code = payme_response + .status_error_code + .map(|error_code| error_code.to_string()); Err(types::ErrorResponse { - code: payme_response.status_error_code.to_string(), - message: payme_response.status_error_code.to_string(), - reason: Some(payme_response.status_error_code.to_string()), + code: status_error_code + .clone() + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + message: status_error_code + .clone() + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: status_error_code, status_code: item.http_code, attempt_status: None, - connector_transaction_id: Some(payme_response.payme_transaction_id.clone()), + connector_transaction_id: payme_response.payme_transaction_id.clone(), }) } else { Ok(types::RefundsResponseData { - connector_refund_id: item.response.payme_transaction_id, + connector_refund_id: item + .response + .payme_transaction_id + .ok_or(errors::ConnectorError::MissingConnectorRefundID)?, refund_status, }) }; @@ -1018,6 +1023,89 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse> } } +#[derive(Debug, Serialize)] +pub struct PaymeVoidRequest { + sale_currency: enums::Currency, + payme_sale_id: String, + seller_payme_id: Secret<String>, + language: String, +} + +impl + TryFrom< + &PaymeRouterData< + &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>, + >, + > for PaymeVoidRequest +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: &PaymeRouterData< + &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>, + >, + ) -> Result<Self, Self::Error> { + let auth_type = PaymeAuthType::try_from(&item.router_data.connector_auth_type)?; + Ok(Self { + payme_sale_id: item.router_data.request.connector_transaction_id.clone(), + seller_payme_id: auth_type.seller_payme_id, + sale_currency: item.router_data.request.get_currency()?, + language: LANGUAGE.to_string(), + }) + } +} + +#[derive(Debug, Deserialize, Serialize)] +pub struct PaymeVoidResponse { + sale_status: SaleStatus, + payme_transaction_id: Option<String>, + status_error_code: Option<u32>, +} + +impl TryFrom<types::PaymentsCancelResponseRouterData<PaymeVoidResponse>> + for types::PaymentsCancelRouterData +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::PaymentsCancelResponseRouterData<PaymeVoidResponse>, + ) -> Result<Self, Self::Error> { + let status = enums::AttemptStatus::from(item.response.sale_status.clone()); + let response = if is_payment_failure(status) { + let payme_response = &item.response; + let status_error_code = payme_response + .status_error_code + .map(|error_code| error_code.to_string()); + Err(types::ErrorResponse { + code: status_error_code + .clone() + .unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()), + message: status_error_code + .clone() + .unwrap_or_else(|| consts::NO_ERROR_MESSAGE.to_string()), + reason: status_error_code, + status_code: item.http_code, + attempt_status: None, + connector_transaction_id: payme_response.payme_transaction_id.clone(), + }) + } else { + // Since we are not receiving payme_sale_id, we are not populating the transaction response + Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::NoResponseId, + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: None, + incremental_authorization_allowed: None, + }) + }; + Ok(Self { + status, + response, + ..item.data + }) + } +} + #[derive(Debug, Serialize, Deserialize)] pub struct PaymeQueryTransactionResponse { items: Vec<TransactionQuery>,
feat
[Payme] Add Void flow to Payme (#3817)
e575fde6dc22675af18e80b005872dec2f6cc22c
2023-06-22 15:08:32
Sai Harsha Vardhan
feat(connector): enforce logging for connector requests (#1467)
false
diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs index f2edc826f17..46e98d9663d 100644 --- a/crates/router/src/connector/aci.rs +++ b/crates/router/src/connector/aci.rs @@ -254,10 +254,15 @@ impl fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { // encode only for for urlencoded things. - let aci_req = utils::Encode::<aci::AciPaymentsRequest>::convert_and_url_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let connector_req = aci::AciPaymentsRequest::try_from(req)?; + let aci_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<aci::AciPaymentsRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(aci_req)) } @@ -365,9 +370,13 @@ impl fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let aci_req = utils::Encode::<aci::AciCancelRequest>::convert_and_url_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_req = aci::AciCancelRequest::try_from(req)?; + let aci_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<aci::AciCancelRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(aci_req)) } fn build_request( @@ -470,9 +479,13 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let body = utils::Encode::<aci::AciRefundRequest>::convert_and_url_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_req = aci::AciRefundRequest::try_from(req)?; + let body = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<aci::AciRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(body)) } diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs index 26951824d67..ca5506de17a 100644 --- a/crates/router/src/connector/adyen.rs +++ b/crates/router/src/connector/adyen.rs @@ -116,14 +116,16 @@ impl fn get_request_body( &self, req: &types::VerifyRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let authorize_req = types::PaymentsAuthorizeRouterData::from(( req, types::PaymentsAuthorizeData::from(req), )); let connector_req = adyen::AdyenPaymentRequest::try_from(&authorize_req)?; - let adyen_req = utils::Encode::<adyen::AdyenPaymentRequest<'_>>::encode_to_string_of_json( + + let adyen_req = types::RequestBody::log_and_get_request_body( &connector_req, + utils::Encode::<adyen::AdyenPaymentRequest<'_>>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(adyen_req)) @@ -238,11 +240,13 @@ impl fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = adyen::AdyenCaptureRequest::try_from(req)?; - let adyen_req = - utils::Encode::<adyen::AdyenCaptureRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let adyen_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<adyen::AdyenCaptureRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(adyen_req)) } fn build_request( @@ -321,7 +325,7 @@ impl fn get_request_body( &self, req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { // Adyen doesn't support PSync flow. We use PSync flow to fetch payment details, // specifically the redirect URL that takes the user to their Payment page. In non-redirection flows, // we rely on webhooks to obtain the payment status since there is no encoded data available. @@ -363,8 +367,9 @@ impl }, }; - let adyen_request = utils::Encode::<adyen::AdyenRedirectRequest>::encode_to_string_of_json( + let adyen_request = types::RequestBody::log_and_get_request_body( &redirection_request, + utils::Encode::<adyen::AdyenRedirectRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; @@ -480,10 +485,12 @@ impl fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = adyen::AdyenPaymentRequest::try_from(req)?; - let adyen_req = utils::Encode::<adyen::AdyenPaymentRequest<'_>>::encode_to_string_of_json( + + let adyen_req = types::RequestBody::log_and_get_request_body( &connector_req, + utils::Encode::<adyen::AdyenPaymentRequest<'_>>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(adyen_req)) @@ -587,11 +594,14 @@ impl fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = adyen::AdyenCancelRequest::try_from(req)?; - let adyen_req = - utils::Encode::<adyen::AdyenCancelRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let adyen_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<adyen::AdyenCancelRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(adyen_req)) } fn build_request( @@ -684,11 +694,14 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = adyen::AdyenRefundRequest::try_from(req)?; - let adyen_req = - utils::Encode::<adyen::AdyenRefundRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let adyen_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<adyen::AdyenRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(adyen_req)) } diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs index 129d36cc481..eff4809ccbc 100644 --- a/crates/router/src/connector/adyen/transformers.rs +++ b/crates/router/src/connector/adyen/transformers.rs @@ -609,7 +609,7 @@ pub struct AdyenGPay { #[serde(rename = "type")] payment_type: PaymentType, #[serde(rename = "googlePayToken")] - google_pay_token: String, + google_pay_token: Secret<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -617,7 +617,7 @@ pub struct AdyenApplePay { #[serde(rename = "type")] payment_type: PaymentType, #[serde(rename = "applePayToken")] - apple_pay_token: String, + apple_pay_token: Secret<String>, } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -1054,14 +1054,14 @@ impl<'a> TryFrom<&api::WalletData> for AdyenPaymentMethod<'a> { api_models::payments::WalletData::GooglePay(data) => { let gpay_data = AdyenGPay { payment_type: PaymentType::Googlepay, - google_pay_token: data.tokenization_data.token.to_owned(), + google_pay_token: Secret::new(data.tokenization_data.token.to_owned()), }; Ok(AdyenPaymentMethod::Gpay(Box::new(gpay_data))) } api_models::payments::WalletData::ApplePay(data) => { let apple_pay_data = AdyenApplePay { payment_type: PaymentType::Applepay, - apple_pay_token: data.payment_data.to_string(), + apple_pay_token: Secret::new(data.payment_data.to_string()), }; Ok(AdyenPaymentMethod::ApplePay(Box::new(apple_pay_data))) diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs index 1a95f670426..3b674a295bb 100644 --- a/crates/router/src/connector/airwallex.rs +++ b/crates/router/src/connector/airwallex.rs @@ -228,11 +228,13 @@ impl fn get_request_body( &self, req: &types::PaymentsInitRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = airwallex::AirwallexIntentRequest::try_from(req)?; - let req = - utils::Encode::<airwallex::AirwallexIntentRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<airwallex::AirwallexIntentRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(req)) } @@ -346,10 +348,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let airwallex_req = - utils::Encode::<airwallex::AirwallexPaymentsRequest>::convert_and_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_req = airwallex::AirwallexPaymentsRequest::try_from(req)?; + let airwallex_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<airwallex::AirwallexPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(airwallex_req)) } @@ -511,10 +516,12 @@ impl fn get_request_body( &self, req: &types::PaymentsCompleteAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = airwallex::AirwallexCompleteRequest::try_from(req)?; - let req = utils::Encode::<airwallex::AirwallexCompleteRequest>::encode_to_string_of_json( + + let req = types::RequestBody::log_and_get_request_body( &req_obj, + utils::Encode::<airwallex::AirwallexCompleteRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(req)) @@ -597,13 +604,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = airwallex::AirwallexPaymentsCaptureRequest::try_from(req)?; - let airwallex_req = - utils::Encode::<airwallex::AirwallexPaymentsCaptureRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let airwallex_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<airwallex::AirwallexPaymentsCaptureRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(airwallex_req)) } @@ -693,13 +702,14 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = airwallex::AirwallexPaymentsCancelRequest::try_from(req)?; - let airwallex_req = - utils::Encode::<airwallex::AirwallexPaymentsCancelRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let airwallex_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<airwallex::AirwallexPaymentsCancelRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(airwallex_req)) } fn handle_response( @@ -779,10 +789,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let airwallex_req = - utils::Encode::<airwallex::AirwallexRefundRequest>::convert_and_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_req = airwallex::AirwallexRefundRequest::try_from(req)?; + let airwallex_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<airwallex::AirwallexRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(airwallex_req)) } diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs index f9545530494..7305c076e76 100644 --- a/crates/router/src/connector/authorizedotnet.rs +++ b/crates/router/src/connector/authorizedotnet.rs @@ -120,13 +120,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = authorizedotnet::CancelOrCaptureTransactionRequest::try_from(req)?; - let authorizedotnet_req = - utils::Encode::<authorizedotnet::CancelOrCaptureTransactionRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let authorizedotnet_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<authorizedotnet::CancelOrCaptureTransactionRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(authorizedotnet_req)) } @@ -207,13 +208,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_request_body( &self, req: &types::PaymentsSyncRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = authorizedotnet::AuthorizedotnetCreateSyncRequest::try_from(req)?; - let sync_request = - utils::Encode::<authorizedotnet::AuthorizedotnetCreateSyncRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let sync_request = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<authorizedotnet::AuthorizedotnetCreateSyncRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(sync_request)) } @@ -291,13 +293,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = authorizedotnet::CreateTransactionRequest::try_from(req)?; - let authorizedotnet_req = - utils::Encode::<authorizedotnet::CreateTransactionRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let authorizedotnet_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<authorizedotnet::CreateTransactionRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(authorizedotnet_req)) } @@ -382,13 +385,14 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = authorizedotnet::CancelOrCaptureTransactionRequest::try_from(req)?; - let authorizedotnet_req = - utils::Encode::<authorizedotnet::CancelOrCaptureTransactionRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let authorizedotnet_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<authorizedotnet::CancelOrCaptureTransactionRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(authorizedotnet_req)) } fn build_request( @@ -470,13 +474,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = authorizedotnet::CreateRefundRequest::try_from(req)?; - let authorizedotnet_req = - utils::Encode::<authorizedotnet::CreateRefundRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let authorizedotnet_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<authorizedotnet::CreateRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(authorizedotnet_req)) } @@ -556,13 +561,13 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_request_body( &self, req: &types::RefundsRouterData<api::RSync>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = authorizedotnet::AuthorizedotnetCreateSyncRequest::try_from(req)?; - let sync_request = - utils::Encode::<authorizedotnet::AuthorizedotnetCreateSyncRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let sync_request = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<authorizedotnet::AuthorizedotnetCreateSyncRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(sync_request)) } diff --git a/crates/router/src/connector/bambora.rs b/crates/router/src/connector/bambora.rs index ebc79f6feee..e6e6b2ae93e 100644 --- a/crates/router/src/connector/bambora.rs +++ b/crates/router/src/connector/bambora.rs @@ -149,11 +149,14 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let request = bambora::BamboraPaymentsRequest::try_from(req)?; - let bambora_req = - utils::Encode::<bambora::BamboraPaymentsRequest>::encode_to_string_of_json(&request) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let bambora_req = types::RequestBody::log_and_get_request_body( + &request, + utils::Encode::<bambora::BamboraPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bambora_req)) } @@ -318,10 +321,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let bambora_req = - utils::Encode::<bambora::BamboraPaymentsCaptureRequest>::convert_and_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_req = bambora::BamboraPaymentsCaptureRequest::try_from(req)?; + let bambora_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<bambora::BamboraPaymentsCaptureRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bambora_req)) } @@ -408,11 +414,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let request = bambora::BamboraPaymentsRequest::try_from(req)?; - let bambora_req = - utils::Encode::<bambora::BamboraPaymentsRequest>::encode_to_string_of_json(&request) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let bambora_req = types::RequestBody::log_and_get_request_body( + &request, + utils::Encode::<bambora::BamboraPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bambora_req)) } @@ -502,9 +511,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let bambora_req = utils::Encode::<bambora::BamboraRefundRequest>::convert_and_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_req = bambora::BamboraRefundRequest::try_from(req)?; + let bambora_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<bambora::BamboraRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bambora_req)) } @@ -700,13 +713,14 @@ impl fn get_request_body( &self, req: &types::PaymentsCompleteAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, 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)?; + + let bambora_req = types::RequestBody::log_and_get_request_body( + &request, + utils::Encode::<bambora::BamboraThreedsContinueRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bambora_req)) } diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs index 4e0ca740b97..bd87993046d 100644 --- a/crates/router/src/connector/bambora/transformers.rs +++ b/crates/router/src/connector/bambora/transformers.rs @@ -428,7 +428,7 @@ pub struct BamboraRefundRequest { } impl<F> TryFrom<&types::RefundsRouterData<F>> for BamboraRefundRequest { - type Error = error_stack::Report<errors::ParsingError>; + 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, diff --git a/crates/router/src/connector/bitpay.rs b/crates/router/src/connector/bitpay.rs index 2a670375cbd..bc386b8ed93 100644 --- a/crates/router/src/connector/bitpay.rs +++ b/crates/router/src/connector/bitpay.rs @@ -161,11 +161,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = bitpay::BitpayPaymentsRequest::try_from(req)?; - let bitpay_req = - utils::Encode::<bitpay::BitpayPaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let bitpay_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<bitpay::BitpayPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bitpay_req)) } @@ -313,7 +316,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, _req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } @@ -387,11 +390,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = bitpay::BitpayRefundRequest::try_from(req)?; - let bitpay_req = - utils::Encode::<bitpay::BitpayRefundRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let bitpay_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<bitpay::BitpayRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bitpay_req)) } diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs index c108b34dd74..2d420cbd28c 100644 --- a/crates/router/src/connector/bitpay/transformers.rs +++ b/crates/router/src/connector/bitpay/transformers.rs @@ -1,3 +1,4 @@ +use masking::Secret; use reqwest::Url; use serde::{Deserialize, Serialize}; @@ -27,7 +28,7 @@ pub struct BitpayPaymentsRequest { #[serde(rename = "notificationURL")] notification_url: String, transaction_speed: TransactionSpeed, - token: String, + token: Secret<String>, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for BitpayPaymentsRequest { @@ -249,7 +250,7 @@ fn get_crypto_specific_payment_data( redirect_url, notification_url, transaction_speed, - token, + token: Secret::new(token), }) } diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs index dda1313eb03..bfaa56e7a36 100644 --- a/crates/router/src/connector/bluesnap.rs +++ b/crates/router/src/connector/bluesnap.rs @@ -178,14 +178,13 @@ impl fn get_request_body( &self, req: &types::ConnectorCustomerRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_request = bluesnap::BluesnapCustomerRequest::try_from(req)?; - router_env::logger::info!(?connector_request); - let bluesnap_req = - utils::Encode::<bluesnap::BluesnapCustomerRequest>::encode_to_string_of_json( - &connector_request, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let bluesnap_req = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<bluesnap::BluesnapCustomerRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bluesnap_req)) } @@ -270,14 +269,13 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = bluesnap::BluesnapVoidRequest::try_from(req)?; - router_env::logger::info!(?connector_req); - let bluesnap_req = - utils::Encode::<bluesnap::BluesnapVoidRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let bluesnap_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<bluesnap::BluesnapVoidRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bluesnap_req)) } @@ -436,14 +434,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = bluesnap::BluesnapCaptureRequest::try_from(req)?; - router_env::logger::info!(?connector_req); - let bluesnap_req = - utils::Encode::<bluesnap::BluesnapCaptureRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let bluesnap_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<bluesnap::BluesnapCaptureRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bluesnap_req)) } @@ -534,14 +531,13 @@ impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::Payme fn get_request_body( &self, req: &types::PaymentsSessionRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = bluesnap::BluesnapCreateWalletToken::try_from(req)?; - router_env::logger::info!(?connector_req); - let bluesnap_req = - utils::Encode::<bluesnap::BluesnapCreateWalletToken>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let bluesnap_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<bluesnap::BluesnapCreateWalletToken>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bluesnap_req)) } @@ -628,14 +624,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = bluesnap::BluesnapPaymentsRequest::try_from(req)?; - router_env::logger::info!(?connector_req); - let bluesnap_req = - utils::Encode::<bluesnap::BluesnapPaymentsRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let bluesnap_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<bluesnap::BluesnapPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bluesnap_req)) } @@ -741,14 +736,13 @@ impl fn get_request_body( &self, req: &types::PaymentsCompleteAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = bluesnap::BluesnapPaymentsRequest::try_from(req)?; - router_env::logger::info!(?connector_req); - let bluesnap_req = - utils::Encode::<bluesnap::BluesnapPaymentsRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let bluesnap_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<bluesnap::BluesnapPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bluesnap_req)) } fn build_request( @@ -833,14 +827,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = bluesnap::BluesnapRefundRequest::try_from(req)?; - router_env::logger::info!(?connector_req); - let bluesnap_req = - utils::Encode::<bluesnap::BluesnapRefundRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let bluesnap_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<bluesnap::BluesnapRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(bluesnap_req)) } diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs index 13838725c38..19c02959105 100644 --- a/crates/router/src/connector/braintree.rs +++ b/crates/router/src/connector/braintree.rs @@ -155,11 +155,13 @@ impl fn get_request_body( &self, req: &types::PaymentsSessionRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let braintree_session_request = - utils::Encode::<braintree::BraintreeSessionRequest>::convert_and_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = braintree::BraintreeSessionRequest::try_from(req)?; + let braintree_session_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<braintree::BraintreeSessionRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(braintree_session_request)) } @@ -304,7 +306,7 @@ impl fn get_request_body( &self, _req: &types::PaymentsSyncRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { Ok(None) } @@ -394,11 +396,14 @@ impl fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let braintree_req = - utils::Encode::<braintree::BraintreePaymentsRequest>::convert_and_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(braintree_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = braintree::BraintreePaymentsRequest::try_from(req)?; + let braintree_payment_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<braintree::BraintreePaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(braintree_payment_request)) } fn handle_response( @@ -521,7 +526,7 @@ impl fn get_request_body( &self, _req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { Ok(None) } @@ -596,11 +601,14 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let braintree_req = - utils::Encode::<braintree::BraintreeRefundRequest>::convert_and_url_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(braintree_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = braintree::BraintreeRefundRequest::try_from(req)?; + let braintree_refund_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<braintree::BraintreeRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(braintree_refund_request)) } fn build_request( @@ -680,7 +688,7 @@ impl services::ConnectorIntegration<api::RSync, types::RefundsData, types::Refun fn get_request_body( &self, _req: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { Ok(None) } diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs index 8d856d47e86..31923312a5e 100644 --- a/crates/router/src/connector/checkout.rs +++ b/crates/router/src/connector/checkout.rs @@ -175,12 +175,13 @@ impl fn get_request_body( &self, req: &types::TokenizationRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = checkout::TokenRequest::try_from(req)?; - router_env::logger::info!(?connector_req); - let checkout_req = - utils::Encode::<checkout::TokenRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let checkout_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<checkout::TokenRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(checkout_req)) } @@ -275,14 +276,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = checkout::PaymentCaptureRequest::try_from(req)?; - router_env::logger::info!(?connector_req); - let checkout_req = - utils::Encode::<checkout::PaymentCaptureRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let checkout_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<checkout::PaymentCaptureRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(checkout_req)) } @@ -427,12 +427,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = checkout::PaymentsRequest::try_from(req)?; - router_env::logger::info!(?connector_req); - let checkout_req = - utils::Encode::<checkout::PaymentsRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let checkout_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<checkout::PaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(checkout_req)) } fn build_request( @@ -511,12 +512,13 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = checkout::PaymentVoidRequest::try_from(req)?; - router_env::logger::info!(?connector_req); - let checkout_req = - utils::Encode::<checkout::PaymentVoidRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let checkout_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<checkout::PaymentVoidRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(checkout_req)) } fn build_request( @@ -597,12 +599,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = checkout::RefundRequest::try_from(req)?; - router_env::logger::info!(?connector_req); - let body = - utils::Encode::<checkout::RefundRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let body = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<checkout::RefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(body)) } @@ -957,12 +960,13 @@ impl fn get_request_body( &self, req: &types::SubmitEvidenceRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let checkout_req = checkout::Evidence::try_from(req)?; - router_env::logger::info!(?checkout_req); - let checkout_req_string = - utils::Encode::<checkout::Evidence>::encode_to_string_of_json(&checkout_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let checkout_req_string = types::RequestBody::log_and_get_request_body( + &checkout_req, + utils::Encode::<checkout::Evidence>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(checkout_req_string)) } diff --git a/crates/router/src/connector/coinbase.rs b/crates/router/src/connector/coinbase.rs index 976b200fca8..5adadb56f56 100644 --- a/crates/router/src/connector/coinbase.rs +++ b/crates/router/src/connector/coinbase.rs @@ -162,12 +162,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let req_obj = coinbase::CoinbasePaymentsRequest::try_from(req)?; - let coinbase_req = - Encode::<coinbase::CoinbasePaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(coinbase_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = coinbase::CoinbasePaymentsRequest::try_from(req)?; + let coinbase_payment_request = types::RequestBody::log_and_get_request_body( + &connector_request, + Encode::<coinbase::CoinbasePaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(coinbase_payment_request)) } fn build_request( @@ -311,7 +313,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, _req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } @@ -387,12 +389,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let req_obj = coinbase::CoinbaseRefundRequest::try_from(req)?; - let coinbase_req = - Encode::<coinbase::CoinbaseRefundRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(coinbase_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = coinbase::CoinbaseRefundRequest::try_from(req)?; + let coinbase_refund_request = types::RequestBody::log_and_get_request_body( + &connector_request, + Encode::<coinbase::CoinbaseRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(coinbase_refund_request)) } fn build_request( diff --git a/crates/router/src/connector/cybersource.rs b/crates/router/src/connector/cybersource.rs index 7a4e55d44fd..138c2da42c4 100644 --- a/crates/router/src/connector/cybersource.rs +++ b/crates/router/src/connector/cybersource.rs @@ -4,6 +4,7 @@ use std::fmt::Debug; use base64::Engine; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use ring::{digest, hmac}; use time::OffsetDateTime; use transformers as cybersource; @@ -151,8 +152,13 @@ where .chars() .skip(base_url.len() - 1) .collect(); - let sha256 = - self.generate_digest(cybersource_req.map_or("{}".to_string(), |s| s).as_bytes()); + let sha256 = self.generate_digest( + cybersource_req + .map_or("{}".to_string(), |s| { + types::RequestBody::get_inner_value(s).peek().to_owned() + }) + .as_bytes(), + ); let http_method = self.get_http_method(); let signature = self.generate_signature( auth, @@ -258,14 +264,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let req_obj = cybersource::CybersourcePaymentsRequest::try_from(req)?; - let req = - utils::Encode::<cybersource::CybersourcePaymentsRequest>::encode_to_string_of_json( - &req_obj, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = cybersource::CybersourcePaymentsRequest::try_from(req)?; + let cybersource_payments_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<cybersource::CybersourcePaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(cybersource_payments_request)) } fn build_request( &self, @@ -354,8 +360,11 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_request_body( &self, _req: &types::PaymentsSyncRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - Ok(Some("{}".to_string())) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + Ok(Some( + types::RequestBody::log_and_get_request_body("{}".to_string(), Ok) + .change_context(errors::ConnectorError::RequestEncodingFailed)?, + )) } fn build_request( &self, @@ -429,14 +438,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let req_obj = cybersource::CybersourcePaymentsRequest::try_from(req)?; - let cybersource_req = - utils::Encode::<cybersource::CybersourcePaymentsRequest>::encode_to_string_of_json( - &req_obj, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(cybersource_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = cybersource::CybersourcePaymentsRequest::try_from(req)?; + let cybersource_payments_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<cybersource::CybersourcePaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(cybersource_payments_request)) } fn build_request( @@ -520,8 +529,11 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, _req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - Ok(Some("{}".to_string())) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + Ok(Some( + types::RequestBody::log_and_get_request_body("{}".to_string(), Ok) + .change_context(errors::ConnectorError::RequestEncodingFailed)?, + )) } fn build_request( @@ -604,13 +616,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundExecuteRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let req_obj = cybersource::CybersourceRefundRequest::try_from(req)?; - let req = utils::Encode::<cybersource::CybersourceRefundRequest>::encode_to_string_of_json( - &req_obj, + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = cybersource::CybersourceRefundRequest::try_from(req)?; + let cybersource_refund_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<cybersource::CybersourceRefundRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(req)) + Ok(Some(cybersource_refund_request)) } fn build_request( &self, diff --git a/crates/router/src/connector/dlocal.rs b/crates/router/src/connector/dlocal.rs index 5df93a1de59..d22a23d2a42 100644 --- a/crates/router/src/connector/dlocal.rs +++ b/crates/router/src/connector/dlocal.rs @@ -8,6 +8,7 @@ use common_utils::{ }; use error_stack::{IntoReport, ResultExt}; use hex::encode; +use masking::PeekInterface; use transformers as dlocal; use crate::{ @@ -55,7 +56,8 @@ where { let dlocal_req = match self.get_request_body(req)? { Some(val) => val, - None => "".to_string(), + None => types::RequestBody::log_and_get_request_body("".to_string(), Ok) + .change_context(errors::ConnectorError::RequestEncodingFailed)?, }; let date = date_time::date_as_yyyymmddthhmmssmmmz() @@ -63,7 +65,14 @@ where .change_context(errors::ConnectorError::RequestEncodingFailed)?; let auth = dlocal::DlocalAuthType::try_from(&req.connector_auth_type)?; - let sign_req: String = format!("{}{}{}", auth.x_login, date, dlocal_req); + let sign_req: String = format!( + "{}{}{}", + auth.x_login, + date, + types::RequestBody::get_inner_value(dlocal_req) + .peek() + .to_owned() + ); let authz = crypto::HmacSha256::sign_message( &crypto::HmacSha256, auth.secret.as_bytes(), @@ -176,10 +185,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let dlocal_req = utils::Encode::<dlocal::DlocalPaymentsRequest>::convert_and_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(dlocal_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = dlocal::DlocalPaymentsRequest::try_from(req)?; + let dlocal_payments_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<dlocal::DlocalPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(dlocal_payments_request)) } fn build_request( @@ -324,11 +337,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let dlocal_req = - utils::Encode::<dlocal::DlocalPaymentsCaptureRequest>::convert_and_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(dlocal_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = dlocal::DlocalPaymentsCaptureRequest::try_from(req)?; + let dlocal_payments_capture_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<dlocal::DlocalPaymentsCaptureRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(dlocal_payments_capture_request)) } fn build_request( @@ -470,10 +486,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let dlocal_req = utils::Encode::<dlocal::RefundRequest>::convert_and_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(dlocal_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = dlocal::RefundRequest::try_from(req)?; + let dlocal_refund_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<dlocal::RefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(dlocal_refund_request)) } fn build_request( diff --git a/crates/router/src/connector/dummyconnector.rs b/crates/router/src/connector/dummyconnector.rs index 5246f39a0c8..bffc6523e2f 100644 --- a/crates/router/src/connector/dummyconnector.rs +++ b/crates/router/src/connector/dummyconnector.rs @@ -173,14 +173,14 @@ impl<const T: u8> fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let req_obj = dummyconnector::DummyConnectorPaymentsRequest::try_from(req)?; - let dummyconnector_req = - utils::Encode::<dummyconnector::DummyConnectorPaymentsRequest>::encode_to_string_of_json( - &req_obj, + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = dummyconnector::DummyConnectorPaymentsRequest::try_from(req)?; + let dummmy_payments_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<dummyconnector::DummyConnectorPaymentsRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(dummyconnector_req)) + Ok(Some(dummmy_payments_request)) } fn build_request( @@ -332,7 +332,7 @@ impl<const T: u8> fn get_request_body( &self, _req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } @@ -414,14 +414,14 @@ impl<const T: u8> ConnectorIntegration<api::Execute, types::RefundsData, types:: fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let req_obj = dummyconnector::DummyConnectorRefundRequest::try_from(req)?; - let dummyconnector_req = - utils::Encode::<dummyconnector::DummyConnectorRefundRequest>::encode_to_string_of_json( - &req_obj, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(dummyconnector_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = dummyconnector::DummyConnectorRefundRequest::try_from(req)?; + let dummmy_refund_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<dummyconnector::DummyConnectorRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(dummmy_refund_request)) } fn build_request( diff --git a/crates/router/src/connector/fiserv.rs b/crates/router/src/connector/fiserv.rs index b75f4e01981..ba455a32ccc 100644 --- a/crates/router/src/connector/fiserv.rs +++ b/crates/router/src/connector/fiserv.rs @@ -4,6 +4,7 @@ use std::fmt::Debug; use base64::Engine; use error_stack::{IntoReport, ResultExt}; +use masking::PeekInterface; use ring::hmac; use time::OffsetDateTime; use transformers as fiserv; @@ -71,7 +72,12 @@ where let client_request_id = Uuid::new_v4().to_string(); let hmac = self - .generate_authorization_signature(auth, &client_request_id, &fiserv_req, timestamp) + .generate_authorization_signature( + auth, + &client_request_id, + types::RequestBody::get_inner_value(fiserv_req).peek(), + timestamp, + ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let mut headers = vec![ ( @@ -212,12 +218,14 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let connector_req = fiserv::FiservCancelRequest::try_from(req)?; - let fiserv_req = - utils::Encode::<fiserv::FiservCancelRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(fiserv_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = fiserv::FiservCancelRequest::try_from(req)?; + let fiserv_payments_cancel_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<fiserv::FiservCancelRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(fiserv_payments_cancel_request)) } fn build_request( @@ -296,12 +304,14 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_request_body( &self, req: &types::PaymentsSyncRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let connector_req = fiserv::FiservSyncRequest::try_from(req)?; - let fiserv_req = - utils::Encode::<fiserv::FiservSyncRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(fiserv_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = fiserv::FiservSyncRequest::try_from(req)?; + let fiserv_payments_sync_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<fiserv::FiservSyncRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(fiserv_payments_sync_request)) } fn build_request( @@ -367,12 +377,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let connector_req = fiserv::FiservCaptureRequest::try_from(req)?; - let fiserv_req = - utils::Encode::<fiserv::FiservCaptureRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(fiserv_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = fiserv::FiservCaptureRequest::try_from(req)?; + let fiserv_payments_capture_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<fiserv::FiservCaptureRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(fiserv_payments_capture_request)) } fn build_request( @@ -470,13 +482,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let connector_req = fiserv::FiservPaymentsRequest::try_from(req)?; - let fiserv_req = utils::Encode::<fiserv::FiservPaymentsRequest>::encode_to_string_of_json( - &connector_req, + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = fiserv::FiservPaymentsRequest::try_from(req)?; + let fiserv_payments_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<fiserv::FiservPaymentsRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(fiserv_req)) + Ok(Some(fiserv_payments_request)) } fn build_request( @@ -556,12 +569,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let connector_req = fiserv::FiservRefundRequest::try_from(req)?; - let fiserv_req = - utils::Encode::<fiserv::FiservRefundRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(fiserv_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = fiserv::FiservRefundRequest::try_from(req)?; + let fiserv_refund_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<fiserv::FiservRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(fiserv_refund_request)) } fn build_request( &self, @@ -634,12 +649,14 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_request_body( &self, req: &types::RefundSyncRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let connector_req = fiserv::FiservSyncRequest::try_from(req)?; - let fiserv_req = - utils::Encode::<fiserv::FiservSyncRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(fiserv_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = fiserv::FiservSyncRequest::try_from(req)?; + let fiserv_sync_request = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<fiserv::FiservSyncRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(fiserv_sync_request)) } fn build_request( diff --git a/crates/router/src/connector/forte.rs b/crates/router/src/connector/forte.rs index 6bc22cfc524..53459d37a1b 100644 --- a/crates/router/src/connector/forte.rs +++ b/crates/router/src/connector/forte.rs @@ -172,11 +172,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = forte::FortePaymentsRequest::try_from(req)?; - let forte_req = - utils::Encode::<forte::FortePaymentsRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let forte_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<forte::FortePaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(forte_req)) } @@ -326,11 +328,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = forte::ForteCaptureRequest::try_from(req)?; - let forte_req = - utils::Encode::<forte::ForteCaptureRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let forte_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<forte::ForteCaptureRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(forte_req)) } @@ -407,11 +411,13 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = forte::ForteCancelRequest::try_from(req)?; - let forte_req = - utils::Encode::<forte::ForteCancelRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let forte_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<forte::ForteCancelRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(forte_req)) } @@ -485,11 +491,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = forte::ForteRefundRequest::try_from(req)?; - let forte_req = - utils::Encode::<forte::ForteRefundRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let forte_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<forte::ForteRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(forte_req)) } diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs index ac0797cc89a..5cdb0b1d8c3 100644 --- a/crates/router/src/connector/globalpay.rs +++ b/crates/router/src/connector/globalpay.rs @@ -145,8 +145,10 @@ impl fn get_request_body( &self, _req: &types::PaymentsCompleteAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - Ok(Some("{}".to_string())) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let globalpay_req = types::RequestBody::log_and_get_request_body("{}".to_string(), Ok) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(globalpay_req)) } fn build_request( @@ -249,11 +251,13 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn get_request_body( &self, req: &types::RefreshTokenRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = GlobalpayRefreshTokenRequest::try_from(req)?; - let globalpay_req = - utils::Encode::<GlobalpayPaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let globalpay_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<GlobalpayPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(globalpay_req)) } @@ -362,11 +366,13 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = requests::GlobalpayCancelRequest::try_from(req)?; - let globalpay_req = - utils::Encode::<GlobalpayPaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let globalpay_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<GlobalpayPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(globalpay_req)) } @@ -498,11 +504,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = requests::GlobalpayCaptureRequest::try_from(req)?; - let globalpay_req = - utils::Encode::<GlobalpayPaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let globalpay_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<GlobalpayPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(globalpay_req)) } @@ -585,11 +593,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = GlobalpayPaymentsRequest::try_from(req)?; - let globalpay_req = - utils::Encode::<GlobalpayPaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let globalpay_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<GlobalpayPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(globalpay_req)) } @@ -673,13 +683,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = requests::GlobalpayRefundRequest::try_from(req)?; - let globalpay_req = - utils::Encode::<requests::GlobalpayRefundRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let globalpay_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<requests::GlobalpayRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(globalpay_req)) } diff --git a/crates/router/src/connector/globalpay/requests.rs b/crates/router/src/connector/globalpay/requests.rs index 35cf25b9b88..8b011e9c7ea 100644 --- a/crates/router/src/connector/globalpay/requests.rs +++ b/crates/router/src/connector/globalpay/requests.rs @@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize}; #[derive(Debug, Serialize)] pub struct GlobalpayPaymentsRequest { /// A meaningful label for the merchant account set by Global Payments. - pub account_name: String, + pub account_name: Secret<String>, /// The amount to transfer between Payer and Merchant for a SALE or a REFUND. It is always /// represented in the lowest denomiation of the related currency. pub amount: Option<String>, @@ -79,7 +79,7 @@ pub struct GlobalpayPaymentsRequest { #[derive(Debug, Serialize)] pub struct GlobalpayRefreshTokenRequest { - pub app_id: String, + pub app_id: Secret<String>, pub nonce: String, pub secret: String, pub grant_type: String, diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs index 8a0916ae934..1bbe8deb181 100644 --- a/crates/router/src/connector/globalpay/transformers.rs +++ b/crates/router/src/connector/globalpay/transformers.rs @@ -1,5 +1,6 @@ use common_utils::crypto::{self, GenerateDigest}; use error_stack::{IntoReport, ResultExt}; +use masking::Secret; use rand::distributions::DistString; use serde::{Deserialize, Serialize}; use url::Url; @@ -23,7 +24,7 @@ type Error = error_stack::Report<errors::ConnectorError>; #[derive(Debug, Serialize, Deserialize)] pub struct GlobalPayMeta { - account_name: String, + account_name: Secret<String>, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobalpayPaymentsRequest { @@ -104,7 +105,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for requests::GlobalpayCancelRequ } pub struct GlobalpayAuthType { - pub app_id: String, + pub app_id: Secret<String>, pub key: String, } @@ -113,7 +114,7 @@ impl TryFrom<&types::ConnectorAuthType> for GlobalpayAuthType { fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self { - app_id: key1.to_string(), + app_id: Secret::new(key1.to_owned()), key: api_key.to_string(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), diff --git a/crates/router/src/connector/iatapay.rs b/crates/router/src/connector/iatapay.rs index 380f90e674d..b27b945b4b8 100644 --- a/crates/router/src/connector/iatapay.rs +++ b/crates/router/src/connector/iatapay.rs @@ -170,12 +170,13 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn get_request_body( &self, req: &types::RefreshTokenRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = iatapay::IatapayAuthUpdateRequest::try_from(req)?; - println!("##accReq={:?}", req_obj); - let iatapay_req = Encode::<iatapay::IatapayAuthUpdateRequest>::url_encode(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - println!("##accReqString={:?}", iatapay_req); + let iatapay_req = types::RequestBody::log_and_get_request_body( + &req_obj, + Encode::<iatapay::IatapayAuthUpdateRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(iatapay_req)) } @@ -262,11 +263,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = iatapay::IatapayPaymentsRequest::try_from(req)?; - let iatapay_req = - Encode::<iatapay::IatapayPaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let iatapay_req = types::RequestBody::log_and_get_request_body( + &req_obj, + Encode::<iatapay::IatapayPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(iatapay_req)) } @@ -413,7 +416,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, _req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } @@ -487,11 +490,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = iatapay::IatapayRefundRequest::try_from(req)?; - let iatapay_req = - Encode::<iatapay::IatapayRefundRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let iatapay_req = types::RequestBody::log_and_get_request_body( + &req_obj, + Encode::<iatapay::IatapayRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(iatapay_req)) } diff --git a/crates/router/src/connector/klarna.rs b/crates/router/src/connector/klarna.rs index 6fc65524d2a..73d6f17248c 100644 --- a/crates/router/src/connector/klarna.rs +++ b/crates/router/src/connector/klarna.rs @@ -124,12 +124,14 @@ impl fn get_request_body( &self, req: &types::PaymentsSessionRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = klarna::KlarnaSessionRequest::try_from(req)?; // encode only for for urlencoded things. - let klarna_req = - utils::Encode::<klarna::KlarnaSessionRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let klarna_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<klarna::KlarnaSessionRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(klarna_req)) } @@ -285,10 +287,11 @@ impl fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = klarna::KlarnaPaymentsRequest::try_from(req)?; - let klarna_req = utils::Encode::<klarna::KlarnaPaymentsRequest>::encode_to_string_of_json( + let klarna_req = types::RequestBody::log_and_get_request_body( &connector_req, + utils::Encode::<klarna::KlarnaPaymentsRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(klarna_req)) diff --git a/crates/router/src/connector/mollie.rs b/crates/router/src/connector/mollie.rs index 898dc586379..9b75ac8702e 100644 --- a/crates/router/src/connector/mollie.rs +++ b/crates/router/src/connector/mollie.rs @@ -144,11 +144,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = mollie::MolliePaymentsRequest::try_from(req)?; - let mollie_req = - utils::Encode::<mollie::MolliePaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let mollie_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<mollie::MolliePaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(mollie_req)) } @@ -330,11 +332,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = mollie::MollieRefundRequest::try_from(req)?; - let mollie_req = - utils::Encode::<mollie::MollieRefundRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let mollie_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<mollie::MollieRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(mollie_req)) } diff --git a/crates/router/src/connector/multisafepay.rs b/crates/router/src/connector/multisafepay.rs index d3562e8a463..d062d08c317 100644 --- a/crates/router/src/connector/multisafepay.rs +++ b/crates/router/src/connector/multisafepay.rs @@ -230,13 +230,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = multisafepay::MultisafepayPaymentsRequest::try_from(req)?; - let multisafepay_req = - utils::Encode::<multisafepay::MultisafepayPaymentsRequest>::encode_to_string_of_json( - &req_obj, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let multisafepay_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<multisafepay::MultisafepayPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(multisafepay_req)) } @@ -323,10 +323,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let multisafepay_req = - utils::Encode::<multisafepay::MultisafepayRefundRequest>::convert_and_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_req = multisafepay::MultisafepayRefundRequest::try_from(req)?; + let multisafepay_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<multisafepay::MultisafepayPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(multisafepay_req)) } diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs index d3a1da39d89..183c5527f74 100644 --- a/crates/router/src/connector/multisafepay/transformers.rs +++ b/crates/router/src/connector/multisafepay/transformers.rs @@ -504,7 +504,7 @@ pub struct MultisafepayRefundRequest { } impl<F> TryFrom<&types::RefundsRouterData<F>> for MultisafepayRefundRequest { - type Error = error_stack::Report<errors::ParsingError>; + type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> { Ok(Self { currency: item.request.currency, diff --git a/crates/router/src/connector/nexinets.rs b/crates/router/src/connector/nexinets.rs index a3490bbb578..2d90c2c4c18 100644 --- a/crates/router/src/connector/nexinets.rs +++ b/crates/router/src/connector/nexinets.rs @@ -177,11 +177,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = nexinets::NexinetsPaymentsRequest::try_from(req)?; - let nexinets_req = - utils::Encode::<nexinets::NexinetsPaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let nexinets_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<nexinets::NexinetsPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(nexinets_req)) } @@ -337,13 +339,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = nexinets::NexinetsCaptureOrVoidRequest::try_from(req)?; - let nexinets_req = - utils::Encode::<nexinets::NexinetsCaptureOrVoidRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let nexinets_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<nexinets::NexinetsCaptureOrVoidRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(nexinets_req)) } @@ -422,13 +424,13 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = nexinets::NexinetsCaptureOrVoidRequest::try_from(req)?; - let nexinets_req = - utils::Encode::<nexinets::NexinetsCaptureOrVoidRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let nexinets_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<nexinets::NexinetsCaptureOrVoidRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(nexinets_req)) } @@ -504,11 +506,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = nexinets::NexinetsRefundRequest::try_from(req)?; - let nexinets_req = - utils::Encode::<nexinets::NexinetsRefundRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let nexinets_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<nexinets::NexinetsRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(nexinets_req)) } diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs index 542f446fa96..37fc6e5cf8e 100644 --- a/crates/router/src/connector/nmi.rs +++ b/crates/router/src/connector/nmi.rs @@ -118,10 +118,13 @@ impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::Payments fn get_request_body( &self, req: &types::VerifyRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = nmi::NmiPaymentsRequest::try_from(req)?; - let nmi_req = utils::Encode::<nmi::NmiPaymentsRequest>::url_encode(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let nmi_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<nmi::NmiPaymentsRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(nmi_req)) } @@ -187,10 +190,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = nmi::NmiPaymentsRequest::try_from(req)?; - let nmi_req = utils::Encode::<nmi::NmiPaymentsRequest>::url_encode(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let nmi_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<nmi::NmiPaymentsRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(nmi_req)) } @@ -258,10 +264,13 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_request_body( &self, req: &types::PaymentsSyncRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = nmi::NmiSyncRequest::try_from(req)?; - let nmi_req = utils::Encode::<nmi::NmiSyncRequest>::url_encode(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let nmi_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<nmi::NmiSyncRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(nmi_req)) } @@ -322,10 +331,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = nmi::NmiCaptureRequest::try_from(req)?; - let nmi_req = utils::Encode::<NmiCaptureRequest>::url_encode(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let nmi_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<NmiCaptureRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(nmi_req)) } @@ -391,10 +403,13 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = nmi::NmiCancelRequest::try_from(req)?; - let nmi_req = utils::Encode::<nmi::NmiCancelRequest>::url_encode(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let nmi_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<nmi::NmiCancelRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(nmi_req)) } @@ -456,10 +471,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = nmi::NmiRefundRequest::try_from(req)?; - let nmi_req = utils::Encode::<nmi::NmiRefundRequest>::url_encode(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let nmi_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<nmi::NmiRefundRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(nmi_req)) } @@ -523,10 +541,13 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse fn get_request_body( &self, req: &types::RefundsRouterData<api::RSync>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = nmi::NmiSyncRequest::try_from(req)?; - let nmi_req = utils::Encode::<nmi::NmiSyncRequest>::url_encode(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let nmi_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<nmi::NmiSyncRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(nmi_req)) } diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index a99c1c9f4ba..f64c24aaf94 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -24,7 +24,7 @@ pub enum TransactionType { } pub struct NmiAuthType { - pub(super) api_key: String, + pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for NmiAuthType { @@ -32,7 +32,7 @@ impl TryFrom<&ConnectorAuthType> for NmiAuthType { fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let types::ConnectorAuthType::HeaderKey { api_key } = auth_type { Ok(Self { - api_key: api_key.to_string(), + api_key: Secret::new(api_key.to_owned()), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType.into()) @@ -68,12 +68,12 @@ pub struct CardData { #[derive(Debug, Serialize)] pub struct GooglePayData { - googlepay_payment_data: String, + googlepay_payment_data: Secret<String>, } #[derive(Debug, Serialize)] pub struct ApplePayData { - applepay_payment_data: String, + applepay_payment_data: Secret<String>, } impl TryFrom<&types::PaymentsAuthorizeRouterData> for NmiPaymentsRequest { @@ -90,7 +90,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NmiPaymentsRequest { Ok(Self { transaction_type, - security_key: auth_type.api_key.into(), + security_key: auth_type.api_key, amount, currency: item.request.currency, payment_method, @@ -143,7 +143,7 @@ impl From<&api_models::payments::Card> for PaymentMethod { impl From<&api_models::payments::GooglePayWalletData> for PaymentMethod { fn from(wallet_data: &api_models::payments::GooglePayWalletData) -> Self { let gpay_data = GooglePayData { - googlepay_payment_data: wallet_data.tokenization_data.token.clone(), + googlepay_payment_data: Secret::new(wallet_data.tokenization_data.token.clone()), }; Self::GPay(Box::new(gpay_data)) } @@ -152,7 +152,7 @@ impl From<&api_models::payments::GooglePayWalletData> for PaymentMethod { impl From<&api_models::payments::ApplePayWalletData> for PaymentMethod { fn from(wallet_data: &api_models::payments::ApplePayWalletData) -> Self { let apple_pay_data = ApplePayData { - applepay_payment_data: wallet_data.payment_data.clone(), + applepay_payment_data: Secret::new(wallet_data.payment_data.clone()), }; Self::ApplePay(Box::new(apple_pay_data)) } @@ -165,7 +165,7 @@ impl TryFrom<&types::VerifyRouterData> for NmiPaymentsRequest { let payment_method = PaymentMethod::try_from(&item.request.payment_method_data)?; Ok(Self { transaction_type: TransactionType::Validate, - security_key: auth_type.api_key.into(), + security_key: auth_type.api_key, amount: 0.0, currency: item.request.currency, payment_method, @@ -176,7 +176,7 @@ impl TryFrom<&types::VerifyRouterData> for NmiPaymentsRequest { #[derive(Debug, Serialize)] pub struct NmiSyncRequest { pub transaction_id: String, - pub security_key: String, + pub security_key: Secret<String>, } impl TryFrom<&types::PaymentsSyncRouterData> for NmiSyncRequest { @@ -209,7 +209,7 @@ impl TryFrom<&types::PaymentsCaptureRouterData> for NmiCaptureRequest { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; Ok(Self { transaction_type: TransactionType::Capture, - security_key: auth.api_key.into(), + security_key: auth.api_key, transactionid: item.request.connector_transaction_id.clone(), amount: Some(utils::to_currency_base_unit_asf64( item.request.amount_to_capture, @@ -282,7 +282,7 @@ impl TryFrom<&types::PaymentsCancelRouterData> for NmiCancelRequest { let auth = NmiAuthType::try_from(&item.connector_auth_type)?; Ok(Self { transaction_type: TransactionType::Void, - security_key: auth.api_key.into(), + security_key: auth.api_key, transactionid: item.request.connector_transaction_id.clone(), void_reason: item.request.cancellation_reason.clone(), }) @@ -522,7 +522,7 @@ impl From<NmiStatus> for enums::AttemptStatus { pub struct NmiRefundRequest { #[serde(rename = "type")] transaction_type: TransactionType, - security_key: String, + security_key: Secret<String>, transactionid: String, amount: f64, } diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs index 256208f70e4..576b8687f87 100644 --- a/crates/router/src/connector/noon.rs +++ b/crates/router/src/connector/noon.rs @@ -166,11 +166,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = noon::NoonPaymentsRequest::try_from(req)?; - let noon_req = - utils::Encode::<noon::NoonPaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let noon_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<noon::NoonPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(noon_req)) } @@ -310,11 +312,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = noon::NoonPaymentsActionRequest::try_from(req)?; - let noon_req = - utils::Encode::<noon::NoonPaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let noon_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<noon::NoonPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(noon_req)) } @@ -385,10 +389,11 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = noon::NoonPaymentsCancelRequest::try_from(req)?; - let noon_req = utils::Encode::<noon::NoonPaymentsCancelRequest>::encode_to_string_of_json( + let noon_req = types::RequestBody::log_and_get_request_body( &connector_req, + utils::Encode::<noon::NoonPaymentsCancelRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(noon_req)) @@ -458,11 +463,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = noon::NoonPaymentsActionRequest::try_from(req)?; - let noon_req = - utils::Encode::<noon::NoonPaymentsActionRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let noon_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<noon::NoonPaymentsActionRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(noon_req)) } diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs index d8f5237379f..a5b164de693 100644 --- a/crates/router/src/connector/nuvei.rs +++ b/crates/router/src/connector/nuvei.rs @@ -131,12 +131,14 @@ impl fn get_request_body( &self, req: &types::PaymentsCompleteAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let meta: nuvei::NuveiMeta = utils::to_connector_meta(req.request.connector_meta.clone())?; let req_obj = nuvei::NuveiPaymentsRequest::try_from((req, meta.session_token))?; - let req = - common_utils::Encode::<nuvei::NuveiPaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let req = types::RequestBody::log_and_get_request_body( + &req_obj, + common_utils::Encode::<nuvei::NuveiPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(req)) } @@ -215,10 +217,11 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = nuvei::NuveiPaymentFlowRequest::try_from(req)?; - let req = common_utils::Encode::<nuvei::NuveiPaymentFlowRequest>::encode_to_string_of_json( + let req = types::RequestBody::log_and_get_request_body( &req_obj, + common_utils::Encode::<nuvei::NuveiPaymentFlowRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(req)) @@ -298,10 +301,11 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe fn get_request_body( &self, req: &types::PaymentsSyncRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = nuvei::NuveiPaymentSyncRequest::try_from(req)?; - let req = common_utils::Encode::<nuvei::NuveiPaymentSyncRequest>::encode_to_string_of_json( + let req = types::RequestBody::log_and_get_request_body( &req_obj, + common_utils::Encode::<nuvei::NuveiPaymentSyncRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(req)) @@ -376,10 +380,11 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = nuvei::NuveiPaymentFlowRequest::try_from(req)?; - let req = common_utils::Encode::<nuvei::NuveiPaymentFlowRequest>::encode_to_string_of_json( + let req = types::RequestBody::log_and_get_request_body( &req_obj, + common_utils::Encode::<nuvei::NuveiPaymentFlowRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(req)) @@ -532,11 +537,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?; - let req = - common_utils::Encode::<nuvei::NuveiPaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let req = types::RequestBody::log_and_get_request_body( + &req_obj, + common_utils::Encode::<nuvei::NuveiPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(req)) } @@ -619,11 +626,13 @@ impl fn get_request_body( &self, req: &types::PaymentsAuthorizeSessionTokenRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = nuvei::NuveiSessionRequest::try_from(req)?; - let req = - common_utils::Encode::<nuvei::NuveiSessionRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let req = types::RequestBody::log_and_get_request_body( + &req_obj, + common_utils::Encode::<nuvei::NuveiSessionRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(req)) } @@ -700,11 +709,13 @@ impl ConnectorIntegration<InitPayment, types::PaymentsAuthorizeData, types::Paym fn get_request_body( &self, req: &types::PaymentsInitRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?; - let req = - common_utils::Encode::<nuvei::NuveiSessionRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let req = types::RequestBody::log_and_get_request_body( + &req_obj, + common_utils::Encode::<nuvei::NuveiSessionRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(req)) } @@ -777,10 +788,11 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = nuvei::NuveiPaymentFlowRequest::try_from(req)?; - let req = common_utils::Encode::<nuvei::NuveiPaymentFlowRequest>::encode_to_string_of_json( + let req = types::RequestBody::log_and_get_request_body( &req_obj, + common_utils::Encode::<nuvei::NuveiPaymentFlowRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(req)) diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs index 5471af10018..86f68af22b1 100644 --- a/crates/router/src/connector/nuvei/transformers.rs +++ b/crates/router/src/connector/nuvei/transformers.rs @@ -234,7 +234,7 @@ pub struct Card { #[serde(rename_all = "camelCase")] pub struct ExternalToken { pub external_token_provider: ExternalTokenProvider, - pub mobile_token: String, + pub mobile_token: Secret<String>, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] @@ -434,15 +434,23 @@ impl TryFrom<payments::GooglePayWalletData> for NuveiPaymentsRequest { Ok(Self { payment_option: PaymentOption { card: Some(Card { - external_token: Some(ExternalToken { - external_token_provider: ExternalTokenProvider::GooglePay, - mobile_token: common_utils::ext_traits::Encode::< - payments::GooglePayWalletData, - >::encode_to_string_of_json( - &utils::GooglePayWalletData::from(gpay_data) - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?, - }), + external_token: + Some( + ExternalToken { + external_token_provider: ExternalTokenProvider::GooglePay, + mobile_token: + Secret::new( + common_utils::ext_traits::Encode::< + payments::GooglePayWalletData, + >::encode_to_string_of_json( + &utils::GooglePayWalletData::from(gpay_data), + ) + .change_context( + errors::ConnectorError::RequestEncodingFailed, + )?, + ), + }, + ), ..Default::default() }), ..Default::default() @@ -458,7 +466,7 @@ impl From<payments::ApplePayWalletData> for NuveiPaymentsRequest { card: Some(Card { external_token: Some(ExternalToken { external_token_provider: ExternalTokenProvider::ApplePay, - mobile_token: apple_pay_data.payment_data, + mobile_token: Secret::new(apple_pay_data.payment_data), }), ..Default::default() }), diff --git a/crates/router/src/connector/opennode.rs b/crates/router/src/connector/opennode.rs index c3ee0e86cf3..d0510561fc7 100644 --- a/crates/router/src/connector/opennode.rs +++ b/crates/router/src/connector/opennode.rs @@ -163,11 +163,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = opennode::OpennodePaymentsRequest::try_from(req)?; - let opennode_req = - Encode::<opennode::OpennodePaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let opennode_req = types::RequestBody::log_and_get_request_body( + &req_obj, + Encode::<opennode::OpennodePaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(opennode_req)) } @@ -312,7 +314,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, _req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into()) } @@ -388,11 +390,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = opennode::OpennodeRefundRequest::try_from(req)?; - let opennode_req = - Encode::<opennode::OpennodeRefundRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let opennode_req = types::RequestBody::log_and_get_request_body( + &req_obj, + Encode::<opennode::OpennodeRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(opennode_req)) } diff --git a/crates/router/src/connector/payeezy.rs b/crates/router/src/connector/payeezy.rs index 5765d3a638e..375fd3faeb1 100644 --- a/crates/router/src/connector/payeezy.rs +++ b/crates/router/src/connector/payeezy.rs @@ -4,6 +4,7 @@ use std::fmt::Debug; use base64::Engine; use error_stack::{IntoReport, ResultExt}; +use masking::ExposeInterface; use rand::distributions::DistString; use ring::hmac; use transformers as payeezy; @@ -40,7 +41,9 @@ where ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> { let auth = payeezy::PayeezyAuthType::try_from(&req.connector_auth_type)?; let option_request_payload = self.get_request_body(req)?; - let request_payload = option_request_payload.map_or("{}".to_string(), |s| s); + let request_payload = option_request_payload.map_or("{}".to_string(), |payload| { + types::RequestBody::get_inner_value(payload).expose() + }); let timestamp = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .ok() @@ -167,13 +170,13 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = payeezy::PayeezyCaptureOrVoidRequest::try_from(req)?; - let payeezy_req = - utils::Encode::<payeezy::PayeezyCaptureOrVoidRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let payeezy_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<payeezy::PayeezyCaptureOrVoidRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(payeezy_req)) } @@ -273,13 +276,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = payeezy::PayeezyCaptureOrVoidRequest::try_from(req)?; - let payeezy_req = - utils::Encode::<payeezy::PayeezyCaptureOrVoidRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let payeezy_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<payeezy::PayeezyCaptureOrVoidRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(payeezy_req)) } @@ -361,13 +364,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = payeezy::PayeezyPaymentsRequest::try_from(req)?; - let payeezy_req = - utils::Encode::<payeezy::PayeezyPaymentsRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let payeezy_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<payeezy::PayeezyPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(payeezy_req)) } @@ -450,13 +453,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = payeezy::PayeezyRefundRequest::try_from(req)?; - let payeezy_req = - utils::Encode::<payeezy::PayeezyCaptureOrVoidRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let payeezy_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<payeezy::PayeezyCaptureOrVoidRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(payeezy_req)) } diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index 85ed7d86e16..2547947c201 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -244,10 +244,13 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn get_request_body( &self, req: &types::RefreshTokenRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let paypal_req = - utils::Encode::<paypal::PaypalAuthUpdateRequest>::convert_and_url_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let req_obj = paypal::PaypalAuthUpdateRequest::try_from(req)?; + let paypal_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<paypal::PaypalAuthUpdateRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(paypal_req)) } @@ -335,11 +338,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = paypal::PaypalPaymentsRequest::try_from(req)?; - let paypal_req = - utils::Encode::<paypal::PaypalPaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let paypal_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<paypal::PaypalPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(paypal_req)) } @@ -614,13 +619,13 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = paypal::PaypalPaymentsCaptureRequest::try_from(req)?; - let paypal_req = - utils::Encode::<paypal::PaypalPaymentsCaptureRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let paypal_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<paypal::PaypalPaymentsCaptureRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(paypal_req)) } @@ -763,11 +768,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = paypal::PaypalRefundRequest::try_from(req)?; - let paypal_req = - utils::Encode::<paypal::PaypalRefundRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let paypal_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<paypal::PaypalRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(paypal_req)) } diff --git a/crates/router/src/connector/payu.rs b/crates/router/src/connector/payu.rs index f2e7cbcc925..959dcd5939a 100644 --- a/crates/router/src/connector/payu.rs +++ b/crates/router/src/connector/payu.rs @@ -221,9 +221,13 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn get_request_body( &self, req: &types::RefreshTokenRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let payu_req = utils::Encode::<payu::PayuAuthUpdateRequest>::convert_and_url_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let req_obj = payu::PayuAuthUpdateRequest::try_from(req)?; + let payu_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<payu::PayuAuthUpdateRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(payu_req)) } @@ -390,10 +394,11 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = payu::PayuPaymentsCaptureRequest::try_from(req)?; - let payu_req = utils::Encode::<payu::PayuPaymentsCaptureRequest>::encode_to_string_of_json( + let payu_req = types::RequestBody::log_and_get_request_body( &connector_req, + utils::Encode::<payu::PayuPaymentsCaptureRequest>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(payu_req)) @@ -483,11 +488,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = payu::PayuPaymentsRequest::try_from(req)?; - let payu_req = - utils::Encode::<payu::PayuPaymentsRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let payu_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<payu::PayuPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(payu_req)) } @@ -575,11 +582,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = payu::PayuRefundRequest::try_from(req)?; - let payu_req = - utils::Encode::<payu::PayuRefundRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let payu_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<payu::PayuRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(payu_req)) } diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs index 2a437bace97..43337c9ced4 100644 --- a/crates/router/src/connector/rapyd.rs +++ b/crates/router/src/connector/rapyd.rs @@ -4,6 +4,7 @@ use std::fmt::Debug; use base64::Engine; use common_utils::{date_time, ext_traits::StringExt}; use error_stack::{IntoReport, ResultExt}; +use masking::ExposeInterface; use rand::distributions::{Alphanumeric, DistString}; use ring::hmac; use transformers as rapyd; @@ -148,6 +149,19 @@ impl Ok(format!("{}/v1/payments", self.base_url(connectors))) } + fn get_request_body( + &self, + req: &types::PaymentsAuthorizeRouterData, + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let req_obj = rapyd::RapydPaymentsRequest::try_from(req)?; + let rapyd_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<rapyd::RapydPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(rapyd_req)) + } + fn build_request( &self, req: &types::RouterData< @@ -160,12 +174,12 @@ impl 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 body = types::PaymentsAuthorizeType::get_request_body(self, req)? + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let req_body = types::RequestBody::get_inner_value(body).expose(); let signature = - self.generate_signature(&auth, "post", "/v1/payments", &rapyd_req, &timestamp, &salt)?; + self.generate_signature(&auth, "post", "/v1/payments", &req_body, &timestamp, &salt)?; let headers = vec![ ("access_key".to_string(), auth.access_key.into_masked()), ("salt".to_string(), salt.into_masked()), @@ -182,20 +196,11 @@ impl self, req, connectors, )?) .headers(headers) - .body(Some(rapyd_req)) + .body(types::PaymentsAuthorizeType::get_request_body(self, 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, @@ -451,9 +456,13 @@ impl 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)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let req_obj = rapyd::CaptureRequest::try_from(req)?; + let rapyd_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<rapyd::CaptureRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(rapyd_req)) } @@ -465,16 +474,16 @@ impl 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 body = types::PaymentsCaptureType::get_request_body(self, req)? + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let req_body = types::RequestBody::get_inner_value(body).expose(); let signature = - self.generate_signature(&auth, "post", &url_path, &rapyd_req, &timestamp, &salt)?; + self.generate_signature(&auth, "post", &url_path, &req_body, &timestamp, &salt)?; let headers = vec![ ("access_key".to_string(), auth.access_key.into_masked()), ("salt".to_string(), salt.into_masked()), @@ -489,7 +498,7 @@ impl self, req, connectors, )?) .headers(headers) - .body(Some(rapyd_req)) + .body(types::PaymentsCaptureType::get_request_body(self, req)?) .build(); Ok(Some(request)) } @@ -579,9 +588,14 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref 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)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let req_obj = rapyd::RapydRefundRequest::try_from(req)?; + let rapyd_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<rapyd::RapydRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(rapyd_req)) } @@ -593,12 +607,12 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref 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 body = types::RefundExecuteType::get_request_body(self, req)? + .ok_or(errors::ConnectorError::RequestEncodingFailed)?; + let req_body = types::RequestBody::get_inner_value(body).expose(); let auth: rapyd::RapydAuthType = rapyd::RapydAuthType::try_from(&req.connector_auth_type)?; let signature = - self.generate_signature(&auth, "post", "/v1/refunds", &rapyd_req, &timestamp, &salt)?; + self.generate_signature(&auth, "post", "/v1/refunds", &req_body, &timestamp, &salt)?; let headers = vec![ ("access_key".to_string(), auth.access_key.into_masked()), ("salt".to_string(), salt.into_masked()), @@ -610,7 +624,7 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref .url(&types::RefundExecuteType::get_url(self, req, connectors)?) .attach_default_headers() .headers(headers) - .body(Some(rapyd_req)) + .body(types::RefundExecuteType::get_request_body(self, req)?) .build(); Ok(Some(request)) } diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs index 5f39317f23c..7f8483a5649 100644 --- a/crates/router/src/connector/rapyd/transformers.rs +++ b/crates/router/src/connector/rapyd/transformers.rs @@ -46,15 +46,15 @@ pub struct PaymentFields { #[derive(Default, Debug, Serialize)] pub struct Address { - name: String, - line_1: String, - line_2: Option<String>, - line_3: Option<String>, + name: Secret<String>, + line_1: Secret<String>, + line_2: Option<Secret<String>>, + line_3: Option<Secret<String>>, city: Option<String>, - state: Option<String>, + state: Option<Secret<String>>, country: Option<String>, zip: Option<String>, - phone_number: Option<String>, + phone_number: Option<Secret<String>>, } #[derive(Debug, Clone, Serialize, Deserialize)] diff --git a/crates/router/src/connector/shift4.rs b/crates/router/src/connector/shift4.rs index fd62faaeb29..6f4150f1f5c 100644 --- a/crates/router/src/connector/shift4.rs +++ b/crates/router/src/connector/shift4.rs @@ -165,11 +165,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = shift4::Shift4PaymentsRequest::try_from(req)?; - let req = - utils::Encode::<shift4::Shift4PaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<shift4::Shift4PaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(req)) } @@ -451,11 +453,13 @@ impl fn get_request_body( &self, req: &types::PaymentsInitRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = shift4::Shift4PaymentsRequest::try_from(req)?; - let req = - utils::Encode::<shift4::Shift4PaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<shift4::Shift4PaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(req)) } @@ -531,11 +535,13 @@ impl fn get_request_body( &self, req: &types::PaymentsCompleteAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = shift4::Shift4PaymentsRequest::try_from(req)?; - let req = - utils::Encode::<shift4::Shift4PaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<shift4::Shift4PaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(req)) } @@ -609,9 +615,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let shift4_req = utils::Encode::<shift4::Shift4RefundRequest>::convert_and_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_req = shift4::Shift4RefundRequest::try_from(req)?; + let shift4_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<shift4::Shift4RefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(shift4_req)) } diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 22fd28ef705..b2f83abb53d 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -129,13 +129,13 @@ impl fn get_request_body( &self, req: &types::PaymentsPreProcessingRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req = stripe::StripeAchSourceRequest::try_from(req)?; - router_env::logger::info!(connector_request=?req); - let pre_processing_request = - utils::Encode::<stripe::StripeAchSourceRequest>::url_encode(&req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - + let pre_processing_request = types::RequestBody::log_and_get_request_body( + &req, + utils::Encode::<stripe::StripeAchSourceRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(pre_processing_request)) } @@ -244,12 +244,13 @@ impl fn get_request_body( &self, req: &types::ConnectorCustomerRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_request = stripe::CustomerRequest::try_from(req)?; - router_env::logger::info!(?connector_request); - let stripe_req = utils::Encode::<stripe::CustomerRequest>::url_encode(&connector_request) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - + let stripe_req = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<stripe::CustomerRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(stripe_req)) } @@ -360,12 +361,13 @@ impl fn get_request_body( &self, req: &types::TokenizationRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_request = stripe::TokenRequest::try_from(req)?; - router_env::logger::info!(?connector_request); - let stripe_req = utils::Encode::<stripe::TokenRequest>::url_encode(&connector_request) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - + let stripe_req = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<stripe::TokenRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(stripe_req)) } @@ -478,11 +480,13 @@ impl fn get_request_body( &self, req: &types::PaymentsCaptureRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_request = stripe::CaptureRequest::try_from(req)?; - router_env::logger::info!(?connector_request); - let stripe_req = utils::Encode::<stripe::CaptureRequest>::url_encode(&connector_request) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let stripe_req = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<stripe::CaptureRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(stripe_req)) } @@ -738,16 +742,18 @@ impl fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { match &req.request.payment_method_data { api_models::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => { stripe::get_bank_transfer_request_data(req, bank_transfer_data.deref()) } _ => { let req = stripe::PaymentIntentRequest::try_from(req)?; - router_env::logger::info!(connector_request=?req); - let request = utils::Encode::<stripe::PaymentIntentRequest>::url_encode(&req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let request = types::RequestBody::log_and_get_request_body( + &req, + utils::Encode::<stripe::PaymentIntentRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(request)) } } @@ -866,11 +872,13 @@ impl fn get_request_body( &self, req: &types::PaymentsCancelRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_request = stripe::CancelRequest::try_from(req)?; - router_env::logger::info!(?connector_request); - let stripe_req = utils::Encode::<stripe::CancelRequest>::url_encode(&connector_request) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let stripe_req = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<stripe::CancelRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(stripe_req)) } @@ -980,11 +988,13 @@ impl fn get_request_body( &self, req: &types::RouterData<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req = stripe::SetupIntentRequest::try_from(req)?; - router_env::logger::info!(connector_request=?req); - let stripe_req = utils::Encode::<stripe::SetupIntentRequest>::url_encode(&req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let stripe_req = types::RequestBody::log_and_get_request_body( + &req, + utils::Encode::<stripe::SetupIntentRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(stripe_req)) } @@ -1096,11 +1106,13 @@ impl services::ConnectorIntegration<api::Execute, types::RefundsData, types::Ref fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_request = stripe::RefundRequest::try_from(req)?; - router_env::logger::info!(?connector_request); - let stripe_req = utils::Encode::<stripe::RefundRequest>::url_encode(&connector_request) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let stripe_req = types::RequestBody::log_and_get_request_body( + &connector_request, + utils::Encode::<stripe::RefundRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(stripe_req)) } @@ -1531,11 +1543,13 @@ impl fn get_request_body( &self, req: &types::SubmitEvidenceRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let stripe_req = stripe::Evidence::try_from(req)?; - router_env::logger::info!(connector_request=?stripe_req); - let stripe_req_string = utils::Encode::<stripe::Evidence>::url_encode(&stripe_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let stripe_req_string = types::RequestBody::log_and_get_request_body( + &stripe_req, + utils::Encode::<stripe::Evidence>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(stripe_req_string)) } diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index ff24de28d5b..7e337c3b33a 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -2586,18 +2586,24 @@ pub struct StripeGpayToken { pub fn get_bank_transfer_request_data( req: &types::PaymentsAuthorizeRouterData, bank_transfer_data: &api_models::payments::BankTransferData, -) -> CustomResult<Option<String>, errors::ConnectorError> { +) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { match bank_transfer_data { api_models::payments::BankTransferData::AchBankTransfer { .. } => { let req = ChargesRequest::try_from(req)?; - let request = utils::Encode::<ChargesRequest>::url_encode(&req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let request = types::RequestBody::log_and_get_request_body( + &req, + utils::Encode::<ChargesRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(request)) } _ => { let req = PaymentIntentRequest::try_from(req)?; - let request = utils::Encode::<PaymentIntentRequest>::url_encode(&req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let request = types::RequestBody::log_and_get_request_body( + &req, + utils::Encode::<PaymentIntentRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(request)) } } diff --git a/crates/router/src/connector/trustpay.rs b/crates/router/src/connector/trustpay.rs index d89a7a4f073..3b6094c0c84 100644 --- a/crates/router/src/connector/trustpay.rs +++ b/crates/router/src/connector/trustpay.rs @@ -190,10 +190,13 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t fn get_request_body( &self, req: &types::RefreshTokenRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let trustpay_req = - utils::Encode::<trustpay::TrustpayAuthUpdateRequest>::convert_and_url_encode(req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_req = trustpay::TrustpayAuthUpdateRequest::try_from(req)?; + let trustpay_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<trustpay::TrustpayAuthUpdateRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(trustpay_req)) } @@ -387,11 +390,13 @@ impl fn get_request_body( &self, req: &types::PaymentsPreProcessingRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let create_intent_req = trustpay::TrustpayCreateIntentRequest::try_from(req)?; - let trustpay_req = - utils::Encode::<trustpay::TrustpayCreateIntentRequest>::url_encode(&create_intent_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let trustpay_req = types::RequestBody::log_and_get_request_body( + &create_intent_req, + utils::Encode::<trustpay::TrustpayCreateIntentRequest>::url_encode, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(trustpay_req)) } @@ -488,17 +493,21 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let trustpay_req = trustpay::TrustpayPaymentsRequest::try_from(req)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_req = trustpay::TrustpayPaymentsRequest::try_from(req)?; let trustpay_req_string = match req.payment_method { storage_models::enums::PaymentMethod::BankRedirect => { - utils::Encode::<trustpay::PaymentRequestBankRedirect>::encode_to_string_of_json( - &trustpay_req, + types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<trustpay::PaymentRequestBankRedirect>::encode_to_string_of_json, ) .change_context(errors::ConnectorError::RequestEncodingFailed)? } - _ => utils::Encode::<trustpay::PaymentRequestCards>::url_encode(&trustpay_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?, + _ => types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<trustpay::PaymentRequestCards>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?, }; Ok(Some(trustpay_req_string)) } @@ -587,16 +596,21 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let trustpay_req = trustpay::TrustpayRefundRequest::try_from(req)?; + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_req = trustpay::TrustpayRefundRequest::try_from(req)?; let trustpay_req_string = match req.payment_method { - storage_models::enums::PaymentMethod::BankRedirect => utils::Encode::< - trustpay::TrustpayRefundRequestBankRedirect, - >::encode_to_string_of_json( - &trustpay_req - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?, - _ => utils::Encode::<trustpay::TrustpayRefundRequestCards>::url_encode(&trustpay_req) + storage_models::enums::PaymentMethod::BankRedirect => { + types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<trustpay::TrustpayRefundRequestBankRedirect>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)? + } + _ => + types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<trustpay::TrustpayRefundRequestCards>::encode_to_string_of_json, + ) .change_context(errors::ConnectorError::RequestEncodingFailed)?, }; Ok(Some(trustpay_req_string)) diff --git a/crates/router/src/connector/worldline.rs b/crates/router/src/connector/worldline.rs index 86afebbaacb..4fa017a278d 100644 --- a/crates/router/src/connector/worldline.rs +++ b/crates/router/src/connector/worldline.rs @@ -354,11 +354,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme types::PaymentsCaptureData, types::PaymentsResponseData, >, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = worldline::ApproveRequest::try_from(req)?; - let worldline_req = - utils::Encode::<worldline::ApproveRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + + let worldline_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<worldline::ApproveRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(worldline_req)) } @@ -462,11 +465,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = worldline::PaymentsRequest::try_from(req)?; - let worldline_req = - utils::Encode::<worldline::PaymentsRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let worldline_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<worldline::PaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(worldline_req)) } @@ -553,13 +558,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let connector_req = worldline::WorldlineRefundRequest::try_from(req)?; - let refund_req = - utils::Encode::<worldline::WorldlineRefundRequest>::encode_to_string_of_json( - &connector_req, - ) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let refund_req = types::RequestBody::log_and_get_request_body( + &connector_req, + utils::Encode::<worldline::WorldlineRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(refund_req)) } diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs index d6a8d2044f3..93a9ae8b3bb 100644 --- a/crates/router/src/connector/worldline/transformers.rs +++ b/crates/router/src/connector/worldline/transformers.rs @@ -52,10 +52,10 @@ pub struct Order { pub struct BillingAddress { pub city: Option<String>, pub country_code: Option<api_enums::CountryAlpha2>, - pub house_number: Option<String>, + pub house_number: Option<Secret<String>>, pub state: Option<Secret<String>>, - pub state_code: Option<String>, - pub street: Option<String>, + pub state_code: Option<Secret<String>>, + pub street: Option<Secret<String>>, pub zip: Option<Secret<String>>, } diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs index 9c6a7cffab0..14ce33e6b67 100644 --- a/crates/router/src/connector/worldpay.rs +++ b/crates/router/src/connector/worldpay.rs @@ -405,12 +405,14 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let connector_req = WorldpayPaymentsRequest::try_from(req)?; - let worldpay_req = - ext_traits::Encode::<WorldpayPaymentsRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(worldpay_req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = WorldpayPaymentsRequest::try_from(req)?; + let worldpay_payment_request = types::RequestBody::log_and_get_request_body( + &connector_request, + ext_traits::Encode::<WorldpayPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(worldpay_payment_request)) } fn build_request( @@ -480,12 +482,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundExecuteRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { - let connector_req = WorldpayRefundRequest::try_from(req)?; - let req = - ext_traits::Encode::<WorldpayRefundRequest>::encode_to_string_of_json(&connector_req) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; - Ok(Some(req)) + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { + let connector_request = WorldpayRefundRequest::try_from(req)?; + let fiserv_refund_request = types::RequestBody::log_and_get_request_body( + &connector_request, + ext_traits::Encode::<WorldpayRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(fiserv_refund_request)) } fn get_url( diff --git a/crates/router/src/connector/zen.rs b/crates/router/src/connector/zen.rs index 6b2d3658287..b298cf7527f 100644 --- a/crates/router/src/connector/zen.rs +++ b/crates/router/src/connector/zen.rs @@ -199,11 +199,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P fn get_request_body( &self, req: &types::PaymentsAuthorizeRouterData, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = zen::ZenPaymentsRequest::try_from(req)?; - router_env::logger::info!(connector_request=?req_obj); - let zen_req = utils::Encode::<zen::ZenPaymentsRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let zen_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<zen::ZenPaymentsRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(zen_req)) } @@ -391,11 +393,13 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon fn get_request_body( &self, req: &types::RefundsRouterData<api::Execute>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { let req_obj = zen::ZenRefundRequest::try_from(req)?; - router_env::logger::info!(connector_request=?req_obj); - let zen_req = utils::Encode::<zen::ZenRefundRequest>::encode_to_string_of_json(&req_obj) - .change_context(errors::ConnectorError::RequestEncodingFailed)?; + let zen_req = types::RequestBody::log_and_get_request_body( + &req_obj, + utils::Encode::<zen::ZenRefundRequest>::encode_to_string_of_json, + ) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(Some(zen_req)) } diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs index 4a149f06519..f78a61d1f3c 100644 --- a/crates/router/src/core/payments/flows/session_flow.rs +++ b/crates/router/src/core/payments/flows/session_flow.rs @@ -116,10 +116,12 @@ fn mk_applepay_session_request( .clone(), }; - let applepay_session_request = - utils::Encode::<payment_types::ApplepaySessionRequest>::encode_to_string_of_json(&request) - .change_context(errors::ApiErrorResponse::InternalServerError) - .attach_printable("Failed to encode ApplePay session request to a string of json")?; + let applepay_session_request = types::RequestBody::log_and_get_request_body( + &request, + utils::Encode::<payment_types::ApplepaySessionRequest>::encode_to_string_of_json, + ) + .change_context(errors::ApiErrorResponse::InternalServerError) + .attach_printable("Failed to encode ApplePay session request to a string of json")?; let mut url = state.conf.connectors.applepay.base_url.to_owned(); url.push_str("paymentservices/paymentSession"); diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs index cdddc6b3afa..33aef926591 100644 --- a/crates/router/src/core/webhooks.rs +++ b/crates/router/src/core/webhooks.rs @@ -18,7 +18,7 @@ use crate::{ routes::AppState, services, types::{ - api, domain, + self, api, domain, storage::{self, enums}, transformers::{ForeignInto, ForeignTryInto}, }, @@ -570,10 +570,12 @@ pub async fn trigger_webhook_to_merchant<W: api::OutgoingWebhookType>( let transformed_outgoing_webhook = W::from(webhook); - let transformed_outgoing_webhook_string = - Encode::<serde_json::Value>::encode_to_string_of_json(&transformed_outgoing_webhook) - .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed) - .attach_printable("There was an issue when encoding the outgoing webhook body")?; + let transformed_outgoing_webhook_string = types::RequestBody::log_and_get_request_body( + &transformed_outgoing_webhook, + Encode::<serde_json::Value>::encode_to_string_of_json, + ) + .change_context(errors::WebhooksFlowError::OutgoingWebhookEncodingFailed) + .attach_printable("There was an issue when encoding the outgoing webhook body")?; let mut header = vec![( reqwest::header::CONTENT_TYPE.to_string(), diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs index 26cec958c05..c8d69d7d51c 100644 --- a/crates/router/src/services/api.rs +++ b/crates/router/src/services/api.rs @@ -78,7 +78,7 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Re fn get_request_body( &self, _req: &types::RouterData<T, Req, Resp>, - ) -> CustomResult<Option<String>, errors::ConnectorError> { + ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> { Ok(None) } diff --git a/crates/router/src/services/api/request.rs b/crates/router/src/services/api/request.rs index 59dd3f0e4c5..8caa9ff9e8b 100644 --- a/crates/router/src/services/api/request.rs +++ b/crates/router/src/services/api/request.rs @@ -5,7 +5,10 @@ use masking::{ExposeInterface, Secret}; use router_env::{instrument, tracing}; use serde::{Deserialize, Serialize}; -use crate::core::errors::{self, CustomResult}; +use crate::{ + core::errors::{self, CustomResult}, + types, +}; pub(crate) type Headers = collections::HashSet<(String, Maskable<String>)>; @@ -211,8 +214,8 @@ impl RequestBuilder { self } - pub fn body(mut self, body: Option<String>) -> Self { - self.payload = body.map(From::from); + pub fn body(mut self, option_body: Option<types::RequestBody>) -> Self { + self.payload = option_body.map(types::RequestBody::get_inner_value); self } diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs index 881d4e7a2b2..def2c1213fd 100644 --- a/crates/router/src/types.rs +++ b/crates/router/src/types.rs @@ -812,3 +812,23 @@ impl<F1, F2, T1, T2> From<(&RouterData<F1, T1, PaymentsResponseData>, T2)> } } } + +#[derive(Clone, Debug)] +pub struct RequestBody(Secret<String>); + +impl RequestBody { + pub fn log_and_get_request_body<T, F>( + body: T, + encoder: F, + ) -> errors::CustomResult<Self, errors::ParsingError> + where + F: FnOnce(T) -> errors::CustomResult<String, errors::ParsingError>, + T: std::fmt::Debug, + { + router_env::logger::info!(connector_request_body=?body); + Ok(Self(Secret::new(encoder(body)?))) + } + pub fn get_inner_value(request_body: Self) -> Secret<String> { + request_body.0 + } +}
feat
enforce logging for connector requests (#1467)
9903119e8b1f2c08ee99e630c1c64cdeb7c34df4
2024-06-06 15:14:35
github-actions
chore(version): 2024.06.06.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index 254f7d7709a..be8e8958322 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2024.06.06.1 + +### Features + +- **router:** Add an api to migrate the apple pay certificates from connector metadata to `connector_wallets_details` column in merchant connector account ([#4790](https://github.com/juspay/hyperswitch/pull/4790)) ([`7a94237`](https://github.com/juspay/hyperswitch/commit/7a9423759e79167c4093c3482ea56f619cf95635)) + +### Refactors + +- **webhooks:** Extract incoming and outgoing webhooks into separate modules ([#4870](https://github.com/juspay/hyperswitch/pull/4870)) ([`b1cb053`](https://github.com/juspay/hyperswitch/commit/b1cb053a55e9ce4d78f7770b53e39700311d9cd4)) + +**Full Changelog:** [`2024.06.06.0...2024.06.06.1`](https://github.com/juspay/hyperswitch/compare/2024.06.06.0...2024.06.06.1) + +- - - + ## 2024.06.06.0 ### Features
chore
2024.06.06.1
d95a64d6c9b870bdc38aa091cf9bf660b1ea404e
2023-10-06 16:54:20
Sakil Mostak
feat(connector): [Paypal] Implement 3DS for Cards (#2443)
false
diff --git a/crates/router/src/connector/paypal.rs b/crates/router/src/connector/paypal.rs index b82223f3acc..9ca418aa04a 100644 --- a/crates/router/src/connector/paypal.rs +++ b/crates/router/src/connector/paypal.rs @@ -8,7 +8,8 @@ use error_stack::{IntoReport, ResultExt}; use masking::PeekInterface; use transformers as paypal; -use self::transformers::PaypalMeta; +use self::transformers::{PaypalAuthResponse, PaypalMeta}; +use super::utils::PaymentsCompleteAuthorizeRequestData; use crate::{ configs::settings, connector::{ @@ -391,24 +392,27 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P data: &types::PaymentsAuthorizeRouterData, res: Response, ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> { - match data.payment_method { - diesel_models::enums::PaymentMethod::Wallet - | diesel_models::enums::PaymentMethod::BankRedirect => { - let response: paypal::PaypalRedirectResponse = res - .response - .parse_struct("paypal PaymentsRedirectResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + let response: PaypalAuthResponse = + res.response + .parse_struct("paypal PaypalAuthResponse") + .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + + match response { + PaypalAuthResponse::PaypalOrdersResponse(response) => { types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), http_code: res.status_code, }) } - _ => { - let response: paypal::PaypalOrdersResponse = res - .response - .parse_struct("paypal PaymentsOrderResponse") - .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; + PaypalAuthResponse::PaypalRedirectResponse(response) => { + types::RouterData::try_from(types::ResponseRouterData { + response, + data: data.clone(), + http_code: res.status_code, + }) + } + PaypalAuthResponse::PaypalThreeDsResponse(response) => { types::RouterData::try_from(types::ResponseRouterData { response, data: data.clone(), @@ -450,10 +454,10 @@ 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(), + let complete_authorize_url = if req.request.is_auto_capture()? { + "capture".to_string() + } else { + "authorize".to_string() }; Ok(format!( "{}v2/checkout/orders/{}/{complete_authorize_url}", @@ -493,7 +497,7 @@ impl ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> { let response: paypal::PaypalOrdersResponse = res .response - .parse_struct("paypal PaymentsOrderResponse") + .parse_struct("paypal PaypalOrdersResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; types::RouterData::try_from(types::ResponseRouterData { response, @@ -559,6 +563,19 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe )?; format!("v2/payments/captures/{capture_id}") } + // only set when payment is done through card 3DS + //because no authorize or capture id is generated during payment authorize call for card 3DS + transformers::PaypalPaymentIntent::Authenticate => { + format!( + "v2/checkout/orders/{}", + req.request + .connector_transaction_id + .get_connector_transaction_id() + .change_context( + errors::ConnectorError::MissingConnectorTransactionID + )? + ) + } }; Ok(format!("{}{psync_url}", self.base_url(connectors))) } diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs index bf40cf0a935..932cf67addd 100644 --- a/crates/router/src/connector/paypal/transformers.rs +++ b/crates/router/src/connector/paypal/transformers.rs @@ -62,6 +62,7 @@ mod webhook_headers { pub enum PaypalPaymentIntent { Capture, Authorize, + Authenticate, } #[derive(Default, Debug, Clone, Serialize, Eq, PartialEq, Deserialize)] @@ -90,6 +91,23 @@ pub struct CardRequest { name: Secret<String>, number: Option<cards::CardNumber>, security_code: Option<Secret<String>>, + attributes: Option<ThreeDsSetting>, +} + +#[derive(Debug, Serialize)] +pub struct ThreeDsSetting { + verification: ThreeDsMethod, +} + +#[derive(Debug, Serialize)] +pub struct ThreeDsMethod { + method: ThreeDsType, +} + +#[derive(Debug, Serialize)] +#[serde(rename_all = "SCREAMING_SNAKE_CASE")] +pub enum ThreeDsType { + ScaAlways, } #[derive(Debug, Serialize)] @@ -251,12 +269,22 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP let card = item.router_data.request.get_card()?; let expiry = Some(card.get_expiry_date_as_yyyymm("-")); + let attributes = match item.router_data.auth_type { + api_models::enums::AuthenticationType::ThreeDs => Some(ThreeDsSetting { + verification: ThreeDsMethod { + method: ThreeDsType::ScaAlways, + }, + }), + api_models::enums::AuthenticationType::NoThreeDs => None, + }; + let payment_source = Some(PaymentSourceItem::Card(CardRequest { billing_address: get_address_info(item.router_data.address.billing.as_ref())?, expiry, name: ccard.card_holder_name.clone(), number: Some(ccard.card_number.clone()), security_code: Some(ccard.card_cvc.clone()), + attributes, })); Ok(Self { @@ -631,7 +659,14 @@ pub struct PurchaseUnitItem { pub payments: PaymentsCollection, } -#[derive(Debug, Serialize, Deserialize)] +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PaypalThreeDsResponse { + id: String, + status: PaypalOrderStatus, + links: Vec<PaypalLinks>, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] pub struct PaypalOrdersResponse { id: String, intent: PaypalPaymentIntent, @@ -653,10 +688,21 @@ pub struct PaypalRedirectResponse { links: Vec<PaypalLinks>, } +// Note: Don't change order of deserialization of variant, priority is in descending order +#[derive(Debug, Deserialize)] +#[serde(untagged)] +pub enum PaypalAuthResponse { + PaypalOrdersResponse(PaypalOrdersResponse), + PaypalRedirectResponse(PaypalRedirectResponse), + PaypalThreeDsResponse(PaypalThreeDsResponse), +} + +// Note: Don't change order of deserialization of variant, priority is in descending order #[derive(Debug, Deserialize)] #[serde(untagged)] pub enum PaypalSyncResponse { PaypalOrdersSyncResponse(PaypalOrdersResponse), + PaypalThreeDsSyncResponse(PaypalThreeDsSyncResponse), PaypalRedirectSyncResponse(PaypalRedirectResponse), PaypalPaymentsSyncResponse(PaypalPaymentsSyncResponse), } @@ -669,6 +715,24 @@ pub struct PaypalPaymentsSyncResponse { supplementary_data: PaypalSupplementaryData, } +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct PaypalThreeDsSyncResponse { + id: String, + status: PaypalOrderStatus, + // provided to separated response of card's 3DS from other + payment_source: CardsData, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CardsData { + card: CardDetails, +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct CardDetails { + last_digits: String, +} + #[derive(Debug, Serialize, Deserialize)] pub struct PaypalMeta { pub authorize_id: Option<String>, @@ -700,6 +764,7 @@ fn get_id_based_on_intent( .next()? .id, ), + PaypalPaymentIntent::Authenticate => None, } }() .ok_or_else(|| errors::ConnectorError::MissingConnectorTransactionID.into()) @@ -738,6 +803,10 @@ impl<F, T> }), types::ResponseId::ConnectorTransactionId(item.response.id), ), + + PaypalPaymentIntent::Authenticate => { + Err(errors::ConnectorError::ResponseDeserializationFailed)? + } }; //payment collection will always have only one element as we only make one transaction per order. let payment_collection = &item @@ -775,10 +844,9 @@ impl<F, T> } fn get_redirect_url( - item: PaypalRedirectResponse, + link_vec: Vec<PaypalLinks>, ) -> CustomResult<Option<Url>, errors::ConnectorError> { let mut link: Option<Url> = None; - let link_vec = item.links; for item2 in link_vec.iter() { if item2.rel == "payer-action" { link = item2.href.clone(); @@ -787,12 +855,24 @@ fn get_redirect_url( Ok(link) } -impl<F, T> TryFrom<types::ResponseRouterData<F, PaypalSyncResponse, T, types::PaymentsResponseData>> - for types::RouterData<F, T, types::PaymentsResponseData> +impl<F> + TryFrom< + types::ResponseRouterData< + F, + PaypalSyncResponse, + types::PaymentsSyncData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( - item: types::ResponseRouterData<F, PaypalSyncResponse, T, types::PaymentsResponseData>, + item: types::ResponseRouterData< + F, + PaypalSyncResponse, + types::PaymentsSyncData, + types::PaymentsResponseData, + >, ) -> Result<Self, Self::Error> { match item.response { PaypalSyncResponse::PaypalOrdersSyncResponse(response) => { @@ -816,6 +896,13 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, PaypalSyncResponse, T, types::Pa http_code: item.http_code, }) } + PaypalSyncResponse::PaypalThreeDsSyncResponse(response) => { + Self::try_from(types::ResponseRouterData { + response, + data: item.data, + http_code: item.http_code, + }) + } } } } @@ -832,7 +919,7 @@ impl<F, T> item.response.clone().status, item.response.intent.clone(), )); - let link = get_redirect_url(item.response.clone())?; + let link = get_redirect_url(item.response.links.clone())?; let connector_meta = serde_json::json!(PaypalMeta { authorize_id: None, capture_id: None, @@ -857,6 +944,119 @@ impl<F, T> } } +impl<F> + TryFrom< + types::ResponseRouterData< + F, + PaypalThreeDsSyncResponse, + types::PaymentsSyncData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + PaypalThreeDsSyncResponse, + types::PaymentsSyncData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + Ok(Self { + // status is hardcoded because this try_from will only be reached in card 3ds before the completion of complete authorize flow. + // also force sync won't be hit in terminal status thus leaving us with only one status to get here. + status: storage_enums::AttemptStatus::AuthenticationPending, + 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 + }) + } +} + +impl<F> + TryFrom< + types::ResponseRouterData< + F, + PaypalThreeDsResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + > for types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData> +{ + type Error = error_stack::Report<errors::ConnectorError>; + fn try_from( + item: types::ResponseRouterData< + F, + PaypalThreeDsResponse, + types::PaymentsAuthorizeData, + types::PaymentsResponseData, + >, + ) -> Result<Self, Self::Error> { + let connector_meta = serde_json::json!(PaypalMeta { + authorize_id: None, + capture_id: None, + psync_flow: PaypalPaymentIntent::Authenticate // when there is no capture or auth id present + }); + + let status = storage_enums::AttemptStatus::foreign_from(( + item.response.clone().status, + PaypalPaymentIntent::Authenticate, + )); + let link = get_redirect_url(item.response.links.clone())?; + + Ok(Self { + status, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(item.response.id), + redirection_data: Some(paypal_threeds_link(( + link, + item.data.request.complete_authorize_url.clone(), + ))?), + mandate_reference: None, + connector_metadata: Some(connector_meta), + network_txn_id: None, + connector_response_reference_id: None, + }), + ..item.data + }) + } +} + +fn paypal_threeds_link( + (redirect_url, complete_auth_url): (Option<Url>, Option<String>), +) -> CustomResult<services::RedirectForm, errors::ConnectorError> { + let mut redirect_url = + redirect_url.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?; + let complete_auth_url = + complete_auth_url.ok_or(errors::ConnectorError::MissingRequiredField { + field_name: "complete_authorize_url", + })?; + let mut form_fields = std::collections::HashMap::from_iter( + redirect_url + .query_pairs() + .map(|(key, value)| (key.to_string(), value.to_string())), + ); + + // paypal requires return url to be passed as a field along with payer_action_url + form_fields.insert(String::from("redirect_uri"), complete_auth_url); + + // Do not include query params in the endpoint + redirect_url.set_query(None); + + Ok(services::RedirectForm::Form { + endpoint: redirect_url.to_string(), + method: services::Method::Get, + form_fields, + }) +} + impl<F, T> TryFrom< types::ResponseRouterData<F, PaypalPaymentsSyncResponse, T, types::PaymentsResponseData>,
feat
[Paypal] Implement 3DS for Cards (#2443)
ea119eb856cf47c5e28117ba9ecfce722aff541f
2023-07-19 19:52:34
Hrithikesh
fix(connector): stripe mandate failure and other ui tests failures (#1742)
false
diff --git a/.github/testcases/ui_tests.json b/.github/testcases/ui_tests.json index 8ab5803b5b3..135059803d9 100644 --- a/.github/testcases/ui_tests.json +++ b/.github/testcases/ui_tests.json @@ -69,19 +69,19 @@ "id": 12, "name": "aci przelewy24", "connector": "aci", - "request": "{\"amount\":6540,\"currency\":\"PLN\",\"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_redirect\",\"payment_method_type\":\"przelewy24\",\"payment_method_data\":{\"bank_redirect\":{\"przelewy24\":{\"billing_details\":{\"email\":\"[email protected]\"}}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "request": "{\"amount\":6540,\"currency\":\"PLN\",\"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_type\":\"przelewy24\",\"payment_method_data\":{\"bank_redirect\":{\"przelewy24\":{\"billing_details\":{\"email\":\"[email protected]\"}}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "13": { "id": 13, "name": "aci trustly", "connector": "aci", - "request": "{\"amount\":6540,\"currency\":\"EUR\",\"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_redirect\",\"payment_method_type\":\"trustly\",\"payment_method_data\":{\"bank_redirect\":{\"trustly\":{\"country\":\"DE\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "request": "{\"amount\":6540,\"currency\":\"EUR\",\"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_type\":\"trustly\",\"payment_method_data\":{\"bank_redirect\":{\"trustly\":{\"country\":\"DE\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "14": { "id": "14", "name": "aci interac", "connector": "aci", - "request": "{\"amount\":6540,\"currency\":\"CAD\",\"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_redirect\",\"payment_method_type\":\"interac\",\"payment_method_data\":{\"bank_redirect\":{\"interac\":{\"email\":\"[email protected]\",\"country\":\"CA\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + "request": "{\"amount\":6540,\"currency\":\"CAD\",\"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_type\":\"interac\",\"payment_method_data\":{\"bank_redirect\":{\"interac\":{\"email\":\"[email protected]\",\"country\":\"CA\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" }, "15": { "id": 15, @@ -165,7 +165,7 @@ "id": 28, "name": "Stripe Bancontact Card success ", "connector": "stripe", - "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\":\"bancontact_card\",\"payment_method_data\":{\"bank_redirect\":{\"bancontact_card\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"wells_fargo\",\"preferred_language\":\"en\",\"country\":\"DE\"}}}}" + "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\":\"bancontact_card\",\"payment_method_data\":{\"bank_redirect\":{\"bancontact_card\":{\"billing_details\":{\"billing_name\":\"John Doe\",\"email\":\"[email protected]\"},\"bank_name\":\"wells_fargo\",\"preferred_language\":\"en\",\"country\":\"DE\"}}}}" }, "29": { "id": 29, @@ -213,7 +213,7 @@ "id": 36, "name": "Mollie Ideal", "connector": "mollie", - "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\":\"ideal\",\"payment_method_data\":{\"bank_redirect\":{\"ideal\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"american_express\",\"preferred_language\":\"en\",\"country\":\"DE\"}}}}" + "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://hs-payments-test.netlify.app/payments/\",\"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\":\"ideal\",\"payment_method_data\":{\"bank_redirect\":{\"ideal\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"american_express\",\"preferred_language\":\"en\",\"country\":\"DE\"}}}}" }, "37": { "id": 37, @@ -291,7 +291,7 @@ "id": 49, "name": "Worldline Ideal", "connector": "worldline", - "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_account_iban\":\"DE46940594210000012345\",\"bank_name\":\"\",\"preferred_language\":\"en\",\"country\":\"DE\"}}}}" + "request": "{\"amount\":6540,\"currency\":\"EUR\",\"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_redirect\",\"payment_method_type\":\"ideal\",\"payment_method_data\":{\"bank_redirect\":{\"ideal\":{\"billing_details\":{\"billing_name\":\"Example\"},\"bank_name\":\"abn_amro\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"NL\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"NL\",\"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\"}}" }, "50": { "id": 50, @@ -306,7 +306,7 @@ "request": "{\"amount\":100,\"currency\":\"EUR\",\"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\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"setup_future_usage\":\"off_session\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"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_debit\",\"payment_method_type\":\"sepa\",\"payment_method_data\":{\"bank_debit\":{\"sepa_bank_debit\":{\"account_number\":\"40308669\",\"routing_number\":\"121000358\",\"sort_code\":\"560036\",\"shopper_email\":\"[email protected]\",\"card_holder_name\":\"joseph Doe\",\"bank_account_holder_name\":\"David Archer\",\"billing_details\":{\"houseNumberOrName\":\"50\",\"street\":\"Test Street\",\"city\":\"Amsterdam\",\"stateOrProvince\":\"NY\",\"postalCode\":\"12010\",\"country\":\"GB\",\"name\":\"A. Klaassen\",\"email\":\"[email protected]\"},\"reference\":\"daslvcgbaieh\",\"iban\":\"DE94888888889876543210\"}}}}" }, "52": { - "id": 52, + "id": "52", "name": "ADYEN IDEAL", "connector": "adyen_uk", "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://hs-payments-test.netlify.app/payments/\",\"billing\":{\"address\":{\"first_name\":\"John\",\"last_name\":\"Doe\",\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"NL\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"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\":\"ideal\",\"payment_method_data\":{\"bank_redirect\":{\"ideal\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"ing\",\"preferred_language\":\"en\",\"country\":\"NL\"}}}}" @@ -357,7 +357,7 @@ "id": 60, "name": "stripe card_no_3ds mandate payment", "connector": "stripe", - "request": "{\"amount\":10000,\"currency\":\"USD\",\"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://google.com\",\"setup_future_usage\":\"off_session\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"13.232.74.226\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"CL-BRW1\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"13.232.74.226\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":7000,\"currency\":\"USD\"}}}}" + "request": "{\"amount\":10000,\"currency\":\"USD\",\"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://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"13.232.74.226\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"25\",\"card_holder_name\":\"CL-BRW1\",\"card_cvc\":\"123\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"13.232.74.226\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":7000,\"currency\":\"USD\"}}}}" }, "61": { "id": 61, @@ -366,7 +366,7 @@ "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://hs-payments-test.netlify.app/payments/\",\"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\":\"ing\",\"preferred_language\":\"en\",\"country\":\"AT\"}}}}" }, "62": { - "id": 62, + "id": "62", "name": "adyen card 3ds success", "connector": "adyen_uk", "request": "{\"amount\":10000,\"currency\":\"USD\",\"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\",\"setup_future_usage\":\"off_session\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4917 6100 0000 0000\",\"card_exp_month\":\"03\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"CL-BRW1\",\"card_cvc\":\"737\"}}}" @@ -933,7 +933,7 @@ "id": 156, "name": "Authorizedotnet Paypal Success", "connector": "authorizedotnet", - "request": "{\"amount\":1200,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1200,\"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\",\"setup_future_usage\":\"off_session\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"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\":\"wallet\",\"payment_method_type\":\"paypal\",\"payment_method_data\":{\"wallet\":{\"paypal_redirect\":{}}}}" + "request": "{\"amount\":120,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":120,\"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\",\"setup_future_usage\":\"off_session\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"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\":\"wallet\",\"payment_method_type\":\"paypal\",\"payment_method_data\":{\"wallet\":{\"paypal_redirect\":{}}}}" }, "157": { "id": 157, @@ -972,7 +972,7 @@ "request": "{\"amount\":6540,\"currency\":\"EUR\",\"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\":\"wallet\",\"payment_method_type\":\"ali_pay_hk\",\"payment_method_data\":{\"wallet\":{\"ali_pay_hk_redirect\":{}}}}" }, "163": { - "id": 163, + "id": "163", "name": "Adyen ClearPay", "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\":\"pay_later\",\"payment_method_type\":\"afterpay_clearpay\",\"payment_method_data\":{\"pay_later\":{\"afterpay_clearpay_redirect\":{\"billing_email\":\"[email protected]\",\"billing_name\":\"sakil\"}}},\"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\"}},\"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\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}}}" @@ -1147,15 +1147,15 @@ }, "192": { "id": 192, - "name": "Globepay wechatpay QR Code", + "name": "Globepay Alipay QR Code", "connector": "globepay", - "request": "{\"amount\":700,\"currency\":\"GBP\",\"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://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"first_name\":\"John\",\"last_name\":\"Doe\",\"country\":\"SE\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"SE\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"payment_method\":\"wallet\",\"payment_method_type\":\"ali_pay\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"wallet\":{\"ali_pay_redirect\":{}}}}" + "request": "{\"amount\":700,\"currency\":\"GBP\",\"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://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"first_name\":\"John\",\"last_name\":\"Doe\",\"country\":\"SE\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"SE\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"payment_method\":\"wallet\",\"payment_method_type\":\"ali_pay\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"wallet\":{\"ali_pay_qr\":{}}}}" }, "193": { "id": 193, "name": "Globepay wechatpay qr code", "connector": "globepay", - "request": "{\"amount\":7000,\"currency\":\"GBP\",\"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://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"first_name\":\"John\",\"last_name\":\"Doe\",\"country\":\"SE\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"SE\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"payment_method\":\"wallet\",\"payment_method_type\":\"we_chat_pay\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"wallet\":{\"we_chat_pay\":{}}}}" + "request": "{\"amount\":7000,\"currency\":\"GBP\",\"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://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"first_name\":\"John\",\"last_name\":\"Doe\",\"country\":\"SE\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"SE\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"order_details\":{\"product_name\":\"Socks\",\"amount\":7000,\"quantity\":1}},\"payment_method\":\"wallet\",\"payment_method_type\":\"we_chat_pay\",\"payment_experience\":\"redirect_to_url\",\"payment_method_data\":{\"wallet\":{\"we_chat_pay_qr\":{}}}}" }, "194": { "id": 194, @@ -1189,13 +1189,13 @@ }, "199": { "id": 199, - "name": "bluesnap card no three ds success\" working fine", + "name": "bluesnap card no three ds success", "connector": "bluesnap", "request": "{\"amount\":10000,\"currency\":\"USD\",\"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\":\"no_three_ds\",\"return_url\":\"https://hs-payments-test.netlify.app/payments\",\"setup_future_usage\":\"off_session\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"4263982640269299\",\"card_exp_month\":\"02\",\"card_exp_year\":\"2026\",\"card_holder_name\":\"CL-BRW1\",\"card_cvc\":\"887\"}}}" }, "200": { "id": 200, - "name": "blusnap 3ds card sucess >>>>.", + "name": "blusnap 3ds card success", "connector": "bluesnap", "request": "{\"amount\":10000,\"currency\":\"USD\",\"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://google.com\",\"setup_future_usage\":\"off_session\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"payment_method\":\"card\",\"payment_method_data\":{\"card\":{\"card_number\":\"5200000000001096\",\"card_exp_month\":\"10\",\"card_exp_year\":\"2026\",\"card_holder_name\":\"CL-BRW1\",\"card_cvc\":\"123\"}}}" }, @@ -1206,7 +1206,7 @@ "request": "{\"amount\":101,\"currency\":\"PLN\",\"confirm\":true,\"business_country\":\"US\",\"business_label\":\"default\",\"amount_to_capture\":97,\"customer_id\":\"custhype1232\",\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"authentication_type\":\"three_ds\",\"return_url\":\"https://hs-payments-test.netlify.app/payments\",\"email\":\"[email protected]\",\"name\":\"Joseph Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"Its my first payment request\",\"statement_descriptor_name\":\"Juspay\",\"statement_descriptor_suffix\":\"Router\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4242424242424242\",\"card_exp_month\":\"10\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"100\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"CA\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"CA\",\"zip\":\"94122\",\"country\":\"PL\",\"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\":\"109.71.40.0\"},\"metadata\":{\"order_category\":\"applepay\"},\"order_details\":[{\"product_name\":\"Apple iphone 15\",\"quantity\":1,\"amount\":101,\"account_name\":\"transaction_processing\"}]}" }, "202": { - "id": 202, + "id": "202", "name": "ADYEN PAYPAL", "connector": "adyen_uk", "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\":{\"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\":\"wallet\",\"payment_method_type\":\"paypal\",\"payment_method_data\":{\"wallet\":{\"paypal_redirect\":{}}}}" @@ -1288,5 +1288,65 @@ "name": "card no 3ds mandates", "connector": "noon", "request": "{\"amount\":6540,\"currency\":\"AED\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":10,\"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\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000000000002701\",\"card_exp_month\":\"10\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"257\"}},\"setup_future_usage\":\"off_session\",\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"in sit\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"single_use\":{\"amount\":6540,\"currency\":\"AED\"}}},\"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.0.0.1\",\"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\",\"order_details\":{\"product_name\":\"test\",\"quantity\":1,\"amount\":10}},\"connector_metadata\":{\"noon\":{\"order_category\":\"pay\"}}}" + }, + "216": { + "id": 216, + "name": "authorizedotnet paypal success", + "connector": "authorizedotnet", + "request": "{\"amount\":1200,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1200,\"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\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"payment_method\":\"wallet\",\"payment_method_type\":\"paypal\",\"payment_method_data\":{\"wallet\":{\"paypal_redirect\":{}}}}" + }, + "217": { + "id": 217, + "name": "Authorizedotnet google pay", + "connector": "authorizedotnet", + "request": "{\"amount\":7000,\"currency\":\"USD\",\"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://google.com\",\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"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\":\"wallet\",\"payment_method_type\":\"google_pay\",\"payment_method_data\":{\"wallet\":{\"google_pay\":{\"description\":\"Visa β€’β€’β€’β€’ 1111\",\"tokenization_data\":{\"type\":\"PAYMENT_GATEWAY\",\"token\":\"{\\\"signature\\\":\\\"MEUCIQCHhAbGg0iMURBNqK1MZDhuN/I+n9icOu/Z3woKZHpbQgIgUbJxfAihIE+MNVmZcKhVSUKai61FhRuCbA28bpIzaVE\\\\u003d\\\",\\\"protocolVersion\\\":\\\"ECv1\\\",\\\"signedMessage\\\":\\\"{\\\\\\\"encryptedMessage\\\\\\\":\\\\\\\"H2ADxvYvqwjKF5A9LuyM/Iq9XYMMmA7R31nZY4LDojSw7V4OE1JpErb3emwdcqvHBV0TSQeJJKraQU5Lq0QGoWRyIrwRo1je0cJf72BGDYguu4MHrROrNguh5O1E0WFyXoJOJ89OkIb8CmOpmk9epS9FQmZ/NsXQNHv6MdAJR0eKtzmV6lUmaNkK1oW9TvJXZciGV8pMCjVA2qZcnxUYtrsl5CNPFqKk2QlKE2SUgrunmI9NcTv97YVQ4miPwc03RQmTQted5obD26POM2wN0tJCdT/U+0bPPxV8bexq/IIGP6hYTVnAVKP4UTFXNmitB9MwasihhXfq+bvw70MUDawUTcxtSIekcPiVC2iNJwiaeABH6wEO7FIsFW4yG9ZjcYFdWENug/dfB82ghCN7LLmHmNpxzfA9Mon2IoX9IAB533SQx2XJagp4zPAxkM+xEQ\\\\\\\\u003d\\\\\\\\u003d\\\\\\\",\\\\\\\"ephemeralPublicKey\\\\\\\":\\\\\\\"BHVIL0CNahS1YUaLuweHPOBPzuutlnrw86Yjg1CFtbRAECC0LAJdqdSC1FvYw7MF8mCEvThJ8uCx8V3mLWPpX7o\\\\\\\\u003d\\\\\\\",\\\\\\\"tag\\\\\\\":\\\\\\\"7DemwQLPSqJp/fNqzPCj9UIzRkIirA4N6Ju7nxFMB1M\\\\\\\\u003d\\\\\\\"}\\\"}\"},\"type\":\"CARD\",\"info\":{\"card_network\":\"VISA\",\"card_details\":\"1111\"}}}}}" + }, + "218": { + "id": 218, + "name": "UPI iatapay", + "connector": "iatapay", + "request": "{\"amount\":5000,\"currency\":\"INR\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":5000,\"customer_id\":\"IatapayCustomer\",\"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\":\"upi\",\"payment_method_type\":\"upi_collect\",\"payment_method_data\":{\"upi\":{\"vpa_id\":\"successtest@iata\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"IN\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + }, + "219": { + "id": 219, + "name": "Adyen Blik Payment", + "connector": "adyen_uk", + "request": "{\"amount\":1000,\"currency\":\"PLN\",\"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\":\"PL\"}},\"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\":\"blik\",\"payment_experience\":\"display_wait_screen\",\"payment_method_data\":{\"bank_redirect\":{\"blik\":{\"billing_details\":{\"billing_name\":\"John Doe\"},\"bank_name\":\"american_express\",\"blik_code\":\"777123\",\"preferred_language\":\"en\",\"country\":\"PL\"}}}}" + }, + "220": { + "id": 220, + "name": "nexinets paypal success", + "connector": "nexinets", + "request": "{\"amount\":1200,\"currency\":\"EUR\",\"confirm\":true,\"capture_method\":\"automatic\",\"capture_on\":\"2022-09-10T10:11:12Z\",\"amount_to_capture\":1200,\"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\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"browser_info\":{\"user_agent\":\"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36\",\"accept_header\":\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\",\"language\":\"nl-NL\",\"color_depth\":24,\"screen_height\":723,\"screen_width\":1536,\"time_zone\":0,\"java_enabled\":true,\"java_script_enabled\":true,\"ip_address\":\"127.0.0.1\"},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"John\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"payment_method\":\"wallet\",\"payment_method_type\":\"paypal\",\"payment_method_data\":{\"wallet\":{\"paypal_redirect\":{}}}}" + }, + "221": { + "id": 221, + "name": "nexinets 3ds challenge success scenario", + "connector": "nexinets", + "request": "{\"amount\":10000,\"currency\":\"EUR\",\"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\":\"three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000007000000031\",\"card_exp_month\":\"05\",\"card_exp_year\":\"25\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + }, + "222": { + "id": 222, + "name": "nexinets ideal success", + "connector": "nexinets", + "request": "{\"amount\":6540,\"currency\":\"EUR\",\"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_redirect\",\"payment_method_type\":\"ideal\",\"payment_method_data\":{\"bank_redirect\":{\"ideal\":{\"billing_details\":{\"billing_name\":\"Example\"},\"bank_name\":\"ing\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"shipping\":{\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"},\"phone\":{\"number\":\"8056594427\",\"country_code\":\"+91\"}},\"statement_descriptor_name\":\"joseph\",\"statement_descriptor_suffix\":\"JS\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"}}" + }, + "223": { + "id": 223, + "name": "Adyen PaySafeCard", + "connector": "adyen_uk", + "request": "{\"amount\":6540,\"currency\":\"EUR\",\"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\":\"gift_card\",\"payment_method_type\":\"pay_safe_card\",\"payment_method_data\":{\"gift_card\":{\"pay_safe_card\":{}}}}" + }, + "224": { + "id": 224, + "name": "Oxxo", + "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\":\"oxxo\",\"payment_method_data\":{\"voucher\":{\"oxxo\":{}}}}" + }, + "225": { + "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\"}}}}" } } diff --git a/.github/workflows/connector-ui-sanity-tests.yml b/.github/workflows/connector-ui-sanity-tests.yml index d13b545c5c4..407687c9dea 100644 --- a/.github/workflows/connector-ui-sanity-tests.yml +++ b/.github/workflows/connector-ui-sanity-tests.yml @@ -69,8 +69,8 @@ jobs: matrix: connector: # do not use more than 2 runners, try to group less time taking connectors together - - stripe,airwallex,bluesnap,checkout,trustpay_3ds,payu,authorizedotnet, - - adyen_uk,shift4,worldline,multisafepay,paypal,mollie,aci,noon + - stripe,airwallex,bluesnap,checkout,trustpay_3ds,payu,authorizedotnet,aci,noon + - adyen_uk,shift4,worldline,multisafepay,paypal,mollie steps: diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index bcf21c8ef33..830a22b3a49 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -1335,7 +1335,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { //here we will get that field from router_data.recurring_mandate_payment_data let payment_method_types = if payment_method.is_some() { //if recurring payment get payment_method_type - get_payment_method_type_for_saved_payment_method_payment(item).map(Some)? + get_payment_method_type_for_saved_payment_method_payment(item)? } else { payment_method_types }; @@ -1450,28 +1450,34 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PaymentIntentRequest { fn get_payment_method_type_for_saved_payment_method_payment( item: &types::PaymentsAuthorizeRouterData, -) -> Result<StripePaymentMethodType, error_stack::Report<errors::ConnectorError>> { - let stripe_payment_method_type = match item.recurring_mandate_payment_data.clone() { - Some(recurring_payment_method_data) => { - match recurring_payment_method_data.payment_method_type { - Some(payment_method_type) => StripePaymentMethodType::try_from(payment_method_type), - None => Err(errors::ConnectorError::MissingRequiredField { - field_name: "payment_method_type", +) -> Result<Option<StripePaymentMethodType>, error_stack::Report<errors::ConnectorError>> { + if item.payment_method == api_enums::PaymentMethod::Card { + Ok(Some(StripePaymentMethodType::Card)) //stripe takes ["Card"] as default + } else { + let stripe_payment_method_type = match item.recurring_mandate_payment_data.clone() { + Some(recurring_payment_method_data) => { + match recurring_payment_method_data.payment_method_type { + Some(payment_method_type) => { + StripePaymentMethodType::try_from(payment_method_type) + } + None => Err(errors::ConnectorError::MissingRequiredField { + field_name: "payment_method_type", + } + .into()), } - .into()), } + None => Err(errors::ConnectorError::MissingRequiredField { + field_name: "recurring_mandate_payment_data", + } + .into()), + }?; + match stripe_payment_method_type { + //Stripe converts Ideal, Bancontact & Sofort Bank redirect methods to Sepa direct debit and attaches to the customer for future usage + StripePaymentMethodType::Ideal + | StripePaymentMethodType::Bancontact + | StripePaymentMethodType::Sofort => Ok(Some(StripePaymentMethodType::Sepa)), + _ => Ok(Some(stripe_payment_method_type)), } - None => Err(errors::ConnectorError::MissingRequiredField { - field_name: "recurring_mandate_payment_data", - } - .into()), - }?; - match stripe_payment_method_type { - //Stripe converts Ideal, Bancontact & Sofort Bank redirect methods to Sepa direct debit and attaches to the customer for future usage - StripePaymentMethodType::Ideal - | StripePaymentMethodType::Bancontact - | StripePaymentMethodType::Sofort => Ok(StripePaymentMethodType::Sepa), - _ => Ok(stripe_payment_method_type), } } diff --git a/crates/router/tests/connectors/authorizedotnet_ui.rs b/crates/router/tests/connectors/authorizedotnet_ui.rs index 099aef427f6..d20831128c8 100644 --- a/crates/router/tests/connectors/authorizedotnet_ui.rs +++ b/crates/router/tests/connectors/authorizedotnet_ui.rs @@ -46,6 +46,7 @@ async fn should_make_paypal_payment(web_driver: WebDriver) -> Result<(), WebDriv #[test] #[serial] +#[ignore] fn should_make_gpay_payment_test() { tester!(should_make_gpay_payment); } diff --git a/crates/router/tests/connectors/mollie_ui.rs b/crates/router/tests/connectors/mollie_ui.rs index 0066a7b6e0e..918b458404c 100644 --- a/crates/router/tests/connectors/mollie_ui.rs +++ b/crates/router/tests/connectors/mollie_ui.rs @@ -73,11 +73,7 @@ async fn should_make_mollie_ideal_payment(web_driver: WebDriver) -> Result<(), W Event::Trigger(Trigger::Click(By::Css( "button[class='button form__button']", ))), - Event::Assert(Assert::IsPresent("Google")), - Event::Assert(Assert::Contains( - Selector::QueryParamStr, - "status=succeeded", - )), + Event::Assert(Assert::IsPresent("succeeded")), ], ) .await?; diff --git a/crates/router/tests/connectors/selenium.rs b/crates/router/tests/connectors/selenium.rs index 9b547890cce..a349cb2c2cd 100644 --- a/crates/router/tests/connectors/selenium.rs +++ b/crates/router/tests/connectors/selenium.rs @@ -75,6 +75,24 @@ pub trait SeleniumTest { ) .expect("Failed to read connector authentication config file") } + async fn retry_click( + &self, + times: i32, + interval: u64, + driver: &WebDriver, + by: By, + ) -> Result<(), WebDriverError> { + let mut res = Ok(()); + for _i in 0..times { + res = self.click_element(driver, by.clone()).await; + if res.is_err() { + tokio::time::sleep(Duration::from_secs(interval)).await; + } else { + break; + } + } + return res; + } fn get_connector_name(&self) -> String; async fn complete_actions( &self, @@ -265,11 +283,7 @@ pub trait SeleniumTest { driver.execute(script, Vec::new()).await?; } Trigger::Click(by) => { - let res = self.click_element(driver, by.clone()).await; - if res.is_err() { - tokio::time::sleep(Duration::from_secs(5)).await; - self.click_element(driver, by).await?; - } + self.retry_click(3, 5, driver, by.clone()).await?; } Trigger::ClickNth(by, n) => { let ele = driver.query(by).all().await?.into_iter().nth(n).unwrap(); @@ -444,31 +458,31 @@ pub trait SeleniumTest { Assert::IsPresent("Big purchase? No problem."), vec![ Event::Trigger(Trigger::SendKeys( - By::Css("input.focusable-form-field.pro11TnYcue.pro284gg8sY"), + By::Css("input[data-testid='phone-number-field']"), "(833) 549-5574", // any test phone number accepted by affirm )), Event::Trigger(Trigger::Click(By::Css( - "button.sc-aXZVg.gCRVeN.pro35Wfly4z.pro300N0DVx.profBy8oj9g", + "button[data-testid='submit-button']", ))), Event::Trigger(Trigger::SendKeys( - By::Css("input.focusable-form-field.pro3g2JlS3A.pro284gg8sY"), + By::Css("input[data-testid='phone-pin-field']"), "1234", )), ], ), Event::Trigger(Trigger::Click(By::Css( - "button.sc-aXZVg.fiBhTR.sc-gEkIjz.lfdPCG.pro35Wfly4z.pro4JEtdJCo.profBy8oj9g", + "button[data-testid='skip-payment-button']", ))), + Event::Trigger(Trigger::Click(By::Css("div[data-testid='indicator']"))), Event::Trigger(Trigger::Click(By::Css( - "div.proXxAyyoTg.pro1jhMLxqa.pro3Q3lI-I9", + "button[data-testid='submit-button']", ))), + Event::Trigger(Trigger::Click(By::Css("div[data-testid='indicator']"))), Event::Trigger(Trigger::Click(By::Css( - "button.sc-aXZVg.gCRVeN.pro35Wfly4z.pro300N0DVx.pro3JiyGdDb.pro1Ss7c7oj", + "div[data-testid='disclosure-checkbox-indicator']", ))), - Event::Trigger(Trigger::Click(By::Css("div.pro1O60NO1I.pro2uav9pZk"))), - Event::Trigger(Trigger::Click(By::Css("div.pro1O60NO1I.pro1xh5zNal"))), Event::Trigger(Trigger::Click(By::Css( - "button.sc-aXZVg.gCRVeN.pro35Wfly4z.pro300N0DVx.profBy8oj9g", + "button[data-testid='submit-button']", ))), ]; affirm_actions.extend(actions); @@ -529,13 +543,7 @@ pub trait SeleniumTest { ), Event::EitherOr( Assert::IsPresent("See Offers and Apply for PayPal Credit"), - vec![ - Event::RunIf( - Assert::IsElePresent(By::Id("spinner")), - vec![Event::Trigger(Trigger::Sleep(5))], - ), - Event::Trigger(Trigger::Click(By::Css(".reviewButton"))), - ], + vec![Event::Trigger(Trigger::Click(By::Css(".reviewButton")))], vec![Event::Trigger(Trigger::Click(By::Id("payment-submit-btn")))], ), ]; diff --git a/crates/router/tests/connectors/worldline_ui.rs b/crates/router/tests/connectors/worldline_ui.rs index b95285b67f2..2e291843f0e 100644 --- a/crates/router/tests/connectors/worldline_ui.rs +++ b/crates/router/tests/connectors/worldline_ui.rs @@ -66,6 +66,7 @@ async fn should_make_worldline_giropay_redirect_payment( #[test] #[serial] +#[ignore] fn should_make_worldline_giropay_redirect_payment_test() { tester!(should_make_worldline_giropay_redirect_payment); }
fix
stripe mandate failure and other ui tests failures (#1742)
07fd9bedf02a1d70fc248fbbab480a5e24a7f077
2023-12-22 19:38:58
DEEPANSHU BANSAL
fix(connector): [BOA] Display 2XX Failure Errors (#3200)
false
diff --git a/crates/router/src/connector/bankofamerica/transformers.rs b/crates/router/src/connector/bankofamerica/transformers.rs index ab9e067a932..bae9d43da22 100644 --- a/crates/router/src/connector/bankofamerica/transformers.rs +++ b/crates/router/src/connector/bankofamerica/transformers.rs @@ -309,7 +309,7 @@ impl From<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> } } -#[derive(Debug, Deserialize, Serialize)] +#[derive(Clone, Debug, Deserialize, Serialize)] #[serde(rename_all = "camelCase")] pub struct ClientReferenceInformation { code: Option<String>, @@ -541,7 +541,7 @@ impl TryFrom<&BankOfAmericaRouterData<&types::PaymentsAuthorizeRouterData>> } } -#[derive(Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum BankofamericaPaymentStatus { Authorized, @@ -594,12 +594,13 @@ pub enum BankOfAmericaPaymentsResponse { ErrorInformation(BankOfAmericaErrorInformationResponse), } -#[derive(Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize)] #[serde(rename_all = "camelCase")] pub struct BankOfAmericaClientReferenceResponse { id: String, status: BankofamericaPaymentStatus, client_reference_information: ClientReferenceInformation, + error_information: Option<BankOfAmericaErrorInformation>, } #[derive(Debug, Deserialize)] @@ -609,12 +610,101 @@ pub struct BankOfAmericaErrorInformationResponse { error_information: BankOfAmericaErrorInformation, } -#[derive(Debug, Deserialize)] +#[derive(Clone, Debug, Deserialize)] pub struct BankOfAmericaErrorInformation { reason: Option<String>, message: Option<String>, } +fn get_error_response_if_failure( + (info_response, status, http_code): ( + &BankOfAmericaClientReferenceResponse, + enums::AttemptStatus, + u16, + ), +) -> Option<types::ErrorResponse> { + if is_payment_failure(status) { + let (message, reason) = match info_response.error_information.as_ref() { + Some(error_info) => ( + error_info + .message + .clone() + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + error_info.reason.clone(), + ), + None => (consts::NO_ERROR_MESSAGE.to_string(), None), + }; + + Some(types::ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message, + reason, + status_code: http_code, + attempt_status: Some(enums::AttemptStatus::Failure), + connector_transaction_id: Some(info_response.id.clone()), + }) + } else { + None + } +} + +fn is_payment_failure(status: enums::AttemptStatus) -> bool { + match status { + common_enums::AttemptStatus::AuthenticationFailed + | common_enums::AttemptStatus::AuthorizationFailed + | common_enums::AttemptStatus::CaptureFailed + | common_enums::AttemptStatus::VoidFailed + | common_enums::AttemptStatus::Failure => true, + common_enums::AttemptStatus::Started + | common_enums::AttemptStatus::RouterDeclined + | common_enums::AttemptStatus::AuthenticationPending + | common_enums::AttemptStatus::AuthenticationSuccessful + | common_enums::AttemptStatus::Authorized + | common_enums::AttemptStatus::Charged + | common_enums::AttemptStatus::Authorizing + | common_enums::AttemptStatus::CodInitiated + | common_enums::AttemptStatus::Voided + | common_enums::AttemptStatus::VoidInitiated + | common_enums::AttemptStatus::CaptureInitiated + | common_enums::AttemptStatus::AutoRefunded + | common_enums::AttemptStatus::PartialCharged + | common_enums::AttemptStatus::PartialChargedAndChargeable + | common_enums::AttemptStatus::Unresolved + | common_enums::AttemptStatus::Pending + | common_enums::AttemptStatus::PaymentMethodAwaited + | common_enums::AttemptStatus::ConfirmationAwaited + | common_enums::AttemptStatus::DeviceDataCollectionPending => false, + } +} + +fn get_payment_response( + (info_response, status, http_code): ( + &BankOfAmericaClientReferenceResponse, + enums::AttemptStatus, + u16, + ), +) -> Result<types::PaymentsResponseData, types::ErrorResponse> { + let error_response = get_error_response_if_failure((info_response, status, http_code)); + match error_response { + Some(error) => Err(error), + None => Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId(info_response.id.clone()), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: Some( + info_response + .client_reference_information + .code + .clone() + .unwrap_or(info_response.id.clone()), + ), + incremental_authorization_allowed: None, + }), + } +} + impl<F> TryFrom< types::ResponseRouterData< @@ -635,29 +725,18 @@ impl<F> >, ) -> Result<Self, Self::Error> { match item.response { - BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => Ok(Self { - status: enums::AttemptStatus::foreign_from(( - info_response.status, + BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => { + let status = enums::AttemptStatus::foreign_from(( + info_response.status.clone(), item.data.request.is_auto_capture()?, - )), - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - info_response.id.clone(), - ), - redirection_data: None, - mandate_reference: None, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: Some( - info_response - .client_reference_information - .code - .unwrap_or(info_response.id), - ), - incremental_authorization_allowed: None, - }), - ..item.data - }), + )); + let response = get_payment_response((&info_response, status, item.http_code)); + Ok(Self { + status, + response, + ..item.data + }) + } BankOfAmericaPaymentsResponse::ErrorInformation(error_response) => Ok(Self { response: Err(types::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), @@ -697,26 +776,16 @@ impl<F> >, ) -> Result<Self, Self::Error> { match item.response { - BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => Ok(Self { - status: enums::AttemptStatus::foreign_from((info_response.status, true)), - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - info_response.id.clone(), - ), - redirection_data: None, - mandate_reference: None, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: Some( - info_response - .client_reference_information - .code - .unwrap_or(info_response.id), - ), - incremental_authorization_allowed: None, - }), - ..item.data - }), + BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => { + let status = + enums::AttemptStatus::foreign_from((info_response.status.clone(), true)); + let response = get_payment_response((&info_response, status, item.http_code)); + Ok(Self { + status, + response, + ..item.data + }) + } BankOfAmericaPaymentsResponse::ErrorInformation(error_response) => Ok(Self { response: Err(types::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), @@ -755,26 +824,16 @@ impl<F> >, ) -> Result<Self, Self::Error> { match item.response { - BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => Ok(Self { - status: enums::AttemptStatus::foreign_from((info_response.status, false)), - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId( - info_response.id.clone(), - ), - redirection_data: None, - mandate_reference: None, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: Some( - info_response - .client_reference_information - .code - .unwrap_or(info_response.id), - ), - incremental_authorization_allowed: None, - }), - ..item.data - }), + BankOfAmericaPaymentsResponse::ClientReferenceInformation(info_response) => { + let status = + enums::AttemptStatus::foreign_from((info_response.status.clone(), false)); + let response = get_payment_response((&info_response, status, item.http_code)); + Ok(Self { + status, + response, + ..item.data + }) + } BankOfAmericaPaymentsResponse::ErrorInformation(error_response) => Ok(Self { response: Err(types::ErrorResponse { code: consts::NO_ERROR_CODE.to_string(), @@ -806,6 +865,7 @@ pub struct BankOfAmericaApplicationInfoResponse { id: String, application_information: ApplicationInformation, client_reference_information: Option<ClientReferenceInformation>, + error_information: Option<BankOfAmericaErrorInformation>, } #[derive(Debug, Deserialize)] @@ -834,25 +894,54 @@ impl<F> >, ) -> Result<Self, Self::Error> { match item.response { - BankOfAmericaTransactionResponse::ApplicationInformation(app_response) => Ok(Self { - status: enums::AttemptStatus::foreign_from(( + BankOfAmericaTransactionResponse::ApplicationInformation(app_response) => { + let status = enums::AttemptStatus::foreign_from(( app_response.application_information.status, item.data.request.is_auto_capture()?, - )), - response: Ok(types::PaymentsResponseData::TransactionResponse { - resource_id: types::ResponseId::ConnectorTransactionId(app_response.id.clone()), - redirection_data: None, - mandate_reference: None, - connector_metadata: None, - network_txn_id: None, - connector_response_reference_id: app_response - .client_reference_information - .map(|cref| cref.code) - .unwrap_or(Some(app_response.id)), - incremental_authorization_allowed: None, - }), - ..item.data - }), + )); + if is_payment_failure(status) { + let (message, reason) = match app_response.error_information { + Some(error_info) => ( + error_info + .message + .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()), + error_info.reason, + ), + None => (consts::NO_ERROR_MESSAGE.to_string(), None), + }; + Ok(Self { + response: Err(types::ErrorResponse { + code: consts::NO_ERROR_CODE.to_string(), + message, + reason, + status_code: item.http_code, + attempt_status: Some(enums::AttemptStatus::Failure), + connector_transaction_id: Some(app_response.id), + }), + status: enums::AttemptStatus::Failure, + ..item.data + }) + } else { + Ok(Self { + status, + response: Ok(types::PaymentsResponseData::TransactionResponse { + resource_id: types::ResponseId::ConnectorTransactionId( + app_response.id.clone(), + ), + redirection_data: None, + mandate_reference: None, + connector_metadata: None, + network_txn_id: None, + connector_response_reference_id: app_response + .client_reference_information + .map(|cref| cref.code) + .unwrap_or(Some(app_response.id)), + incremental_authorization_allowed: None, + }), + ..item.data + }) + } + } BankOfAmericaTransactionResponse::ErrorInformation(error_response) => Ok(Self { status: item.data.status, response: Ok(types::PaymentsResponseData::TransactionResponse {
fix
[BOA] Display 2XX Failure Errors (#3200)
ff3b9a2a12cd7f7e6c20f81777f6862b1f229bd4
2024-07-24 23:01:18
Prajjwal Kumar
refactor(core): patch file for removal of id from schema (#5398)
false
diff --git a/crates/common_utils/src/id_type.rs b/crates/common_utils/src/id_type.rs index 100f7957f5c..63f8497cae7 100644 --- a/crates/common_utils/src/id_type.rs +++ b/crates/common_utils/src/id_type.rs @@ -36,11 +36,11 @@ fn get_invalid_input_character(input_string: Cow<'static, str>) -> Option<char> .find(|char| !is_valid_id_character(char)) } -#[derive(Debug, PartialEq, Serialize, Clone, Eq, Hash)] +#[derive(Debug, PartialEq, Hash, Serialize, Clone, Eq)] /// A type for alphanumeric ids pub(crate) struct AlphaNumericId(String); -#[derive(Debug, Deserialize, Serialize, Error, Eq, PartialEq)] +#[derive(Debug, Deserialize, Hash, Serialize, Error, Eq, PartialEq)] #[error("value `{0}` contains invalid character `{1}`")] /// The error type for alphanumeric id pub(crate) struct AlphaNumericIdError(String, char); @@ -82,7 +82,7 @@ impl AlphaNumericId { } /// A common type of id that can be used for reference ids with length constraint -#[derive(Debug, Clone, Serialize, PartialEq, Eq, AsExpression, Hash)] +#[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq, AsExpression)] #[diesel(sql_type = sql_types::Text)] pub(crate) struct LengthId<const MAX_LENGTH: u8, const MIN_LENGTH: u8>(AlphaNumericId); diff --git a/crates/common_utils/src/id_type/customer.rs b/crates/common_utils/src/id_type/customer.rs index f56957025b2..00bd565d9e0 100644 --- a/crates/common_utils/src/id_type/customer.rs +++ b/crates/common_utils/src/id_type/customer.rs @@ -17,7 +17,7 @@ use crate::{ }; /// A type for customer_id that can be used for customer ids -#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, AsExpression)] +#[derive(Clone, Serialize, Deserialize, Hash, PartialEq, Eq, AsExpression)] #[diesel(sql_type = sql_types::Text)] pub struct CustomerId( LengthId<MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH, MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH>, diff --git a/crates/diesel_models/remove_id.patch b/crates/diesel_models/remove_id.patch new file mode 100644 index 00000000000..5b2e96ded3f --- /dev/null +++ b/crates/diesel_models/remove_id.patch @@ -0,0 +1,108 @@ +diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs +index 55f8e935b..469ad1d22 100644 +--- a/crates/diesel_models/src/schema.rs ++++ b/crates/diesel_models/src/schema.rs +@@ -5,7 +5,6 @@ diesel::table! { + use crate::enums::diesel_exports::*; + + address (address_id) { +- id -> Nullable<Int4>, + #[max_length = 64] + address_id -> Varchar, + #[max_length = 128] +@@ -129,7 +128,6 @@ diesel::table! { + use crate::enums::diesel_exports::*; + + blocklist (merchant_id, fingerprint_id) { +- id -> Int4, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] +@@ -284,7 +282,6 @@ diesel::table! { + use crate::enums::diesel_exports::*; + + customers (customer_id, merchant_id) { +- id -> Int4, + #[max_length = 64] + customer_id -> Varchar, + #[max_length = 64] +@@ -337,7 +334,6 @@ diesel::table! { + use crate::enums::diesel_exports::*; + + dispute (dispute_id) { +- id -> Int4, + #[max_length = 64] + dispute_id -> Varchar, + #[max_length = 255] +@@ -588,7 +584,6 @@ diesel::table! { + use crate::enums::diesel_exports::*; + + mandate (mandate_id) { +- id -> Int4, + #[max_length = 64] + mandate_id -> Varchar, + #[max_length = 64] +@@ -634,7 +629,6 @@ diesel::table! { + use crate::enums::diesel_exports::*; + + merchant_account (merchant_id) { +- id -> Int4, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 255] +@@ -678,7 +672,6 @@ diesel::table! { + use crate::enums::diesel_exports::*; + + merchant_connector_account (merchant_connector_id) { +- id -> Int4, + #[max_length = 64] + merchant_id -> Varchar, + #[max_length = 64] +@@ -741,7 +734,6 @@ diesel::table! { + use crate::enums::diesel_exports::*; + + payment_attempt (attempt_id, merchant_id) { +- id -> Nullable<Int4>, + #[max_length = 64] + payment_id -> Varchar, + #[max_length = 64] +@@ -832,7 +824,6 @@ diesel::table! { + use crate::enums::diesel_exports::*; + + payment_intent (payment_id, merchant_id) { +- id -> Nullable<Int4>, + #[max_length = 64] + payment_id -> Varchar, + #[max_length = 64] +@@ -935,7 +926,6 @@ diesel::table! { + use crate::enums::diesel_exports::*; + + payment_methods (payment_method_id) { +- id -> Int4, + #[max_length = 64] + customer_id -> Varchar, + #[max_length = 64] +@@ -1100,7 +1090,6 @@ diesel::table! { + use crate::enums::diesel_exports::*; + + refund (merchant_id, refund_id) { +- id -> Int4, + #[max_length = 64] + internal_reference_id -> Varchar, + #[max_length = 64] +@@ -1169,7 +1158,6 @@ diesel::table! { + use crate::enums::diesel_exports::*; + + roles (role_id) { +- id -> Int4, + #[max_length = 64] + role_name -> Varchar, + #[max_length = 64] +@@ -1276,7 +1263,6 @@ diesel::table! { + use crate::enums::diesel_exports::*; + + users (user_id) { +- id -> Int4, + #[max_length = 64] + user_id -> Varchar, + #[max_length = 255] diff --git a/crates/diesel_models/src/address.rs b/crates/diesel_models/src/address.rs index 8de7d8aa190..aaaa7fb747a 100644 --- a/crates/diesel_models/src/address.rs +++ b/crates/diesel_models/src/address.rs @@ -39,7 +39,6 @@ pub struct AddressNew { #[derive(Clone, Debug, Queryable, Identifiable, Selectable, Serialize, Deserialize)] #[diesel(table_name = address, primary_key(address_id), check_for_backend(diesel::pg::Pg))] pub struct Address { - pub id: Option<i32>, pub address_id: String, pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, diff --git a/crates/diesel_models/src/blocklist.rs b/crates/diesel_models/src/blocklist.rs index 0ef7daf0099..c4a5b48bad2 100644 --- a/crates/diesel_models/src/blocklist.rs +++ b/crates/diesel_models/src/blocklist.rs @@ -16,10 +16,8 @@ pub struct BlocklistNew { #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Deserialize, Serialize, )] -#[diesel(table_name = blocklist, check_for_backend(diesel::pg::Pg))] +#[diesel(table_name = blocklist, primary_key(merchant_id, fingerprint_id), check_for_backend(diesel::pg::Pg))] pub struct Blocklist { - #[serde(skip)] - pub id: i32, pub merchant_id: common_utils::id_type::MerchantId, pub fingerprint_id: String, pub data_kind: common_enums::BlocklistDataKind, diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs index ea552e0d399..7219bb90524 100644 --- a/crates/diesel_models/src/customers.rs +++ b/crates/diesel_models/src/customers.rs @@ -33,7 +33,6 @@ impl CustomerNew { impl From<CustomerNew> for Customer { fn from(customer_new: CustomerNew) -> Self { Self { - id: 0i32, customer_id: customer_new.customer_id, merchant_id: customer_new.merchant_id, name: customer_new.name, @@ -55,9 +54,8 @@ impl From<CustomerNew> for Customer { #[derive( Clone, Debug, Identifiable, Queryable, Selectable, serde::Deserialize, serde::Serialize, )] -#[diesel(table_name = customers, check_for_backend(diesel::pg::Pg))] +#[diesel(table_name = customers, primary_key(customer_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct Customer { - pub id: i32, pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub name: Option<Encryption>, diff --git a/crates/diesel_models/src/dispute.rs b/crates/diesel_models/src/dispute.rs index c2ef94e671f..704b1781e2a 100644 --- a/crates/diesel_models/src/dispute.rs +++ b/crates/diesel_models/src/dispute.rs @@ -33,10 +33,8 @@ pub struct DisputeNew { } #[derive(Clone, Debug, PartialEq, Serialize, Identifiable, Queryable, Selectable)] -#[diesel(table_name = dispute, check_for_backend(diesel::pg::Pg))] +#[diesel(table_name = dispute, primary_key(dispute_id), check_for_backend(diesel::pg::Pg))] pub struct Dispute { - #[serde(skip_serializing)] - pub id: i32, pub dispute_id: String, pub amount: String, pub currency: String, diff --git a/crates/diesel_models/src/mandate.rs b/crates/diesel_models/src/mandate.rs index ec4b572e8ee..bfac1849a58 100644 --- a/crates/diesel_models/src/mandate.rs +++ b/crates/diesel_models/src/mandate.rs @@ -9,9 +9,8 @@ use crate::{enums as storage_enums, schema::mandate}; #[derive( Clone, Debug, Identifiable, Queryable, Selectable, serde::Serialize, serde::Deserialize, )] -#[diesel(table_name = mandate, check_for_backend(diesel::pg::Pg))] +#[diesel(table_name = mandate, primary_key(mandate_id), check_for_backend(diesel::pg::Pg))] pub struct Mandate { - pub id: i32, pub mandate_id: String, pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, @@ -209,7 +208,6 @@ impl MandateUpdateInternal { impl From<&MandateNew> for Mandate { fn from(mandate_new: &MandateNew) -> Self { Self { - id: 0i32, mandate_id: mandate_new.mandate_id.clone(), customer_id: mandate_new.customer_id.clone(), merchant_id: mandate_new.merchant_id.clone(), diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs index 4e99900af2f..23bc642c2db 100644 --- a/crates/diesel_models/src/merchant_account.rs +++ b/crates/diesel_models/src/merchant_account.rs @@ -26,7 +26,6 @@ use crate::schema_v2::merchant_account; )] #[diesel(table_name = merchant_account, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))] pub struct MerchantAccount { - pub id: i32, pub merchant_id: id_type::MerchantId, pub return_url: Option<String>, pub enable_payment_response_hash: bool, diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs index 4b6ab77d8ae..eb561f2f9c6 100644 --- a/crates/diesel_models/src/merchant_connector_account.rs +++ b/crates/diesel_models/src/merchant_connector_account.rs @@ -16,9 +16,8 @@ use crate::{enums as storage_enums, schema::merchant_connector_account}; Selectable, router_derive::DebugAsDisplay, )] -#[diesel(table_name = merchant_connector_account, check_for_backend(diesel::pg::Pg))] +#[diesel(table_name = merchant_connector_account, primary_key(merchant_connector_id), check_for_backend(diesel::pg::Pg))] pub struct MerchantConnectorAccount { - pub id: i32, pub merchant_id: id_type::MerchantId, pub connector_name: String, pub connector_account_details: Encryption, diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs index 791d4fb26e5..525c681a1e5 100644 --- a/crates/diesel_models/src/payment_attempt.rs +++ b/crates/diesel_models/src/payment_attempt.rs @@ -86,7 +86,6 @@ pub struct PaymentAttempt { )] #[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentAttempt { - pub id: Option<i32>, pub payment_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub attempt_id: String, @@ -1703,7 +1702,6 @@ mod tests { #[test] fn test_backwards_compatibility() { let serialized_payment_attempt = r#"{ - "id": 1, "payment_id": "PMT123456789", "merchant_id": "M123456789", "attempt_id": "ATMPT123456789", diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs index 012376ae3d2..2d390b0b34c 100644 --- a/crates/diesel_models/src/payment_intent.rs +++ b/crates/diesel_models/src/payment_intent.rs @@ -74,7 +74,6 @@ pub struct PaymentIntent { #[derive(Clone, Debug, PartialEq, Identifiable, Queryable, Serialize, Deserialize, Selectable)] #[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentIntent { - pub id: Option<i32>, pub payment_id: String, pub merchant_id: common_utils::id_type::MerchantId, pub status: storage_enums::IntentStatus, @@ -1027,7 +1026,6 @@ mod tests { #[test] fn test_backwards_compatibility() { let serialized_payment_intent = r#"{ - "id": 123, "payment_id": "payment_12345", "merchant_id": "merchant_67890", "status": "succeeded", diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs index 0121ec5112c..b54824ad935 100644 --- a/crates/diesel_models/src/payment_method.rs +++ b/crates/diesel_models/src/payment_method.rs @@ -10,9 +10,8 @@ use crate::{enums as storage_enums, schema::payment_methods}; #[derive( Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Serialize, Deserialize, )] -#[diesel(table_name = payment_methods, check_for_backend(diesel::pg::Pg))] +#[diesel(table_name = payment_methods, primary_key(payment_method_id), check_for_backend(diesel::pg::Pg))] pub struct PaymentMethod { - pub id: i32, pub customer_id: common_utils::id_type::CustomerId, pub merchant_id: common_utils::id_type::MerchantId, pub payment_method_id: String, @@ -329,7 +328,6 @@ impl From<PaymentMethodUpdate> for PaymentMethodUpdateInternal { impl From<&PaymentMethodNew> for PaymentMethod { fn from(payment_method_new: &PaymentMethodNew) -> Self { Self { - id: 0i32, customer_id: payment_method_new.customer_id.clone(), merchant_id: payment_method_new.merchant_id.clone(), payment_method_id: payment_method_new.payment_method_id.clone(), diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs index b95ade2df1a..e4a74a6d66e 100644 --- a/crates/diesel_models/src/refund.rs +++ b/crates/diesel_models/src/refund.rs @@ -19,9 +19,8 @@ use crate::{enums as storage_enums, schema::refund}; serde::Serialize, serde::Deserialize, )] -#[diesel(table_name = refund, check_for_backend(diesel::pg::Pg))] +#[diesel(table_name = refund, primary_key(refund_id), check_for_backend(diesel::pg::Pg))] pub struct Refund { - pub id: i32, pub internal_reference_id: String, pub refund_id: String, //merchant_reference id pub payment_id: String, @@ -341,7 +340,6 @@ mod tests { #[test] fn test_backwards_compatibility() { let serialized_refund = r#"{ - "id": 1, "internal_reference_id": "internal_ref_123", "refund_id": "refund_456", "payment_id": "payment_789", diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs index cf38f49aadf..713590adeda 100644 --- a/crates/diesel_models/src/role.rs +++ b/crates/diesel_models/src/role.rs @@ -5,9 +5,8 @@ use time::PrimitiveDateTime; use crate::{enums, schema::roles}; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] -#[diesel(table_name = roles, check_for_backend(diesel::pg::Pg))] +#[diesel(table_name = roles, primary_key(role_id), check_for_backend(diesel::pg::Pg))] pub struct Role { - pub id: i32, pub role_name: String, pub role_id: String, pub merchant_id: id_type::MerchantId, diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs index c6f47a32557..544a99bccb5 100644 --- a/crates/diesel_models/src/schema.rs +++ b/crates/diesel_models/src/schema.rs @@ -5,7 +5,6 @@ diesel::table! { use crate::enums::diesel_exports::*; address (address_id) { - id -> Nullable<Int4>, #[max_length = 64] address_id -> Varchar, #[max_length = 128] @@ -129,7 +128,6 @@ diesel::table! { use crate::enums::diesel_exports::*; blocklist (merchant_id, fingerprint_id) { - id -> Int4, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] @@ -284,7 +282,6 @@ diesel::table! { use crate::enums::diesel_exports::*; customers (customer_id, merchant_id) { - id -> Int4, #[max_length = 64] customer_id -> Varchar, #[max_length = 64] @@ -337,7 +334,6 @@ diesel::table! { use crate::enums::diesel_exports::*; dispute (dispute_id) { - id -> Int4, #[max_length = 64] dispute_id -> Varchar, #[max_length = 255] @@ -588,7 +584,6 @@ diesel::table! { use crate::enums::diesel_exports::*; mandate (mandate_id) { - id -> Int4, #[max_length = 64] mandate_id -> Varchar, #[max_length = 64] @@ -634,7 +629,6 @@ diesel::table! { use crate::enums::diesel_exports::*; merchant_account (merchant_id) { - id -> Int4, #[max_length = 64] merchant_id -> Varchar, #[max_length = 255] @@ -678,7 +672,6 @@ diesel::table! { use crate::enums::diesel_exports::*; merchant_connector_account (merchant_connector_id) { - id -> Int4, #[max_length = 64] merchant_id -> Varchar, #[max_length = 64] @@ -745,7 +738,6 @@ diesel::table! { use crate::enums::diesel_exports::*; payment_attempt (attempt_id, merchant_id) { - id -> Nullable<Int4>, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] @@ -836,7 +828,6 @@ diesel::table! { use crate::enums::diesel_exports::*; payment_intent (payment_id, merchant_id) { - id -> Nullable<Int4>, #[max_length = 64] payment_id -> Varchar, #[max_length = 64] @@ -939,7 +930,6 @@ diesel::table! { use crate::enums::diesel_exports::*; payment_methods (payment_method_id) { - id -> Int4, #[max_length = 64] customer_id -> Varchar, #[max_length = 64] @@ -1104,7 +1094,6 @@ diesel::table! { use crate::enums::diesel_exports::*; refund (merchant_id, refund_id) { - id -> Int4, #[max_length = 64] internal_reference_id -> Varchar, #[max_length = 64] @@ -1173,7 +1162,6 @@ diesel::table! { use crate::enums::diesel_exports::*; roles (role_id) { - id -> Int4, #[max_length = 64] role_name -> Varchar, #[max_length = 64] @@ -1280,7 +1268,6 @@ diesel::table! { use crate::enums::diesel_exports::*; users (user_id) { - id -> Int4, #[max_length = 64] user_id -> Varchar, #[max_length = 255] diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs index 8469e4c2cab..582041ec42e 100644 --- a/crates/diesel_models/src/user.rs +++ b/crates/diesel_models/src/user.rs @@ -9,9 +9,8 @@ pub mod dashboard_metadata; pub mod sample_data; #[derive(Clone, Debug, Identifiable, Queryable, Selectable)] -#[diesel(table_name = users, check_for_backend(diesel::pg::Pg))] +#[diesel(table_name = users, primary_key(user_id), check_for_backend(diesel::pg::Pg))] pub struct User { - pub id: i32, pub user_id: String, pub email: pii::Email, pub name: Secret<String>, diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs index 558a8b4469c..504c1c20465 100644 --- a/crates/hyperswitch_domain_models/src/customer.rs +++ b/crates/hyperswitch_domain_models/src/customer.rs @@ -22,7 +22,6 @@ pub enum SoftDeleteStatus { #[derive(Clone, Debug)] pub struct Customer { - pub id: Option<i32>, pub customer_id: id_type::CustomerId, pub merchant_id: id_type::MerchantId, pub name: crypto::OptionalEncryptableName, @@ -49,9 +48,6 @@ impl super::behaviour::Conversion for Customer { type NewDstType = diesel_models::customers::CustomerNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::customers::Customer { - id: self.id.ok_or(ValidationError::MissingRequiredField { - field_name: "id".to_string(), - })?, customer_id: self.customer_id, merchant_id: self.merchant_id, name: self.name.map(|value| value.into()), @@ -98,7 +94,6 @@ impl super::behaviour::Conversion for Customer { })?; Ok(Self { - id: Some(item.id), customer_id: item.customer_id, merchant_id: item.merchant_id, name: encryptable_customer.name, diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs index eb5905c507e..6d311ea2d4d 100644 --- a/crates/hyperswitch_domain_models/src/merchant_account.rs +++ b/crates/hyperswitch_domain_models/src/merchant_account.rs @@ -22,7 +22,6 @@ use crate::type_encryption::{decrypt_optional, AsyncLift}; ))] #[derive(Clone, Debug, serde::Serialize)] pub struct MerchantAccount { - pub id: Option<i32>, merchant_id: common_utils::id_type::MerchantId, pub return_url: Option<String>, pub enable_payment_response_hash: bool, @@ -95,7 +94,6 @@ pub struct MerchantAccountSetter { impl From<MerchantAccountSetter> for MerchantAccount { fn from(item: MerchantAccountSetter) -> Self { Self { - id: None, merchant_id: item.merchant_id, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, @@ -416,9 +414,6 @@ impl super::behaviour::Conversion for MerchantAccount { type NewDstType = diesel_models::merchant_account::MerchantAccountNew; async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::merchant_account::MerchantAccount { - id: self.id.ok_or(ValidationError::MissingRequiredField { - field_name: "id".to_string(), - })?, merchant_id: self.merchant_id, return_url: self.return_url, enable_payment_response_hash: self.enable_payment_response_hash, @@ -465,7 +460,6 @@ impl super::behaviour::Conversion for MerchantAccount { })?; async { Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self { - id: Some(item.id), merchant_id: item.merchant_id, return_url: item.return_url, enable_payment_response_hash: item.enable_payment_response_hash, diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs index 7e4c5524727..9203a33239e 100644 --- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs +++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs @@ -682,7 +682,6 @@ impl behaviour::Conversion for PaymentIntent { async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(DieselPaymentIntent { - id: None, payment_id: self.payment_id, merchant_id: self.merchant_id, status: self.status, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 4dd41bd4e88..e6c132b4993 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -1441,7 +1441,6 @@ pub async fn create_payment_connector( business_sub_label: req.business_sub_label.clone(), created_at: date_time::now(), modified_at: date_time::now(), - id: None, connector_webhook_details: match req.connector_webhook_details { Some(connector_webhook_details) => { connector_webhook_details.encode_to_value( diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index 16f79e375b8..4c96f4fbe8f 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -170,7 +170,6 @@ impl CustomerCreateBridge for customers::CustomerRequest { description: self.description.clone(), phone_country_code: self.phone_country_code.clone(), metadata: self.metadata.clone(), - id: None, connector_customer: None, address_id: address_from_db.clone().map(|addr| addr.address_id), created_at: common_utils::date_time::now(), diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs index 6dd8f194724..f6bdd78fc25 100644 --- a/crates/router/src/core/payments/helpers.rs +++ b/crates/router/src/core/payments/helpers.rs @@ -362,7 +362,6 @@ pub async fn get_domain_address( let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; Ok(domain::Address { - id: None, phone_number: encryptable_address.phone_number, country_code: address.phone.as_ref().and_then(|a| a.country_code.clone()), merchant_id: merchant_id.to_owned(), @@ -1680,7 +1679,6 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>( phone_country_code: request_customer_details.phone_country_code.clone(), description: None, created_at: common_utils::date_time::now(), - id: None, metadata: None, modified_at: common_utils::date_time::now(), connector_customer: None, diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs index 41229552ad5..66ade4ee536 100644 --- a/crates/router/src/core/payouts/helpers.rs +++ b/crates/router/src/core/payouts/helpers.rs @@ -654,7 +654,6 @@ pub async fn get_or_create_customer_details( phone_country_code: customer_details.phone_country_code.to_owned(), metadata: None, connector_customer: None, - id: None, created_at: common_utils::date_time::now(), modified_at: common_utils::date_time::now(), address_id: None, diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs index f15adbeea69..10ad8ebe80a 100644 --- a/crates/router/src/db/address.rs +++ b/crates/router/src/db/address.rs @@ -571,7 +571,6 @@ mod storage { }; let field = format!("add_{}", &address_new.address_id); let created_address = diesel_models::Address { - id: Some(0i32), address_id: address_new.address_id.clone(), city: address_new.city.clone(), country: address_new.country, diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs index 4de14057c18..073b725448d 100644 --- a/crates/router/src/db/dispute.rs +++ b/crates/router/src/db/dispute.rs @@ -1,4 +1,4 @@ -use error_stack::{report, ResultExt}; +use error_stack::report; use router_env::{instrument, tracing}; use super::{MockDb, Store}; @@ -148,8 +148,6 @@ impl DisputeInterface for MockDb { let now = common_utils::date_time::now(); let new_dispute = storage::Dispute { - id: i32::try_from(locked_disputes.len()) - .change_context(errors::StorageError::MockDbError)?, dispute_id: dispute.dispute_id, amount: dispute.amount, currency: dispute.currency, @@ -674,7 +672,6 @@ mod tests { .await .unwrap(); - assert_eq!(created_dispute.id, updated_dispute.id); assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); assert_eq!(created_dispute.amount, updated_dispute.amount); assert_eq!(created_dispute.currency, updated_dispute.currency); @@ -751,7 +748,6 @@ mod tests { .await .unwrap(); - assert_eq!(created_dispute.id, updated_dispute.id); assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); assert_eq!(created_dispute.amount, updated_dispute.amount); assert_eq!(created_dispute.currency, updated_dispute.currency); @@ -827,7 +823,6 @@ mod tests { .await .unwrap(); - assert_eq!(created_dispute.id, updated_dispute.id); assert_eq!(created_dispute.dispute_id, updated_dispute.dispute_id); assert_eq!(created_dispute.amount, updated_dispute.amount); assert_eq!(created_dispute.currency, updated_dispute.currency); diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs index bdc51c8ad8b..c85bb4cb176 100644 --- a/crates/router/src/db/mandate.rs +++ b/crates/router/src/db/mandate.rs @@ -1,5 +1,4 @@ use common_utils::id_type; -use error_stack::ResultExt; use super::MockDb; use crate::{ @@ -614,7 +613,6 @@ impl MandateInterface for MockDb { ) -> CustomResult<storage_types::Mandate, errors::StorageError> { let mut mandates = self.mandates.lock().await; let mandate = storage_types::Mandate { - id: i32::try_from(mandates.len()).change_context(errors::StorageError::MockDbError)?, mandate_id: mandate_new.mandate_id.clone(), customer_id: mandate_new.customer_id, merchant_id: mandate_new.merchant_id, diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs index f48007d15b3..22f67b3538f 100644 --- a/crates/router/src/db/merchant_connector_account.rs +++ b/crates/router/src/db/merchant_connector_account.rs @@ -858,7 +858,6 @@ impl MerchantConnectorAccountInterface for MockDb { ) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> { let mut accounts = self.merchant_connector_accounts.lock().await; let account = storage::MerchantConnectorAccount { - id: i32::try_from(accounts.len()).change_context(errors::StorageError::MockDbError)?, merchant_id: t.merchant_id, connector_name: t.connector_name, connector_account_details: t.connector_account_details.into(), @@ -945,7 +944,7 @@ impl MerchantConnectorAccountInterface for MockDb { .lock() .await .iter_mut() - .find(|account| Some(account.id) == this.id) + .find(|account| account.merchant_connector_id == this.merchant_connector_id) .map(|a| { let updated = merchant_connector_account.create_merchant_connector_account(a.clone()); @@ -1097,7 +1096,6 @@ mod merchant_connector_account_cache_tests { .unwrap(); let mca = domain::MerchantConnectorAccount { - id: Some(1), merchant_id: merchant_id.to_owned(), connector_name: "stripe".to_string(), connector_account_details: domain::types::encrypt( diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs index b0fed03e9b5..e182d62c3f3 100644 --- a/crates/router/src/db/payment_method.rs +++ b/crates/router/src/db/payment_method.rs @@ -664,8 +664,6 @@ impl PaymentMethodInterface for MockDb { let mut payment_methods = self.payment_methods.lock().await; let payment_method = storage_types::PaymentMethod { - id: i32::try_from(payment_methods.len()) - .change_context(errors::StorageError::MockDbError)?, customer_id: payment_method_new.customer_id, merchant_id: payment_method_new.merchant_id, payment_method_id: payment_method_new.payment_method_id, @@ -784,7 +782,7 @@ impl PaymentMethodInterface for MockDb { .lock() .await .iter_mut() - .find(|pm| pm.id == payment_method.id) + .find(|pm| pm.payment_method_id == payment_method.payment_method_id) .map(|pm| { let payment_method_updated = PaymentMethodUpdateInternal::from(payment_method_update) diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs index 67be1d30e04..1fa7e28cb81 100644 --- a/crates/router/src/db/refund.rs +++ b/crates/router/src/db/refund.rs @@ -4,7 +4,6 @@ use std::collections::HashSet; #[cfg(feature = "olap")] use common_utils::types::MinorUnit; use diesel_models::{errors::DatabaseError, refund::RefundUpdateInternal}; -use error_stack::ResultExt; use super::MockDb; use crate::{ @@ -372,7 +371,6 @@ mod storage { // TODO: need to add an application generated payment attempt id to distinguish between multiple attempts for the same payment id // Check for database presence as well Maybe use a read replica here ? let created_refund = storage_types::Refund { - id: 0i32, refund_id: new.refund_id.clone(), merchant_id: new.merchant_id.clone(), attempt_id: new.attempt_id.clone(), @@ -834,7 +832,6 @@ impl RefundInterface for MockDb { let current_time = common_utils::date_time::now(); let refund = storage_types::Refund { - id: i32::try_from(refunds.len()).change_context(errors::StorageError::MockDbError)?, internal_reference_id: new.internal_reference_id, refund_id: new.refund_id, payment_id: new.payment_id, diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs index 15dfc14d375..286a85190b8 100644 --- a/crates/router/src/db/role.rs +++ b/crates/router/src/db/role.rs @@ -1,7 +1,7 @@ use common_enums::enums; use common_utils::id_type; use diesel_models::role as storage; -use error_stack::{report, ResultExt}; +use error_stack::report; use router_env::{instrument, tracing}; use super::MockDb; @@ -138,7 +138,6 @@ impl RoleInterface for MockDb { })? } let role = storage::Role { - id: i32::try_from(roles.len()).change_context(errors::StorageError::MockDbError)?, role_name: role.role_name, role_id: role.role_id, merchant_id: role.merchant_id, diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs index 742944bd1e0..b8c5001d910 100644 --- a/crates/router/src/db/user.rs +++ b/crates/router/src/db/user.rs @@ -1,5 +1,5 @@ use diesel_models::user as storage; -use error_stack::{report, ResultExt}; +use error_stack::report; use masking::Secret; use router_env::{instrument, tracing}; @@ -152,7 +152,6 @@ impl UserInterface for MockDb { } let time_now = common_utils::date_time::now(); let user = storage::User { - id: i32::try_from(users.len()).change_context(errors::StorageError::MockDbError)?, user_id: user_data.user_id, email: user_data.email, name: user_data.name, diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs index c7604622f3b..55d83679db9 100644 --- a/crates/router/src/types/domain/address.rs +++ b/crates/router/src/types/domain/address.rs @@ -17,8 +17,6 @@ use super::{behaviour, types}; #[derive(Clone, Debug, serde::Serialize)] pub struct Address { - #[serde(skip_serializing)] - pub id: Option<i32>, pub address_id: String, pub city: Option<String>, pub country: Option<enums::CountryAlpha2>, @@ -161,7 +159,6 @@ impl behaviour::Conversion for Address { async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok(diesel_models::address::Address { - id: self.id, address_id: self.address_id, city: self.city, country: self.country, @@ -206,7 +203,6 @@ impl behaviour::Conversion for Address { message: "Failed while decrypting".to_string(), })?; Ok(Self { - id: other.id, address_id: other.address_id, city: other.city, country: other.country, diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs index 6b0436b6f2f..170113c7a2a 100644 --- a/crates/router/src/types/domain/merchant_connector_account.rs +++ b/crates/router/src/types/domain/merchant_connector_account.rs @@ -16,7 +16,6 @@ use super::{ }; #[derive(Clone, Debug)] pub struct MerchantConnectorAccount { - pub id: Option<i32>, pub merchant_id: common_utils::id_type::MerchantId, pub connector_name: String, pub connector_account_details: Encryptable<Secret<serde_json::Value>>, @@ -74,9 +73,6 @@ impl behaviour::Conversion for MerchantConnectorAccount { async fn convert(self) -> CustomResult<Self::DstType, ValidationError> { Ok( diesel_models::merchant_connector_account::MerchantConnectorAccount { - id: self.id.ok_or(ValidationError::MissingRequiredField { - field_name: "id".to_string(), - })?, merchant_id: self.merchant_id, connector_name: self.connector_name, connector_account_details: self.connector_account_details.into(), @@ -113,7 +109,6 @@ impl behaviour::Conversion for MerchantConnectorAccount { ) -> CustomResult<Self, ValidationError> { let identifier = Identifier::Merchant(other.merchant_id.clone()); Ok(Self { - id: Some(other.id), merchant_id: other.merchant_id, connector_name: other.connector_name, connector_account_details: decrypt( diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs index ea3a36b518a..c86f9240c4b 100644 --- a/crates/router/src/utils.rs +++ b/crates/router/src/utils.rs @@ -755,7 +755,6 @@ impl CustomerAddress for api_models::customers::CustomerRequest { let encryptable_address = AddressDetailsWithPhone::from_encryptable(encrypted_data) .change_context(common_utils::errors::CryptoError::EncodingFailed)?; let address = domain::Address { - id: None, city: address_details.city, country: address_details.country, line1: encryptable_address.line1, diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs index f5d28f7698d..03a9ac6e454 100644 --- a/crates/storage_impl/src/payments/payment_attempt.rs +++ b/crates/storage_impl/src/payments/payment_attempt.rs @@ -1292,7 +1292,6 @@ impl DataModelExt for PaymentAttempt { fn to_storage_model(self) -> Self::StorageModel { DieselPaymentAttempt { - id: None, payment_id: self.payment_id, merchant_id: self.merchant_id, attempt_id: self.attempt_id, diff --git a/diesel.toml b/diesel.toml index 0496c748c3e..9079080b31f 100644 --- a/diesel.toml +++ b/diesel.toml @@ -5,3 +5,4 @@ file = "crates/diesel_models/src/schema.rs" import_types = ["diesel::sql_types::*", "crate::enums::diesel_exports::*"] generate_missing_sql_type_definitions = false +patch_file="crates/diesel_models/remove_id.patch"
refactor
patch file for removal of id from schema (#5398)
d21fcc7bfc3bdf672b9cfbc5a234a3f3d03771c8
2023-06-07 15:15:52
Sampras Lopes
fix(config): fix docker compose local setup (#1372)
false
diff --git a/.github/ISSUE_TEMPLATE/bug_report.yml b/.github/ISSUE_TEMPLATE/bug_report.yml index fccc641180a..f33acc41194 100644 --- a/.github/ISSUE_TEMPLATE/bug_report.yml +++ b/.github/ISSUE_TEMPLATE/bug_report.yml @@ -70,7 +70,7 @@ body: If yes, please provide the value of the `x-request-id` response header for helping us debug your issue. If not (or if building/running locally), please provide the following details: - 1. Operating System or Linux distribution: + 1. Operating System or Linux distribution: 2. Rust version (output of `rustc --version`): `` 3. App version (output of `cargo r -- --version`): `` validations: diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 50b5585813f..c867f994f5e 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -19,7 +19,7 @@ - [ ] This PR modifies the database schema - [ ] This PR modifies application configuration/environment variables -<!-- +<!-- Provide links to the files with corresponding changes. Following are the paths where you can find config files: diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 26696fa4707..3a85f302218 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -384,4 +384,4 @@ jobs: - name: Spell check uses: crate-ci/typos@master - + diff --git a/CHANGELOG.md b/CHANGELOG.md index 61233275af1..c38ac5371aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -326,7 +326,7 @@ All notable changes to HyperSwitch will be documented here. * **bank_redirects:** modify api contract for sofort (#880) (fc2e4514) * add template code for connector forte (#854) (7a581a6) * add template code for connector nexinets (#852) (dee5f61) - + ### Bug Fixes * **connector:** [coinbase] make metadata as option parameter (#887) (f5728955) @@ -335,7 +335,7 @@ All notable changes to HyperSwitch will be documented here. ### Enhancement -* **payments:** make TokenizationAction clonable (#895) +* **payments:** make TokenizationAction clonable (#895) ### Integration diff --git a/Cargo.nix b/Cargo.nix index 5be543d09dc..11056f2f096 100644 --- a/Cargo.nix +++ b/Cargo.nix @@ -85,7 +85,6 @@ in tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".actix-codec."0.5.0" = overridableMkRustCrate (profileName: rec { name = "actix-codec"; version = "0.5.0"; @@ -103,7 +102,6 @@ in tokio_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".actix-cors."0.6.4" = overridableMkRustCrate (profileName: rec { name = "actix-cors"; version = "0.6.4"; @@ -119,7 +117,6 @@ in smallvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".actix-http."3.3.0" = overridableMkRustCrate (profileName: rec { name = "actix-http"; version = "3.3.0"; @@ -176,7 +173,6 @@ in zstd = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zstd."0.12.2+zstd.1.5.2" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".actix-macros."0.2.3" = overridableMkRustCrate (profileName: rec { name = "actix-macros"; version = "0.2.3"; @@ -187,7 +183,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".actix-router."0.5.1" = overridableMkRustCrate (profileName: rec { name = "actix-router"; version = "0.5.1"; @@ -205,7 +200,6 @@ in tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".actix-rt."2.8.0" = overridableMkRustCrate (profileName: rec { name = "actix-rt"; version = "2.8.0"; @@ -222,7 +216,6 @@ in tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".actix-server."2.1.1" = overridableMkRustCrate (profileName: rec { name = "actix-server"; version = "2.1.1"; @@ -244,7 +237,6 @@ in tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".actix-service."2.0.2" = overridableMkRustCrate (profileName: rec { name = "actix-service"; version = "2.0.2"; @@ -256,7 +248,6 @@ in pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".actix-tls."3.0.3" = overridableMkRustCrate (profileName: rec { name = "actix-tls"; version = "3.0.3"; @@ -286,7 +277,6 @@ in webpki_roots = rustPackages."registry+https://github.com/rust-lang/crates.io-index".webpki-roots."0.22.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".actix-utils."3.0.1" = overridableMkRustCrate (profileName: rec { name = "actix-utils"; version = "3.0.1"; @@ -297,7 +287,6 @@ in pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".actix-web."4.3.0" = overridableMkRustCrate (profileName: rec { name = "actix-web"; version = "4.3.0"; @@ -351,7 +340,6 @@ in url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".actix-web-codegen."4.1.0" = overridableMkRustCrate (profileName: rec { name = "actix-web-codegen"; version = "4.1.0"; @@ -364,7 +352,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".actix_derive."0.6.0" = overridableMkRustCrate (profileName: rec { name = "actix_derive"; version = "0.6.0"; @@ -376,14 +363,12 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".adler."1.0.2" = overridableMkRustCrate (profileName: rec { name = "adler"; version = "1.0.2"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "f26201604c87b1e01bd3d98f8d5d9a8fcbb815e8cedb41ffccbeb4bf593a35fe"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".ahash."0.7.6" = overridableMkRustCrate (profileName: rec { name = "ahash"; version = "0.7.6"; @@ -401,7 +386,6 @@ in version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aho-corasick."0.7.20" = overridableMkRustCrate (profileName: rec { name = "aho-corasick"; version = "0.7.20"; @@ -415,14 +399,12 @@ in memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".alloc-no-stdlib."2.0.4" = overridableMkRustCrate (profileName: rec { name = "alloc-no-stdlib"; version = "2.0.4"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".alloc-stdlib."0.2.2" = overridableMkRustCrate (profileName: rec { name = "alloc-stdlib"; version = "0.2.2"; @@ -432,7 +414,6 @@ in alloc_no_stdlib = rustPackages."registry+https://github.com/rust-lang/crates.io-index".alloc-no-stdlib."2.0.4" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".anyhow."1.0.68" = overridableMkRustCrate (profileName: rec { name = "anyhow"; version = "1.0.68"; @@ -443,7 +424,6 @@ in [ "std" ] ]; }); - "unknown".api_models."0.1.0" = overridableMkRustCrate (profileName: rec { name = "api_models"; version = "0.1.0"; @@ -466,14 +446,12 @@ in utoipa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".utoipa."3.0.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".arc-swap."1.6.0" = overridableMkRustCrate (profileName: rec { name = "arc-swap"; version = "1.6.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "bddcadddf5e9015d310179a59bb28c4d4b9920ad0f11e8e14dbadf654890c9a6"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".arcstr."1.1.5" = overridableMkRustCrate (profileName: rec { name = "arcstr"; version = "1.1.5"; @@ -484,21 +462,18 @@ in [ "substr" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".arrayref."0.3.6" = overridableMkRustCrate (profileName: rec { name = "arrayref"; version = "0.3.6"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "a4c527152e37cf757a3f78aae5a06fbeefdb07ccc535c980a3208ee3060dd544"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".arrayvec."0.7.2" = overridableMkRustCrate (profileName: rec { name = "arrayvec"; version = "0.7.2"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "8da52d66c7071e2e3fa2a1e5c6d088fec47b593032b254f5e980de8ea54454d6"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".assert-json-diff."2.0.2" = overridableMkRustCrate (profileName: rec { name = "assert-json-diff"; version = "2.0.2"; @@ -509,7 +484,6 @@ in serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; }; }); - "git+https://github.com/juspay/async-bb8-diesel".async-bb8-diesel."0.1.0" = overridableMkRustCrate (profileName: rec { name = "async-bb8-diesel"; version = "0.1.0"; @@ -527,7 +501,6 @@ in tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".async-channel."1.8.0" = overridableMkRustCrate (profileName: rec { name = "async-channel"; version = "1.8.0"; @@ -539,7 +512,6 @@ in futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".async-compression."0.3.15" = overridableMkRustCrate (profileName: rec { name = "async-compression"; version = "0.3.15"; @@ -558,7 +530,6 @@ in tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".async-stream."0.3.3" = overridableMkRustCrate (profileName: rec { name = "async-stream"; version = "0.3.3"; @@ -569,7 +540,6 @@ in futures_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".async-stream-impl."0.3.3" = overridableMkRustCrate (profileName: rec { name = "async-stream-impl"; version = "0.3.3"; @@ -581,7 +551,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".async-trait."0.1.63" = overridableMkRustCrate (profileName: rec { name = "async-trait"; version = "0.1.63"; @@ -593,7 +562,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".atty."0.2.14" = overridableMkRustCrate (profileName: rec { name = "atty"; version = "0.2.14"; @@ -605,14 +573,12 @@ in ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" = overridableMkRustCrate (profileName: rec { name = "autocfg"; version = "1.1.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".awc."3.1.0" = overridableMkRustCrate (profileName: rec { name = "awc"; version = "3.1.0"; @@ -659,7 +625,6 @@ in tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-config."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-config"; version = "0.54.1"; @@ -695,7 +660,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "zeroize" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zeroize."1.5.7" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-credential-types."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-credential-types"; version = "0.54.1"; @@ -709,7 +673,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "zeroize" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zeroize."1.5.7" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-endpoint."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-endpoint"; version = "0.54.1"; @@ -724,7 +687,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-http."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-http"; version = "0.54.1"; @@ -744,7 +706,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-sdk-kms."0.24.0" = overridableMkRustCrate (profileName: rec { name = "aws-sdk-kms"; version = "0.24.0"; @@ -775,7 +736,6 @@ in ${ if rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-sdk-sso."0.24.0" = overridableMkRustCrate (profileName: rec { name = "aws-sdk-sso"; version = "0.24.0"; @@ -800,7 +760,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tower" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-sdk-sts."0.24.0" = overridableMkRustCrate (profileName: rec { name = "aws-sdk-sts"; version = "0.24.0"; @@ -827,7 +786,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-sig-auth."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-sig-auth"; version = "0.54.1"; @@ -842,7 +800,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-sigv4."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-sigv4"; version = "0.54.1"; @@ -869,7 +826,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-async."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-smithy-async"; version = "0.54.1"; @@ -885,7 +841,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio_stream" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-client."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-smithy-client"; version = "0.54.1"; @@ -917,7 +872,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-smithy-http"; version = "0.54.1"; @@ -945,7 +899,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-http-tower."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-smithy-http-tower"; version = "0.54.1"; @@ -962,7 +915,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tracing" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-json."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-smithy-json"; version = "0.54.1"; @@ -972,7 +924,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "aws_smithy_types" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-query."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-smithy-query"; version = "0.54.1"; @@ -983,7 +934,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "urlencoding" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".urlencoding."2.1.2" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-types."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-smithy-types"; version = "0.54.1"; @@ -997,7 +947,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "time" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-smithy-xml."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-smithy-xml"; version = "0.54.1"; @@ -1007,7 +956,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "xmlparser" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".xmlparser."0.13.5" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".aws-types."0.54.1" = overridableMkRustCrate (profileName: rec { name = "aws-types"; version = "0.54.1"; @@ -1026,7 +974,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "rustc_version" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".axum."0.6.2" = overridableMkRustCrate (profileName: rec { name = "axum"; version = "0.6.2"; @@ -1058,7 +1005,6 @@ in rustversion = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".axum-core."0.3.1" = overridableMkRustCrate (profileName: rec { name = "axum-core"; version = "0.3.1"; @@ -1078,7 +1024,6 @@ in rustversion = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" = overridableMkRustCrate (profileName: rec { name = "base64"; version = "0.13.1"; @@ -1089,7 +1034,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" = overridableMkRustCrate (profileName: rec { name = "base64"; version = "0.21.0"; @@ -1100,7 +1044,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".base64-simd."0.7.0" = overridableMkRustCrate (profileName: rec { name = "base64-simd"; version = "0.7.0"; @@ -1116,7 +1059,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "simd_abstraction" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".simd-abstraction."0.7.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".bb8."0.8.0" = overridableMkRustCrate (profileName: rec { name = "bb8"; version = "0.8.0"; @@ -1130,7 +1072,6 @@ in tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".bit-set."0.5.3" = overridableMkRustCrate (profileName: rec { name = "bit-set"; version = "0.5.3"; @@ -1144,7 +1085,6 @@ in bit_vec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bit-vec."0.6.3" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".bit-vec."0.6.3" = overridableMkRustCrate (profileName: rec { name = "bit-vec"; version = "0.6.3"; @@ -1154,7 +1094,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" = overridableMkRustCrate (profileName: rec { name = "bitflags"; version = "1.3.2"; @@ -1164,7 +1103,6 @@ in [ "default" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".blake3."1.3.3" = overridableMkRustCrate (profileName: rec { name = "blake3"; version = "1.3.3"; @@ -1186,7 +1124,6 @@ in cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".block-buffer."0.9.0" = overridableMkRustCrate (profileName: rec { name = "block-buffer"; version = "0.9.0"; @@ -1196,7 +1133,6 @@ in generic_array = rustPackages."registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".block-buffer."0.10.3" = overridableMkRustCrate (profileName: rec { name = "block-buffer"; version = "0.10.3"; @@ -1206,7 +1142,6 @@ in generic_array = rustPackages."registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".brotli."3.3.4" = overridableMkRustCrate (profileName: rec { name = "brotli"; version = "3.3.4"; @@ -1224,7 +1159,6 @@ in brotli_decompressor = rustPackages."registry+https://github.com/rust-lang/crates.io-index".brotli-decompressor."2.3.4" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".brotli-decompressor."2.3.4" = overridableMkRustCrate (profileName: rec { name = "brotli-decompressor"; version = "2.3.4"; @@ -1239,7 +1173,6 @@ in alloc_stdlib = rustPackages."registry+https://github.com/rust-lang/crates.io-index".alloc-stdlib."0.2.2" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".bumpalo."3.12.0" = overridableMkRustCrate (profileName: rec { name = "bumpalo"; version = "3.12.0"; @@ -1249,7 +1182,6 @@ in [ "default" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".byteorder."1.4.3" = overridableMkRustCrate (profileName: rec { name = "byteorder"; version = "1.4.3"; @@ -1260,7 +1192,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" = overridableMkRustCrate (profileName: rec { name = "bytes"; version = "1.3.0"; @@ -1271,7 +1202,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".bytes-utils."0.1.3" = overridableMkRustCrate (profileName: rec { name = "bytes-utils"; version = "0.1.3"; @@ -1286,7 +1216,6 @@ in either = rustPackages."registry+https://github.com/rust-lang/crates.io-index".either."1.8.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".bytestring."1.2.0" = overridableMkRustCrate (profileName: rec { name = "bytestring"; version = "1.2.0"; @@ -1296,7 +1225,6 @@ in bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bytes."1.3.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" = overridableMkRustCrate (profileName: rec { name = "cc"; version = "1.0.78"; @@ -1310,14 +1238,12 @@ in jobserver = rustPackages."registry+https://github.com/rust-lang/crates.io-index".jobserver."0.1.25" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" = overridableMkRustCrate (profileName: rec { name = "cfg-if"; version = "1.0.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".clap."4.1.4" = overridableMkRustCrate (profileName: rec { name = "clap"; version = "4.1.4"; @@ -1336,7 +1262,6 @@ in once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".clap_derive."4.1.0" = overridableMkRustCrate (profileName: rec { name = "clap_derive"; version = "4.1.0"; @@ -1353,7 +1278,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".clap_lex."0.3.1" = overridableMkRustCrate (profileName: rec { name = "clap_lex"; version = "0.3.1"; @@ -1363,7 +1287,6 @@ in os_str_bytes = rustPackages."registry+https://github.com/rust-lang/crates.io-index".os_str_bytes."6.4.1" { inherit profileName; }; }; }); - "unknown".common_utils."0.1.0" = overridableMkRustCrate (profileName: rec { name = "common_utils"; version = "0.1.0"; @@ -1396,7 +1319,6 @@ in proptest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proptest."1.1.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".concurrent-queue."2.1.0" = overridableMkRustCrate (profileName: rec { name = "concurrent-queue"; version = "2.1.0"; @@ -1410,7 +1332,6 @@ in crossbeam_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crossbeam-utils."0.8.14" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".config."0.13.3" = overridableMkRustCrate (profileName: rec { name = "config"; version = "0.13.3"; @@ -1443,21 +1364,18 @@ in yaml_rust = rustPackages."registry+https://github.com/rust-lang/crates.io-index".yaml-rust."0.4.5" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".constant_time_eq."0.2.4" = overridableMkRustCrate (profileName: rec { name = "constant_time_eq"; version = "0.2.4"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "f3ad85c1f65dc7b37604eb0e89748faf0b9653065f2a8ef69f96a687ec1e9279"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".convert_case."0.4.0" = overridableMkRustCrate (profileName: rec { name = "convert_case"; version = "0.4.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".cookie."0.16.2" = overridableMkRustCrate (profileName: rec { name = "cookie"; version = "0.16.2"; @@ -1475,7 +1393,6 @@ in version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".cookie-factory."0.3.2" = overridableMkRustCrate (profileName: rec { name = "cookie-factory"; version = "0.3.2"; @@ -1486,7 +1403,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".core-foundation."0.9.3" = overridableMkRustCrate (profileName: rec { name = "core-foundation"; version = "0.9.3"; @@ -1497,14 +1413,12 @@ in libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".core-foundation-sys."0.8.3" = overridableMkRustCrate (profileName: rec { name = "core-foundation-sys"; version = "0.8.3"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "5827cebf4670468b8772dd191856768aedcb1b0278a04f989f7766351917b9dc"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".cpufeatures."0.2.5" = overridableMkRustCrate (profileName: rec { name = "cpufeatures"; version = "0.2.5"; @@ -1514,14 +1428,12 @@ in ${ if hostPlatform.config == "aarch64-apple-darwin" || hostPlatform.config == "aarch64-linux-android" || hostPlatform.parsed.cpu.name == "aarch64" && hostPlatform.parsed.kernel.name == "linux" then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".crc16."0.4.0" = overridableMkRustCrate (profileName: rec { name = "crc16"; version = "0.4.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "338089f42c427b86394a5ee60ff321da23a5c89c9d89514c829687b26359fcff"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".crc32fast."1.3.2" = overridableMkRustCrate (profileName: rec { name = "crc32fast"; version = "1.3.2"; @@ -1535,7 +1447,6 @@ in cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".crossbeam-channel."0.5.6" = overridableMkRustCrate (profileName: rec { name = "crossbeam-channel"; version = "0.5.6"; @@ -1551,7 +1462,6 @@ in crossbeam_utils = rustPackages."registry+https://github.com/rust-lang/crates.io-index".crossbeam-utils."0.8.14" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".crossbeam-utils."0.8.14" = overridableMkRustCrate (profileName: rec { name = "crossbeam-utils"; version = "0.8.14"; @@ -1564,7 +1474,6 @@ in cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".crypto-common."0.1.6" = overridableMkRustCrate (profileName: rec { name = "crypto-common"; version = "0.1.6"; @@ -1578,7 +1487,6 @@ in typenum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".typenum."1.16.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".dashmap."5.4.0" = overridableMkRustCrate (profileName: rec { name = "dashmap"; version = "5.4.0"; @@ -1592,7 +1500,6 @@ in parking_lot_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.9.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".deadpool."0.9.5" = overridableMkRustCrate (profileName: rec { name = "deadpool"; version = "0.9.5"; @@ -1612,14 +1519,12 @@ in tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".deadpool-runtime."0.1.2" = overridableMkRustCrate (profileName: rec { name = "deadpool-runtime"; version = "0.1.2"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "eaa37046cc0f6c3cc6090fbdbf73ef0b8ef4cfcc37f6befc0020f63e8cf121e1"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".derive_deref."1.1.1" = overridableMkRustCrate (profileName: rec { name = "derive_deref"; version = "1.1.1"; @@ -1631,7 +1536,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".derive_more."0.99.17" = overridableMkRustCrate (profileName: rec { name = "derive_more"; version = "0.99.17"; @@ -1675,7 +1579,6 @@ in rustc_version = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".diesel."2.0.3" = overridableMkRustCrate (profileName: rec { name = "diesel"; version = "2.0.3"; @@ -1706,7 +1609,6 @@ in time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".diesel_derives."2.0.1" = overridableMkRustCrate (profileName: rec { name = "diesel_derives"; version = "2.0.1"; @@ -1725,7 +1627,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".digest."0.9.0" = overridableMkRustCrate (profileName: rec { name = "digest"; version = "0.9.0"; @@ -1739,7 +1640,6 @@ in generic_array = rustPackages."registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" = overridableMkRustCrate (profileName: rec { name = "digest"; version = "0.10.6"; @@ -1760,14 +1660,12 @@ in subtle = rustPackages."registry+https://github.com/rust-lang/crates.io-index".subtle."2.4.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".dlv-list."0.3.0" = overridableMkRustCrate (profileName: rec { name = "dlv-list"; version = "0.3.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "0688c2a7f92e427f44895cd63841bff7b29f8d7a1648b9e7e07a4a365b2e1257"; }; }); - "unknown".drainer."0.1.0" = overridableMkRustCrate (profileName: rec { name = "drainer"; version = "0.1.0"; @@ -1795,14 +1693,12 @@ in router_env = buildRustPackages."unknown".router_env."0.1.0" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".dyn-clone."1.0.10" = overridableMkRustCrate (profileName: rec { name = "dyn-clone"; version = "1.0.10"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "c9b0705efd4599c15a38151f4721f7bc388306f61084d3bfd50bd07fbca5cb60"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".either."1.8.0" = overridableMkRustCrate (profileName: rec { name = "either"; version = "1.8.0"; @@ -1813,7 +1709,6 @@ in [ "use_std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".encoding_rs."0.8.31" = overridableMkRustCrate (profileName: rec { name = "encoding_rs"; version = "0.8.31"; @@ -1827,7 +1722,6 @@ in cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".env_logger."0.7.1" = overridableMkRustCrate (profileName: rec { name = "env_logger"; version = "0.7.1"; @@ -1848,7 +1742,6 @@ in termcolor = rustPackages."registry+https://github.com/rust-lang/crates.io-index".termcolor."1.2.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".error-stack."0.2.4" = overridableMkRustCrate (profileName: rec { name = "error-stack"; version = "0.2.4"; @@ -1867,14 +1760,12 @@ in rustc_version = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".event-listener."2.5.3" = overridableMkRustCrate (profileName: rec { name = "event-listener"; version = "2.5.3"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".fake."2.5.0" = overridableMkRustCrate (profileName: rec { name = "fake"; version = "2.5.0"; @@ -1884,7 +1775,6 @@ in rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".fastrand."1.8.0" = overridableMkRustCrate (profileName: rec { name = "fastrand"; version = "1.8.0"; @@ -1894,7 +1784,6 @@ in ${ if hostPlatform.parsed.cpu.name == "wasm32" then "instant" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".instant."0.1.12" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".flate2."1.0.25" = overridableMkRustCrate (profileName: rec { name = "flate2"; version = "1.0.25"; @@ -1910,7 +1799,6 @@ in miniz_oxide = rustPackages."registry+https://github.com/rust-lang/crates.io-index".miniz_oxide."0.6.2" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".float-cmp."0.8.0" = overridableMkRustCrate (profileName: rec { name = "float-cmp"; version = "0.8.0"; @@ -1925,7 +1813,6 @@ in num_traits = rustPackages."registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".fnv."1.0.7" = overridableMkRustCrate (profileName: rec { name = "fnv"; version = "1.0.7"; @@ -1936,7 +1823,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".foreign-types."0.3.2" = overridableMkRustCrate (profileName: rec { name = "foreign-types"; version = "0.3.2"; @@ -1946,14 +1832,12 @@ in foreign_types_shared = rustPackages."registry+https://github.com/rust-lang/crates.io-index".foreign-types-shared."0.1.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".foreign-types-shared."0.1.1" = overridableMkRustCrate (profileName: rec { name = "foreign-types-shared"; version = "0.1.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".form_urlencoded."1.1.0" = overridableMkRustCrate (profileName: rec { name = "form_urlencoded"; version = "1.1.0"; @@ -1963,7 +1847,6 @@ in percent_encoding = rustPackages."registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".fred."5.2.0" = overridableMkRustCrate (profileName: rec { name = "fred"; version = "5.2.0"; @@ -2008,7 +1891,6 @@ in url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".frunk."0.4.1" = overridableMkRustCrate (profileName: rec { name = "frunk"; version = "0.4.1"; @@ -2027,7 +1909,6 @@ in frunk_proc_macros = rustPackages."registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macros."0.1.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".frunk_core."0.4.1" = overridableMkRustCrate (profileName: rec { name = "frunk_core"; version = "0.4.1"; @@ -2038,7 +1919,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".frunk_derives."0.4.1" = overridableMkRustCrate (profileName: rec { name = "frunk_derives"; version = "0.4.1"; @@ -2050,7 +1930,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macro_helpers."0.1.1" = overridableMkRustCrate (profileName: rec { name = "frunk_proc_macro_helpers"; version = "0.1.1"; @@ -2063,7 +1942,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macros."0.1.1" = overridableMkRustCrate (profileName: rec { name = "frunk_proc_macros"; version = "0.1.1"; @@ -2075,7 +1953,6 @@ in proc_macro_hack = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro-hack."0.5.20+deprecated" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".frunk_proc_macros_impl."0.1.1" = overridableMkRustCrate (profileName: rec { name = "frunk_proc_macros_impl"; version = "0.1.1"; @@ -2089,7 +1966,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".futures."0.3.25" = overridableMkRustCrate (profileName: rec { name = "futures"; version = "0.3.25"; @@ -2113,7 +1989,6 @@ in futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".futures-channel."0.3.25" = overridableMkRustCrate (profileName: rec { name = "futures-channel"; version = "0.3.25"; @@ -2131,7 +2006,6 @@ in futures_sink = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".futures-core."0.3.25" = overridableMkRustCrate (profileName: rec { name = "futures-core"; version = "0.3.25"; @@ -2143,7 +2017,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".futures-executor."0.3.25" = overridableMkRustCrate (profileName: rec { name = "futures-executor"; version = "0.3.25"; @@ -2159,7 +2032,6 @@ in futures_util = rustPackages."registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".futures-io."0.3.25" = overridableMkRustCrate (profileName: rec { name = "futures-io"; version = "0.3.25"; @@ -2170,7 +2042,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".futures-lite."1.12.0" = overridableMkRustCrate (profileName: rec { name = "futures-lite"; version = "1.12.0"; @@ -2196,7 +2067,6 @@ in waker_fn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".waker-fn."1.1.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".futures-macro."0.3.25" = overridableMkRustCrate (profileName: rec { name = "futures-macro"; version = "0.3.25"; @@ -2208,7 +2078,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".futures-sink."0.3.25" = overridableMkRustCrate (profileName: rec { name = "futures-sink"; version = "0.3.25"; @@ -2220,7 +2089,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".futures-task."0.3.25" = overridableMkRustCrate (profileName: rec { name = "futures-task"; version = "0.3.25"; @@ -2231,14 +2099,12 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".futures-timer."3.0.2" = overridableMkRustCrate (profileName: rec { name = "futures-timer"; version = "3.0.2"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "e64b03909df88034c26dc1547e8970b91f98bdb65165d6a4e9110d94263dbb2c"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".futures-util."0.3.25" = overridableMkRustCrate (profileName: rec { name = "futures-util"; version = "0.3.25"; @@ -2273,7 +2139,6 @@ in slab = rustPackages."registry+https://github.com/rust-lang/crates.io-index".slab."0.4.7" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".generic-array."0.14.6" = overridableMkRustCrate (profileName: rec { name = "generic-array"; version = "0.14.6"; @@ -2289,7 +2154,6 @@ in version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".gethostname."0.4.1" = overridableMkRustCrate (profileName: rec { name = "gethostname"; version = "0.4.1"; @@ -2300,7 +2164,6 @@ in ${ if hostPlatform.isWindows then "windows" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows."0.43.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".getrandom."0.1.16" = overridableMkRustCrate (profileName: rec { name = "getrandom"; version = "0.1.16"; @@ -2315,7 +2178,6 @@ in ${ if hostPlatform.parsed.kernel.name == "wasi" then "wasi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasi."0.9.0+wasi-snapshot-preview1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".getrandom."0.2.8" = overridableMkRustCrate (profileName: rec { name = "getrandom"; version = "0.2.8"; @@ -2330,7 +2192,6 @@ in ${ if hostPlatform.parsed.kernel.name == "wasi" then "wasi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasi."0.11.0+wasi-snapshot-preview1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".git2."0.16.1" = overridableMkRustCrate (profileName: rec { name = "git2"; version = "0.16.1"; @@ -2344,7 +2205,6 @@ in url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".h2."0.3.15" = overridableMkRustCrate (profileName: rec { name = "h2"; version = "0.3.15"; @@ -2364,7 +2224,6 @@ in tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".hashbrown."0.12.3" = overridableMkRustCrate (profileName: rec { name = "hashbrown"; version = "0.12.3"; @@ -2380,7 +2239,6 @@ in ahash = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ahash."0.7.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".heck."0.4.0" = overridableMkRustCrate (profileName: rec { name = "heck"; version = "0.4.0"; @@ -2390,7 +2248,6 @@ in [ "default" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".hermit-abi."0.1.19" = overridableMkRustCrate (profileName: rec { name = "hermit-abi"; version = "0.1.19"; @@ -2403,7 +2260,6 @@ in libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".hermit-abi."0.2.6" = overridableMkRustCrate (profileName: rec { name = "hermit-abi"; version = "0.2.6"; @@ -2416,7 +2272,6 @@ in libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".hex."0.4.3" = overridableMkRustCrate (profileName: rec { name = "hex"; version = "0.4.3"; @@ -2428,7 +2283,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".hmac."0.12.1" = overridableMkRustCrate (profileName: rec { name = "hmac"; version = "0.12.1"; @@ -2438,7 +2292,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "digest" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".http."0.2.8" = overridableMkRustCrate (profileName: rec { name = "http"; version = "0.2.8"; @@ -2450,7 +2303,6 @@ in itoa = rustPackages."registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".http-body."0.4.5" = overridableMkRustCrate (profileName: rec { name = "http-body"; version = "0.4.5"; @@ -2462,14 +2314,12 @@ in pin_project_lite = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".http-range-header."0.3.0" = overridableMkRustCrate (profileName: rec { name = "http-range-header"; version = "0.3.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "0bfe8eed0a9285ef776bb792479ea3834e8b94e13d615c2f66d03dd50a435a29"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".http-types."2.12.0" = overridableMkRustCrate (profileName: rec { name = "http-types"; version = "2.12.0"; @@ -2495,7 +2345,6 @@ in url = rustPackages."registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".httparse."1.8.0" = overridableMkRustCrate (profileName: rec { name = "httparse"; version = "1.8.0"; @@ -2506,14 +2355,12 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".httpdate."1.0.2" = overridableMkRustCrate (profileName: rec { name = "httpdate"; version = "1.0.2"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "c4a1e36c821dbe04574f602848a19f742f4fb3c98d40449f11bcad18d6b17421"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".humantime."1.3.0" = overridableMkRustCrate (profileName: rec { name = "humantime"; version = "1.3.0"; @@ -2523,7 +2370,6 @@ in quick_error = rustPackages."registry+https://github.com/rust-lang/crates.io-index".quick-error."1.2.3" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".hyper."0.14.23" = overridableMkRustCrate (profileName: rec { name = "hyper"; version = "0.14.23"; @@ -2561,7 +2407,6 @@ in want = rustPackages."registry+https://github.com/rust-lang/crates.io-index".want."0.3.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".hyper-rustls."0.23.2" = overridableMkRustCrate (profileName: rec { name = "hyper-rustls"; version = "0.23.2"; @@ -2588,7 +2433,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "tokio_rustls" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-rustls."0.23.4" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".hyper-timeout."0.4.1" = overridableMkRustCrate (profileName: rec { name = "hyper-timeout"; version = "0.4.1"; @@ -2601,7 +2445,6 @@ in tokio_io_timeout = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-io-timeout."1.2.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".hyper-tls."0.5.0" = overridableMkRustCrate (profileName: rec { name = "hyper-tls"; version = "0.5.0"; @@ -2615,7 +2458,6 @@ in tokio_native_tls = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-native-tls."0.3.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".idna."0.3.0" = overridableMkRustCrate (profileName: rec { name = "idna"; version = "0.3.0"; @@ -2626,7 +2468,6 @@ in unicode_normalization = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unicode-normalization."0.1.22" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".indexmap."1.9.2" = overridableMkRustCrate (profileName: rec { name = "indexmap"; version = "1.9.2"; @@ -2644,14 +2485,12 @@ in autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".infer."0.2.3" = overridableMkRustCrate (profileName: rec { name = "infer"; version = "0.2.3"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "64e9829a50b42bb782c1df523f78d332fe371b10c661e78b7a3c34b0198e9fac"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".instant."0.1.12" = overridableMkRustCrate (profileName: rec { name = "instant"; version = "0.1.12"; @@ -2661,7 +2500,6 @@ in cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".ipnet."2.7.1" = overridableMkRustCrate (profileName: rec { name = "ipnet"; version = "2.7.1"; @@ -2671,14 +2509,12 @@ in [ "default" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".is_ci."1.1.1" = overridableMkRustCrate (profileName: rec { name = "is_ci"; version = "1.1.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "616cde7c720bb2bb5824a224687d8f77bfd38922027f01d825cd7453be5099fb"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".itertools."0.10.5" = overridableMkRustCrate (profileName: rec { name = "itertools"; version = "0.10.5"; @@ -2691,7 +2527,6 @@ in either = rustPackages."registry+https://github.com/rust-lang/crates.io-index".either."1.8.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".itoa."0.4.8" = overridableMkRustCrate (profileName: rec { name = "itoa"; version = "0.4.8"; @@ -2701,14 +2536,12 @@ in [ "i128" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".itoa."1.0.5" = overridableMkRustCrate (profileName: rec { name = "itoa"; version = "1.0.5"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".jobserver."0.1.25" = overridableMkRustCrate (profileName: rec { name = "jobserver"; version = "0.1.25"; @@ -2718,7 +2551,6 @@ in ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".josekit."0.8.1" = overridableMkRustCrate (profileName: rec { name = "josekit"; version = "0.8.1"; @@ -2737,7 +2569,6 @@ in ${ if rootFeatures' ? "router/basilisk" || rootFeatures' ? "router/josekit" || rootFeatures' ? "router/sandbox" then "time" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".js-sys."0.3.60" = overridableMkRustCrate (profileName: rec { name = "js-sys"; version = "0.3.60"; @@ -2747,7 +2578,6 @@ in wasm_bindgen = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen."0.2.83" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".json5."0.4.1" = overridableMkRustCrate (profileName: rec { name = "json5"; version = "0.4.1"; @@ -2759,7 +2589,6 @@ in serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".jsonwebtoken."8.2.0" = overridableMkRustCrate (profileName: rec { name = "jsonwebtoken"; version = "8.2.0"; @@ -2780,21 +2609,18 @@ in simple_asn1 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".simple_asn1."0.6.2" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".language-tags."0.3.2" = overridableMkRustCrate (profileName: rec { name = "language-tags"; version = "0.3.2"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "d4345964bb142484797b161f473a503a434de77149dd8c7427788c6e13379388"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" = overridableMkRustCrate (profileName: rec { name = "lazy_static"; version = "1.4.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" = overridableMkRustCrate (profileName: rec { name = "libc"; version = "0.2.139"; @@ -2805,7 +2631,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".libgit2-sys."0.14.2+1.5.1" = overridableMkRustCrate (profileName: rec { name = "libgit2-sys"; version = "0.14.2+1.5.1"; @@ -2820,7 +2645,6 @@ in pkg_config = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pkg-config."0.3.26" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".libm."0.2.6" = overridableMkRustCrate (profileName: rec { name = "libm"; version = "0.2.6"; @@ -2830,7 +2654,6 @@ in [ "default" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".libmimalloc-sys."0.1.30" = overridableMkRustCrate (profileName: rec { name = "libmimalloc-sys"; version = "0.1.30"; @@ -2846,7 +2669,6 @@ in ${ if rootFeatures' ? "router/mimalloc" then "cc" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".libz-sys."1.1.8" = overridableMkRustCrate (profileName: rec { name = "libz-sys"; version = "1.1.8"; @@ -2864,21 +2686,18 @@ in ${ if hostPlatform.parsed.abi.name == "msvc" then "vcpkg" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".vcpkg."0.2.15" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".linked-hash-map."0.5.6" = overridableMkRustCrate (profileName: rec { name = "linked-hash-map"; version = "0.5.6"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".literally."0.1.3" = overridableMkRustCrate (profileName: rec { name = "literally"; version = "0.1.3"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "f0d2be3f5a0d4d5c983d1f8ecc2a87676a0875a14feb9eebf0675f7c3e2f3c35"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".local-channel."0.1.3" = overridableMkRustCrate (profileName: rec { name = "local-channel"; version = "0.1.3"; @@ -2891,14 +2710,12 @@ in local_waker = rustPackages."registry+https://github.com/rust-lang/crates.io-index".local-waker."0.1.3" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".local-waker."0.1.3" = overridableMkRustCrate (profileName: rec { name = "local-waker"; version = "0.1.3"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "e34f76eb3611940e0e7d53a9aaa4e6a3151f69541a282fd0dad5571420c53ff1"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".lock_api."0.4.9" = overridableMkRustCrate (profileName: rec { name = "lock_api"; version = "0.4.9"; @@ -2911,7 +2728,6 @@ in autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" = overridableMkRustCrate (profileName: rec { name = "log"; version = "0.4.17"; @@ -2924,7 +2740,6 @@ in cfg_if = rustPackages."registry+https://github.com/rust-lang/crates.io-index".cfg-if."1.0.0" { inherit profileName; }; }; }); - "unknown".masking."0.1.0" = overridableMkRustCrate (profileName: rec { name = "masking"; version = "0.1.0"; @@ -2949,7 +2764,6 @@ in serde_json = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".matchers."0.1.0" = overridableMkRustCrate (profileName: rec { name = "matchers"; version = "0.1.0"; @@ -2959,7 +2773,6 @@ in regex_automata = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex-automata."0.1.10" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".matchit."0.7.0" = overridableMkRustCrate (profileName: rec { name = "matchit"; version = "0.7.0"; @@ -2969,7 +2782,6 @@ in [ "default" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".maud."0.24.0" = overridableMkRustCrate (profileName: rec { name = "maud"; version = "0.24.0"; @@ -2988,7 +2800,6 @@ in maud_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".maud_macros."0.24.0" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".maud_macros."0.24.0" = overridableMkRustCrate (profileName: rec { name = "maud_macros"; version = "0.24.0"; @@ -3001,7 +2812,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" = overridableMkRustCrate (profileName: rec { name = "memchr"; version = "2.5.0"; @@ -3012,7 +2822,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".mimalloc."0.1.34" = overridableMkRustCrate (profileName: rec { name = "mimalloc"; version = "0.1.34"; @@ -3026,14 +2835,12 @@ in ${ if rootFeatures' ? "router/mimalloc" then "libmimalloc_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libmimalloc-sys."0.1.30" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".mime."0.3.16" = overridableMkRustCrate (profileName: rec { name = "mime"; version = "0.3.16"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "2a60c7ce501c71e03a9c9c0d35b861413ae925bd979cc7a4e30d060069aaac8d"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".minimal-lexical."0.2.1" = overridableMkRustCrate (profileName: rec { name = "minimal-lexical"; version = "0.2.1"; @@ -3043,7 +2850,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".miniz_oxide."0.6.2" = overridableMkRustCrate (profileName: rec { name = "miniz_oxide"; version = "0.6.2"; @@ -3056,7 +2862,6 @@ in adler = rustPackages."registry+https://github.com/rust-lang/crates.io-index".adler."1.0.2" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".mio."0.8.5" = overridableMkRustCrate (profileName: rec { name = "mio"; version = "0.8.5"; @@ -3075,7 +2880,6 @@ in ${ if hostPlatform.isWindows then "windows_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".nanoid."0.4.0" = overridableMkRustCrate (profileName: rec { name = "nanoid"; version = "0.4.0"; @@ -3085,7 +2889,6 @@ in rand = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".native-tls."0.2.11" = overridableMkRustCrate (profileName: rec { name = "native-tls"; version = "0.2.11"; @@ -3104,7 +2907,6 @@ in ${ if hostPlatform.parsed.kernel.name == "darwin" || hostPlatform.parsed.kernel.name == "ios" then "tempfile" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tempfile."3.3.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".nom."7.1.3" = overridableMkRustCrate (profileName: rec { name = "nom"; version = "7.1.3"; @@ -3120,7 +2922,6 @@ in minimal_lexical = rustPackages."registry+https://github.com/rust-lang/crates.io-index".minimal-lexical."0.2.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".nom8."0.2.0" = overridableMkRustCrate (profileName: rec { name = "nom8"; version = "0.2.0"; @@ -3135,7 +2936,6 @@ in memchr = rustPackages."registry+https://github.com/rust-lang/crates.io-index".memchr."2.5.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".nu-ansi-term."0.46.0" = overridableMkRustCrate (profileName: rec { name = "nu-ansi-term"; version = "0.46.0"; @@ -3146,7 +2946,6 @@ in ${ if hostPlatform.parsed.kernel.name == "windows" then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".num-bigint."0.4.3" = overridableMkRustCrate (profileName: rec { name = "num-bigint"; version = "0.4.3"; @@ -3160,7 +2959,6 @@ in autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".num-integer."0.1.45" = overridableMkRustCrate (profileName: rec { name = "num-integer"; version = "0.1.45"; @@ -3178,7 +2976,6 @@ in autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".num-traits."0.2.15" = overridableMkRustCrate (profileName: rec { name = "num-traits"; version = "0.2.15"; @@ -3196,7 +2993,6 @@ in autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".num_cpus."1.15.0" = overridableMkRustCrate (profileName: rec { name = "num_cpus"; version = "1.15.0"; @@ -3207,7 +3003,6 @@ in ${ if !hostPlatform.isWindows then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" = overridableMkRustCrate (profileName: rec { name = "once_cell"; version = "1.17.0"; @@ -3220,14 +3015,12 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".opaque-debug."0.3.0" = overridableMkRustCrate (profileName: rec { name = "opaque-debug"; version = "0.3.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".openssl."0.10.45" = overridableMkRustCrate (profileName: rec { name = "openssl"; version = "0.10.45"; @@ -3246,7 +3039,6 @@ in ffi = rustPackages."registry+https://github.com/rust-lang/crates.io-index".openssl-sys."0.9.80" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".openssl-macros."0.1.0" = overridableMkRustCrate (profileName: rec { name = "openssl-macros"; version = "0.1.0"; @@ -3258,14 +3050,12 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".openssl-probe."0.1.5" = overridableMkRustCrate (profileName: rec { name = "openssl-probe"; version = "0.1.5"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".openssl-sys."0.9.80" = overridableMkRustCrate (profileName: rec { name = "openssl-sys"; version = "0.9.80"; @@ -3281,7 +3071,6 @@ in ${ if hostPlatform.parsed.abi.name == "msvc" then "vcpkg" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".vcpkg."0.2.15" { profileName = "__noProfile"; }; }; }); - "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry."0.18.0" = overridableMkRustCrate (profileName: rec { name = "opentelemetry"; version = "0.18.0"; @@ -3302,7 +3091,6 @@ in opentelemetry_sdk = rustPackages."git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry_sdk."0.18.0" { inherit profileName; }; }; }); - "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry-otlp."0.11.0" = overridableMkRustCrate (profileName: rec { name = "opentelemetry-otlp"; version = "0.11.0"; @@ -3335,7 +3123,6 @@ in tonic = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tonic."0.8.3" { inherit profileName; }; }; }); - "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry-proto."0.1.0" = overridableMkRustCrate (profileName: rec { name = "opentelemetry-proto"; version = "0.1.0"; @@ -3360,7 +3147,6 @@ in tonic = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tonic."0.8.3" { inherit profileName; }; }; }); - "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry_api."0.18.0" = overridableMkRustCrate (profileName: rec { name = "opentelemetry_api"; version = "0.18.0"; @@ -3388,7 +3174,6 @@ in thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; }; }); - "git+https://github.com/open-telemetry/opentelemetry-rust".opentelemetry_sdk."0.18.0" = overridableMkRustCrate (profileName: rec { name = "opentelemetry_sdk"; version = "0.18.0"; @@ -3429,7 +3214,6 @@ in tokio_stream = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".ordered-multimap."0.4.3" = overridableMkRustCrate (profileName: rec { name = "ordered-multimap"; version = "0.4.3"; @@ -3440,7 +3224,6 @@ in hashbrown = rustPackages."registry+https://github.com/rust-lang/crates.io-index".hashbrown."0.12.3" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".os_str_bytes."6.4.1" = overridableMkRustCrate (profileName: rec { name = "os_str_bytes"; version = "6.4.1"; @@ -3450,21 +3233,18 @@ in [ "raw_os_str" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".outref."0.1.0" = overridableMkRustCrate (profileName: rec { name = "outref"; version = "0.1.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "7f222829ae9293e33a9f5e9f440c6760a3d450a64affe1846486b140db81c1f4"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".overload."0.1.1" = overridableMkRustCrate (profileName: rec { name = "overload"; version = "0.1.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "b15813163c1d831bf4a13c3610c05c0d03b39feb07f7e09fa234dac9b15aaf39"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".owo-colors."3.5.0" = overridableMkRustCrate (profileName: rec { name = "owo-colors"; version = "3.5.0"; @@ -3478,14 +3258,12 @@ in supports_color = rustPackages."registry+https://github.com/rust-lang/crates.io-index".supports-color."1.3.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".parking."2.0.0" = overridableMkRustCrate (profileName: rec { name = "parking"; version = "2.0.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "427c3892f9e783d91cc128285287e70a59e206ca452770ece88a76f7a3eddd72"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.11.2" = overridableMkRustCrate (profileName: rec { name = "parking_lot"; version = "0.11.2"; @@ -3500,7 +3278,6 @@ in parking_lot_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.8.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" = overridableMkRustCrate (profileName: rec { name = "parking_lot"; version = "0.12.1"; @@ -3514,7 +3291,6 @@ in parking_lot_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.9.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.8.6" = overridableMkRustCrate (profileName: rec { name = "parking_lot_core"; version = "0.8.6"; @@ -3529,7 +3305,6 @@ in ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".parking_lot_core."0.9.6" = overridableMkRustCrate (profileName: rec { name = "parking_lot_core"; version = "0.9.6"; @@ -3543,21 +3318,18 @@ in ${ if hostPlatform.isWindows then "windows_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".paste."1.0.11" = overridableMkRustCrate (profileName: rec { name = "paste"; version = "1.0.11"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "d01a5bd0424d00070b0098dd17ebca6f961a959dead1dbcbbbc1d1cd8d3deeba"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".pathdiff."0.2.1" = overridableMkRustCrate (profileName: rec { name = "pathdiff"; version = "0.2.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".pem."1.1.1" = overridableMkRustCrate (profileName: rec { name = "pem"; version = "1.1.1"; @@ -3567,7 +3339,6 @@ in base64 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.13.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".percent-encoding."2.2.0" = overridableMkRustCrate (profileName: rec { name = "percent-encoding"; version = "2.2.0"; @@ -3578,7 +3349,6 @@ in [ "default" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".pest."2.5.3" = overridableMkRustCrate (profileName: rec { name = "pest"; version = "2.5.3"; @@ -3594,7 +3364,6 @@ in ucd_trie = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ucd-trie."0.1.5" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".pest_derive."2.5.3" = overridableMkRustCrate (profileName: rec { name = "pest_derive"; version = "2.5.3"; @@ -3609,7 +3378,6 @@ in pest_generator = rustPackages."registry+https://github.com/rust-lang/crates.io-index".pest_generator."2.5.3" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".pest_generator."2.5.3" = overridableMkRustCrate (profileName: rec { name = "pest_generator"; version = "2.5.3"; @@ -3626,7 +3394,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".pest_meta."2.5.3" = overridableMkRustCrate (profileName: rec { name = "pest_meta"; version = "2.5.3"; @@ -3640,7 +3407,6 @@ in sha2 = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".sha2."0.10.6" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".pin-project."1.0.12" = overridableMkRustCrate (profileName: rec { name = "pin-project"; version = "1.0.12"; @@ -3650,7 +3416,6 @@ in pin_project_internal = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pin-project-internal."1.0.12" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".pin-project-internal."1.0.12" = overridableMkRustCrate (profileName: rec { name = "pin-project-internal"; version = "1.0.12"; @@ -3662,28 +3427,24 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".pin-project-lite."0.2.9" = overridableMkRustCrate (profileName: rec { name = "pin-project-lite"; version = "0.2.9"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".pin-utils."0.1.0" = overridableMkRustCrate (profileName: rec { name = "pin-utils"; version = "0.1.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".pkg-config."0.3.26" = overridableMkRustCrate (profileName: rec { name = "pkg-config"; version = "0.3.26"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "6ac9a59f73473f1b8d852421e59e64809f025994837ef743615c6d0c5b305160"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".ppv-lite86."0.2.17" = overridableMkRustCrate (profileName: rec { name = "ppv-lite86"; version = "0.2.17"; @@ -3694,7 +3455,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".pq-sys."0.4.7" = overridableMkRustCrate (profileName: rec { name = "pq-sys"; version = "0.4.7"; @@ -3704,7 +3464,6 @@ in ${ if hostPlatform.parsed.abi.name == "msvc" then "vcpkg" else null } = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".vcpkg."0.2.15" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".pretty_env_logger."0.4.0" = overridableMkRustCrate (profileName: rec { name = "pretty_env_logger"; version = "0.4.0"; @@ -3715,7 +3474,6 @@ in log = rustPackages."registry+https://github.com/rust-lang/crates.io-index".log."0.4.17" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".proc-macro-error."1.0.4" = overridableMkRustCrate (profileName: rec { name = "proc-macro-error"; version = "1.0.4"; @@ -3736,7 +3494,6 @@ in version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".proc-macro-error-attr."1.0.4" = overridableMkRustCrate (profileName: rec { name = "proc-macro-error-attr"; version = "1.0.4"; @@ -3750,14 +3507,12 @@ in version_check = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".proc-macro-hack."0.5.20+deprecated" = overridableMkRustCrate (profileName: rec { name = "proc-macro-hack"; version = "0.5.20+deprecated"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" = overridableMkRustCrate (profileName: rec { name = "proc-macro2"; version = "1.0.50"; @@ -3771,7 +3526,6 @@ in unicode_ident = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unicode-ident."1.0.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".proptest."1.1.0" = overridableMkRustCrate (profileName: rec { name = "proptest"; version = "1.1.0"; @@ -3806,7 +3560,6 @@ in unarray = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unarray."0.1.4" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".prost."0.11.6" = overridableMkRustCrate (profileName: rec { name = "prost"; version = "0.11.6"; @@ -3822,7 +3575,6 @@ in prost_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".prost-derive."0.11.6" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".prost-derive."0.11.6" = overridableMkRustCrate (profileName: rec { name = "prost-derive"; version = "0.11.6"; @@ -3836,21 +3588,18 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".quick-error."1.2.3" = overridableMkRustCrate (profileName: rec { name = "quick-error"; version = "1.2.3"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "a1d01941d82fa2ab50be1e79e6714289dd7cde78eba4c074bc5a4374f650dfe0"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".quick-error."2.0.1" = overridableMkRustCrate (profileName: rec { name = "quick-error"; version = "2.0.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".quote."1.0.23" = overridableMkRustCrate (profileName: rec { name = "quote"; version = "1.0.23"; @@ -3864,7 +3613,6 @@ in proc_macro2 = rustPackages."registry+https://github.com/rust-lang/crates.io-index".proc-macro2."1.0.50" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".r2d2."0.8.10" = overridableMkRustCrate (profileName: rec { name = "r2d2"; version = "0.8.10"; @@ -3876,7 +3624,6 @@ in scheduled_thread_pool = rustPackages."registry+https://github.com/rust-lang/crates.io-index".scheduled-thread-pool."0.2.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rand."0.7.3" = overridableMkRustCrate (profileName: rec { name = "rand"; version = "0.7.3"; @@ -3898,7 +3645,6 @@ in ${ if hostPlatform.parsed.kernel.name == "emscripten" then "rand_hc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_hc."0.2.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rand."0.8.5" = overridableMkRustCrate (profileName: rec { name = "rand"; version = "0.8.5"; @@ -3920,7 +3666,6 @@ in rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.6.4" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rand_chacha."0.2.2" = overridableMkRustCrate (profileName: rec { name = "rand_chacha"; version = "0.2.2"; @@ -3934,7 +3679,6 @@ in rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.5.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rand_chacha."0.3.1" = overridableMkRustCrate (profileName: rec { name = "rand_chacha"; version = "0.3.1"; @@ -3948,7 +3692,6 @@ in rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.6.4" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rand_core."0.5.1" = overridableMkRustCrate (profileName: rec { name = "rand_core"; version = "0.5.1"; @@ -3963,7 +3706,6 @@ in getrandom = rustPackages."registry+https://github.com/rust-lang/crates.io-index".getrandom."0.1.16" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rand_core."0.6.4" = overridableMkRustCrate (profileName: rec { name = "rand_core"; version = "0.6.4"; @@ -3978,7 +3720,6 @@ in getrandom = rustPackages."registry+https://github.com/rust-lang/crates.io-index".getrandom."0.2.8" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rand_hc."0.2.0" = overridableMkRustCrate (profileName: rec { name = "rand_hc"; version = "0.2.0"; @@ -3988,7 +3729,6 @@ in rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.5.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rand_xorshift."0.3.0" = overridableMkRustCrate (profileName: rec { name = "rand_xorshift"; version = "0.3.0"; @@ -3998,7 +3738,6 @@ in rand_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".rand_core."0.6.4" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".redis-protocol."4.1.0" = overridableMkRustCrate (profileName: rec { name = "redis-protocol"; version = "4.1.0"; @@ -4017,7 +3756,6 @@ in nom = rustPackages."registry+https://github.com/rust-lang/crates.io-index".nom."7.1.3" { inherit profileName; }; }; }); - "unknown".redis_interface."0.1.0" = overridableMkRustCrate (profileName: rec { name = "redis_interface"; version = "0.1.0"; @@ -4036,7 +3774,6 @@ in tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".redox_syscall."0.2.16" = overridableMkRustCrate (profileName: rec { name = "redox_syscall"; version = "0.2.16"; @@ -4046,7 +3783,6 @@ in bitflags = rustPackages."registry+https://github.com/rust-lang/crates.io-index".bitflags."1.3.2" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".regex."1.7.1" = overridableMkRustCrate (profileName: rec { name = "regex"; version = "1.7.1"; @@ -4077,7 +3813,6 @@ in regex_syntax = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex-syntax."0.6.28" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".regex-automata."0.1.10" = overridableMkRustCrate (profileName: rec { name = "regex-automata"; version = "0.1.10"; @@ -4092,7 +3827,6 @@ in regex_syntax = rustPackages."registry+https://github.com/rust-lang/crates.io-index".regex-syntax."0.6.28" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".regex-syntax."0.6.28" = overridableMkRustCrate (profileName: rec { name = "regex-syntax"; version = "0.6.28"; @@ -4110,7 +3844,6 @@ in [ "unicode-segment" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".remove_dir_all."0.5.3" = overridableMkRustCrate (profileName: rec { name = "remove_dir_all"; version = "0.5.3"; @@ -4120,7 +3853,6 @@ in ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".reqwest."0.11.14" = overridableMkRustCrate (profileName: rec { name = "reqwest"; version = "0.11.14"; @@ -4174,14 +3906,12 @@ in ${ if hostPlatform.isWindows then "winreg" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winreg."0.10.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".retain_mut."0.1.9" = overridableMkRustCrate (profileName: rec { name = "retain_mut"; version = "0.1.9"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "4389f1d5789befaf6029ebd9f7dac4af7f7e3d61b69d4f30e2ac02b57e7712b0"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".ring."0.16.20" = overridableMkRustCrate (profileName: rec { name = "ring"; version = "0.16.20"; @@ -4206,7 +3936,6 @@ in cc = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".cc."1.0.78" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".ron."0.7.1" = overridableMkRustCrate (profileName: rec { name = "ron"; version = "0.7.1"; @@ -4218,7 +3947,6 @@ in serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; }; }); - "unknown".router."0.2.0" = overridableMkRustCrate (profileName: rec { name = "router"; version = "0.2.0"; @@ -4316,7 +4044,6 @@ in router_env = buildRustPackages."unknown".router_env."0.1.0" { profileName = "__noProfile"; }; }; }); - "unknown".router_derive."0.1.0" = overridableMkRustCrate (profileName: rec { name = "router_derive"; version = "0.1.0"; @@ -4334,7 +4061,6 @@ in strum = rustPackages."registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" { inherit profileName; }; }; }); - "unknown".router_env."0.1.0" = overridableMkRustCrate (profileName: rec { name = "router_env"; version = "0.1.0"; @@ -4376,7 +4102,6 @@ in vergen = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".vergen."8.0.0-beta.3" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rust-ini."0.18.0" = overridableMkRustCrate (profileName: rec { name = "rust-ini"; version = "0.18.0"; @@ -4390,7 +4115,6 @@ in ordered_multimap = rustPackages."registry+https://github.com/rust-lang/crates.io-index".ordered-multimap."0.4.3" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rustc-hash."1.1.0" = overridableMkRustCrate (profileName: rec { name = "rustc-hash"; version = "1.1.0"; @@ -4401,7 +4125,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".rustc_version."0.4.0" = overridableMkRustCrate (profileName: rec { name = "rustc_version"; version = "0.4.0"; @@ -4411,7 +4134,6 @@ in semver = rustPackages."registry+https://github.com/rust-lang/crates.io-index".semver."1.0.16" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rustls."0.20.8" = overridableMkRustCrate (profileName: rec { name = "rustls"; version = "0.20.8"; @@ -4431,7 +4153,6 @@ in webpki = rustPackages."registry+https://github.com/rust-lang/crates.io-index".webpki."0.22.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rustls-native-certs."0.6.2" = overridableMkRustCrate (profileName: rec { name = "rustls-native-certs"; version = "0.6.2"; @@ -4444,7 +4165,6 @@ in ${ if (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") && hostPlatform.parsed.kernel.name == "darwin" then "security_framework" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".security-framework."2.7.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rustls-pemfile."1.0.2" = overridableMkRustCrate (profileName: rec { name = "rustls-pemfile"; version = "1.0.2"; @@ -4454,14 +4174,12 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "base64" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".base64."0.21.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" = overridableMkRustCrate (profileName: rec { name = "rustversion"; version = "1.0.11"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "5583e89e108996506031660fe09baa5011b9dd0341b89029313006d1fb508d70"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".rusty-fork."0.3.0" = overridableMkRustCrate (profileName: rec { name = "rusty-fork"; version = "0.3.0"; @@ -4478,14 +4196,12 @@ in wait_timeout = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wait-timeout."0.2.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".ryu."1.0.12" = overridableMkRustCrate (profileName: rec { name = "ryu"; version = "1.0.12"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "7b4b9743ed687d4b4bcedf9ff5eaa7398495ae14e61cba0a295704edbc7decde"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".schannel."0.1.21" = overridableMkRustCrate (profileName: rec { name = "schannel"; version = "0.1.21"; @@ -4495,7 +4211,6 @@ in windows_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".scheduled-thread-pool."0.2.6" = overridableMkRustCrate (profileName: rec { name = "scheduled-thread-pool"; version = "0.2.6"; @@ -4505,14 +4220,12 @@ in parking_lot = rustPackages."registry+https://github.com/rust-lang/crates.io-index".parking_lot."0.12.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".scopeguard."1.1.0" = overridableMkRustCrate (profileName: rec { name = "scopeguard"; version = "1.1.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".sct."0.7.0" = overridableMkRustCrate (profileName: rec { name = "sct"; version = "0.7.0"; @@ -4523,7 +4236,6 @@ in untrusted = rustPackages."registry+https://github.com/rust-lang/crates.io-index".untrusted."0.7.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".security-framework."2.7.0" = overridableMkRustCrate (profileName: rec { name = "security-framework"; version = "2.7.0"; @@ -4541,7 +4253,6 @@ in security_framework_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".security-framework-sys."2.6.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".security-framework-sys."2.6.1" = overridableMkRustCrate (profileName: rec { name = "security-framework-sys"; version = "2.6.1"; @@ -4556,7 +4267,6 @@ in libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".semver."1.0.16" = overridableMkRustCrate (profileName: rec { name = "semver"; version = "1.0.16"; @@ -4567,7 +4277,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" = overridableMkRustCrate (profileName: rec { name = "serde"; version = "1.0.152"; @@ -4584,7 +4293,6 @@ in serde_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".serde_derive."1.0.152" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".serde_derive."1.0.152" = overridableMkRustCrate (profileName: rec { name = "serde_derive"; version = "1.0.152"; @@ -4599,7 +4307,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".serde_json."1.0.91" = overridableMkRustCrate (profileName: rec { name = "serde_json"; version = "1.0.91"; @@ -4618,7 +4325,6 @@ in serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".serde_path_to_error."0.1.9" = overridableMkRustCrate (profileName: rec { name = "serde_path_to_error"; version = "0.1.9"; @@ -4628,7 +4334,6 @@ in serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".serde_qs."0.8.5" = overridableMkRustCrate (profileName: rec { name = "serde_qs"; version = "0.8.5"; @@ -4643,7 +4348,6 @@ in thiserror = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".serde_qs."0.11.0" = overridableMkRustCrate (profileName: rec { name = "serde_qs"; version = "0.11.0"; @@ -4658,7 +4362,6 @@ in ${ if rootFeatures' ? "router/default" || rootFeatures' ? "router/sandbox" || rootFeatures' ? "router/stripe" then "thiserror" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".serde_spanned."0.6.1" = overridableMkRustCrate (profileName: rec { name = "serde_spanned"; version = "0.6.1"; @@ -4671,7 +4374,6 @@ in serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".serde_urlencoded."0.7.1" = overridableMkRustCrate (profileName: rec { name = "serde_urlencoded"; version = "0.7.1"; @@ -4684,7 +4386,6 @@ in serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".serial_test."1.0.0" = overridableMkRustCrate (profileName: rec { name = "serial_test"; version = "1.0.0"; @@ -4706,7 +4407,6 @@ in serial_test_derive = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".serial_test_derive."1.0.0" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".serial_test_derive."1.0.0" = overridableMkRustCrate (profileName: rec { name = "serial_test_derive"; version = "1.0.0"; @@ -4721,7 +4421,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".sha-1."0.9.8" = overridableMkRustCrate (profileName: rec { name = "sha-1"; version = "0.9.8"; @@ -4739,7 +4438,6 @@ in opaque_debug = rustPackages."registry+https://github.com/rust-lang/crates.io-index".opaque-debug."0.3.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".sha1."0.10.5" = overridableMkRustCrate (profileName: rec { name = "sha1"; version = "0.10.5"; @@ -4755,7 +4453,6 @@ in digest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".sha2."0.10.6" = overridableMkRustCrate (profileName: rec { name = "sha2"; version = "0.10.6"; @@ -4771,7 +4468,6 @@ in digest = rustPackages."registry+https://github.com/rust-lang/crates.io-index".digest."0.10.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".sharded-slab."0.1.4" = overridableMkRustCrate (profileName: rec { name = "sharded-slab"; version = "0.1.4"; @@ -4781,7 +4477,6 @@ in lazy_static = rustPackages."registry+https://github.com/rust-lang/crates.io-index".lazy_static."1.4.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".signal-hook."0.3.14" = overridableMkRustCrate (profileName: rec { name = "signal-hook"; version = "0.3.14"; @@ -4797,7 +4492,6 @@ in signal_hook_registry = rustPackages."registry+https://github.com/rust-lang/crates.io-index".signal-hook-registry."1.4.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".signal-hook-registry."1.4.0" = overridableMkRustCrate (profileName: rec { name = "signal-hook-registry"; version = "1.4.0"; @@ -4807,7 +4501,6 @@ in libc = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".signal-hook-tokio."0.3.1" = overridableMkRustCrate (profileName: rec { name = "signal-hook-tokio"; version = "0.3.1"; @@ -4824,7 +4517,6 @@ in tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".simd-abstraction."0.7.1" = overridableMkRustCrate (profileName: rec { name = "simd-abstraction"; version = "0.7.1"; @@ -4839,7 +4531,6 @@ in ${ if rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox" then "outref" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".outref."0.1.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".simple_asn1."0.6.2" = overridableMkRustCrate (profileName: rec { name = "simple_asn1"; version = "0.6.2"; @@ -4852,7 +4543,6 @@ in time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".slab."0.4.7" = overridableMkRustCrate (profileName: rec { name = "slab"; version = "0.4.7"; @@ -4866,14 +4556,12 @@ in autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".smallvec."1.10.0" = overridableMkRustCrate (profileName: rec { name = "smallvec"; version = "1.10.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".socket2."0.4.7" = overridableMkRustCrate (profileName: rec { name = "socket2"; version = "0.4.7"; @@ -4887,14 +4575,12 @@ in ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".spin."0.5.2" = overridableMkRustCrate (profileName: rec { name = "spin"; version = "0.5.2"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "6e63cff320ae2c57904679ba7cb63280a3dc4613885beafb148ee7bf9aa9042d"; }; }); - "unknown".storage_models."0.1.0" = overridableMkRustCrate (profileName: rec { name = "storage_models"; version = "0.1.0"; @@ -4923,7 +4609,6 @@ in time = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".strum."0.24.1" = overridableMkRustCrate (profileName: rec { name = "strum"; version = "0.24.1"; @@ -4939,7 +4624,6 @@ in strum_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".strum_macros."0.24.3" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".strum_macros."0.24.3" = overridableMkRustCrate (profileName: rec { name = "strum_macros"; version = "0.24.3"; @@ -4953,7 +4637,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".subtle."2.4.1" = overridableMkRustCrate (profileName: rec { name = "subtle"; version = "2.4.1"; @@ -4965,7 +4648,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".supports-color."1.3.1" = overridableMkRustCrate (profileName: rec { name = "supports-color"; version = "1.3.1"; @@ -4976,7 +4658,6 @@ in is_ci = rustPackages."registry+https://github.com/rust-lang/crates.io-index".is_ci."1.1.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" = overridableMkRustCrate (profileName: rec { name = "syn"; version = "1.0.107"; @@ -5002,14 +4683,12 @@ in unicode_ident = rustPackages."registry+https://github.com/rust-lang/crates.io-index".unicode-ident."1.0.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".sync_wrapper."0.1.1" = overridableMkRustCrate (profileName: rec { name = "sync_wrapper"; version = "0.1.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "20518fe4a4c9acf048008599e464deb21beeae3d3578418951a189c235a7a9a8"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tempfile."3.3.0" = overridableMkRustCrate (profileName: rec { name = "tempfile"; version = "3.3.0"; @@ -5024,7 +4703,6 @@ in ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".termcolor."1.2.0" = overridableMkRustCrate (profileName: rec { name = "termcolor"; version = "1.2.0"; @@ -5034,7 +4712,6 @@ in ${ if hostPlatform.isWindows then "winapi_util" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi-util."0.1.5" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".thiserror."1.0.38" = overridableMkRustCrate (profileName: rec { name = "thiserror"; version = "1.0.38"; @@ -5044,7 +4721,6 @@ in thiserror_impl = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".thiserror-impl."1.0.38" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".thiserror-impl."1.0.38" = overridableMkRustCrate (profileName: rec { name = "thiserror-impl"; version = "1.0.38"; @@ -5056,7 +4732,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".thread_local."1.1.4" = overridableMkRustCrate (profileName: rec { name = "thread_local"; version = "1.1.4"; @@ -5066,7 +4741,6 @@ in once_cell = rustPackages."registry+https://github.com/rust-lang/crates.io-index".once_cell."1.17.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".time."0.3.17" = overridableMkRustCrate (profileName: rec { name = "time"; version = "0.3.17"; @@ -5089,14 +4763,12 @@ in time_macros = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".time-macros."0.2.6" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".time-core."0.1.0" = overridableMkRustCrate (profileName: rec { name = "time-core"; version = "0.1.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "2e153e1f1acaef8acc537e68b44906d2db6436e2b35ac2c6b42640fff91f00fd"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".time-macros."0.2.6" = overridableMkRustCrate (profileName: rec { name = "time-macros"; version = "0.2.6"; @@ -5111,7 +4783,6 @@ in time_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".time-core."0.1.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tinyvec."1.6.0" = overridableMkRustCrate (profileName: rec { name = "tinyvec"; version = "1.6.0"; @@ -5126,14 +4797,12 @@ in tinyvec_macros = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tinyvec_macros."0.1.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tinyvec_macros."0.1.0" = overridableMkRustCrate (profileName: rec { name = "tinyvec_macros"; version = "0.1.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" = overridableMkRustCrate (profileName: rec { name = "tokio"; version = "1.25.0"; @@ -5179,7 +4848,6 @@ in autocfg = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".autocfg."1.1.0" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-io-timeout."1.2.0" = overridableMkRustCrate (profileName: rec { name = "tokio-io-timeout"; version = "1.2.0"; @@ -5190,7 +4858,6 @@ in tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-macros."1.8.2" = overridableMkRustCrate (profileName: rec { name = "tokio-macros"; version = "1.8.2"; @@ -5202,7 +4869,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-native-tls."0.3.0" = overridableMkRustCrate (profileName: rec { name = "tokio-native-tls"; version = "0.3.0"; @@ -5213,7 +4879,6 @@ in tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-rustls."0.23.4" = overridableMkRustCrate (profileName: rec { name = "tokio-rustls"; version = "0.23.4"; @@ -5230,7 +4895,6 @@ in webpki = rustPackages."registry+https://github.com/rust-lang/crates.io-index".webpki."0.22.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-stream."0.1.11" = overridableMkRustCrate (profileName: rec { name = "tokio-stream"; version = "0.1.11"; @@ -5246,7 +4910,6 @@ in tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.6.10" = overridableMkRustCrate (profileName: rec { name = "tokio-util"; version = "0.6.10"; @@ -5265,7 +4928,6 @@ in tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tokio-util."0.7.4" = overridableMkRustCrate (profileName: rec { name = "tokio-util"; version = "0.7.4"; @@ -5286,7 +4948,6 @@ in tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".toml."0.5.11" = overridableMkRustCrate (profileName: rec { name = "toml"; version = "0.5.11"; @@ -5299,7 +4960,6 @@ in serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".toml."0.7.2" = overridableMkRustCrate (profileName: rec { name = "toml"; version = "0.7.2"; @@ -5317,7 +4977,6 @@ in toml_edit = rustPackages."registry+https://github.com/rust-lang/crates.io-index".toml_edit."0.19.3" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".toml_datetime."0.6.1" = overridableMkRustCrate (profileName: rec { name = "toml_datetime"; version = "0.6.1"; @@ -5330,7 +4989,6 @@ in serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".toml_edit."0.19.3" = overridableMkRustCrate (profileName: rec { name = "toml_edit"; version = "0.19.3"; @@ -5348,7 +5006,6 @@ in toml_datetime = rustPackages."registry+https://github.com/rust-lang/crates.io-index".toml_datetime."0.6.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tonic."0.8.3" = overridableMkRustCrate (profileName: rec { name = "tonic"; version = "0.8.3"; @@ -5398,7 +5055,6 @@ in tracing_futures = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-futures."0.2.5" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tower."0.4.13" = overridableMkRustCrate (profileName: rec { name = "tower"; version = "0.4.13"; @@ -5444,7 +5100,6 @@ in tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tower-http."0.3.5" = overridableMkRustCrate (profileName: rec { name = "tower-http"; version = "0.3.5"; @@ -5470,21 +5125,18 @@ in tower_service = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tower-layer."0.3.2" = overridableMkRustCrate (profileName: rec { name = "tower-layer"; version = "0.3.2"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "c20c8dbed6283a09604c3e69b4b7eeb54e298b8a600d4d5ecb5ad39de609f1d0"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tower-service."0.3.2" = overridableMkRustCrate (profileName: rec { name = "tower-service"; version = "0.3.2"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "b6bc1c9ce2b5135ac7f93c72918fc37feb872bdc6a5533a8b85eb4b86bfdae52"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" = overridableMkRustCrate (profileName: rec { name = "tracing"; version = "0.1.36"; @@ -5505,7 +5157,6 @@ in tracing_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-actix-web."0.7.2" = overridableMkRustCrate (profileName: rec { name = "tracing-actix-web"; version = "0.7.2"; @@ -5527,7 +5178,6 @@ in uuid = rustPackages."registry+https://github.com/rust-lang/crates.io-index".uuid."1.2.2" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-appender."0.2.2" = overridableMkRustCrate (profileName: rec { name = "tracing-appender"; version = "0.2.2"; @@ -5539,7 +5189,6 @@ in tracing_subscriber = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-subscriber."0.3.16" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-attributes."0.1.22" = overridableMkRustCrate (profileName: rec { name = "tracing-attributes"; version = "0.1.22"; @@ -5551,7 +5200,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" = overridableMkRustCrate (profileName: rec { name = "tracing-core"; version = "0.1.30"; @@ -5568,7 +5216,6 @@ in ${ if false then "valuable" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".valuable."0.1.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-futures."0.2.5" = overridableMkRustCrate (profileName: rec { name = "tracing-futures"; version = "0.2.5"; @@ -5585,7 +5232,6 @@ in tracing = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing."0.1.36" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-log."0.1.3" = overridableMkRustCrate (profileName: rec { name = "tracing-log"; version = "0.1.3"; @@ -5601,7 +5247,6 @@ in tracing_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-opentelemetry."0.18.0" = overridableMkRustCrate (profileName: rec { name = "tracing-opentelemetry"; version = "0.18.0"; @@ -5621,7 +5266,6 @@ in tracing_subscriber = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-subscriber."0.3.16" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-serde."0.1.3" = overridableMkRustCrate (profileName: rec { name = "tracing-serde"; version = "0.1.3"; @@ -5632,7 +5276,6 @@ in tracing_core = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-core."0.1.30" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".tracing-subscriber."0.3.16" = overridableMkRustCrate (profileName: rec { name = "tracing-subscriber"; version = "0.3.16"; @@ -5676,21 +5319,18 @@ in tracing_serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tracing-serde."0.1.3" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".try-lock."0.2.4" = overridableMkRustCrate (profileName: rec { name = "try-lock"; version = "0.2.4"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".typenum."1.16.0" = overridableMkRustCrate (profileName: rec { name = "typenum"; version = "1.16.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".ucd-trie."0.1.5" = overridableMkRustCrate (profileName: rec { name = "ucd-trie"; version = "0.1.5"; @@ -5700,14 +5340,12 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".unarray."0.1.4" = overridableMkRustCrate (profileName: rec { name = "unarray"; version = "0.1.4"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "eaea85b334db583fe3274d12b4cd1880032beab409c0d774be044d4480ab9a94"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".unicode-bidi."0.3.8" = overridableMkRustCrate (profileName: rec { name = "unicode-bidi"; version = "0.3.8"; @@ -5719,14 +5357,12 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".unicode-ident."1.0.6" = overridableMkRustCrate (profileName: rec { name = "unicode-ident"; version = "1.0.6"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".unicode-normalization."0.1.22" = overridableMkRustCrate (profileName: rec { name = "unicode-normalization"; version = "0.1.22"; @@ -5740,14 +5376,12 @@ in tinyvec = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tinyvec."1.6.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".untrusted."0.7.1" = overridableMkRustCrate (profileName: rec { name = "untrusted"; version = "0.7.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "a156c684c91ea7d62626509bce3cb4e1d9ed5c4d978f7b4352658f96a4c26b4a"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".url."2.3.1" = overridableMkRustCrate (profileName: rec { name = "url"; version = "2.3.1"; @@ -5764,14 +5398,12 @@ in serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".urlencoding."2.1.2" = overridableMkRustCrate (profileName: rec { name = "urlencoding"; version = "2.1.2"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "e8db7427f936968176eaa7cdf81b7f98b980b18495ec28f1b5791ac3bfe3eea9"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".utoipa."3.0.1" = overridableMkRustCrate (profileName: rec { name = "utoipa"; version = "3.0.1"; @@ -5789,7 +5421,6 @@ in utoipa_gen = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".utoipa-gen."3.0.1" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".utoipa-gen."3.0.1" = overridableMkRustCrate (profileName: rec { name = "utoipa-gen"; version = "3.0.1"; @@ -5805,7 +5436,6 @@ in syn = rustPackages."registry+https://github.com/rust-lang/crates.io-index".syn."1.0.107" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".uuid."1.2.2" = overridableMkRustCrate (profileName: rec { name = "uuid"; version = "1.2.2"; @@ -5824,7 +5454,6 @@ in serde = rustPackages."registry+https://github.com/rust-lang/crates.io-index".serde."1.0.152" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".valuable."0.1.0" = overridableMkRustCrate (profileName: rec { name = "valuable"; version = "0.1.0"; @@ -5835,14 +5464,12 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".vcpkg."0.2.15" = overridableMkRustCrate (profileName: rec { name = "vcpkg"; version = "0.2.15"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".vergen."8.0.0-beta.3" = overridableMkRustCrate (profileName: rec { name = "vergen"; version = "8.0.0-beta.3"; @@ -5868,14 +5495,12 @@ in rustversion = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".rustversion."1.0.11" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".version_check."0.9.4" = overridableMkRustCrate (profileName: rec { name = "version_check"; version = "0.9.4"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".wait-timeout."0.2.0" = overridableMkRustCrate (profileName: rec { name = "wait-timeout"; version = "0.2.0"; @@ -5885,14 +5510,12 @@ in ${ if hostPlatform.isUnix then "libc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".libc."0.2.139" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".waker-fn."1.1.0" = overridableMkRustCrate (profileName: rec { name = "waker-fn"; version = "1.1.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "9d5b2c62b4012a3e1eca5a7e077d13b3bf498c4073e33ccd58626607748ceeca"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".want."0.3.0" = overridableMkRustCrate (profileName: rec { name = "want"; version = "0.3.0"; @@ -5903,7 +5526,6 @@ in try_lock = rustPackages."registry+https://github.com/rust-lang/crates.io-index".try-lock."0.2.4" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".wasi."0.9.0+wasi-snapshot-preview1" = overridableMkRustCrate (profileName: rec { name = "wasi"; version = "0.9.0+wasi-snapshot-preview1"; @@ -5914,7 +5536,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".wasi."0.11.0+wasi-snapshot-preview1" = overridableMkRustCrate (profileName: rec { name = "wasi"; version = "0.11.0+wasi-snapshot-preview1"; @@ -5925,7 +5546,6 @@ in [ "std" ] ]; }); - "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen."0.2.83" = overridableMkRustCrate (profileName: rec { name = "wasm-bindgen"; version = "0.2.83"; @@ -5941,7 +5561,6 @@ in wasm_bindgen_macro = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-macro."0.2.83" { profileName = "__noProfile"; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-backend."0.2.83" = overridableMkRustCrate (profileName: rec { name = "wasm-bindgen-backend"; version = "0.2.83"; @@ -5960,7 +5579,6 @@ in wasm_bindgen_shared = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-shared."0.2.83" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-futures."0.4.33" = overridableMkRustCrate (profileName: rec { name = "wasm-bindgen-futures"; version = "0.4.33"; @@ -5973,7 +5591,6 @@ in ${ if builtins.elem "atomics" hostPlatformFeatures then "web_sys" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".web-sys."0.3.60" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-macro."0.2.83" = overridableMkRustCrate (profileName: rec { name = "wasm-bindgen-macro"; version = "0.2.83"; @@ -5987,7 +5604,6 @@ in wasm_bindgen_macro_support = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-macro-support."0.2.83" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-macro-support."0.2.83" = overridableMkRustCrate (profileName: rec { name = "wasm-bindgen-macro-support"; version = "0.2.83"; @@ -6004,14 +5620,12 @@ in wasm_bindgen_shared = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-shared."0.2.83" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen-shared."0.2.83" = overridableMkRustCrate (profileName: rec { name = "wasm-bindgen-shared"; version = "0.2.83"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "1c38c045535d93ec4f0b4defec448e4291638ee608530863b1e2ba115d4fff7f"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".web-sys."0.3.60" = overridableMkRustCrate (profileName: rec { name = "web-sys"; version = "0.3.60"; @@ -6043,7 +5657,6 @@ in wasm_bindgen = rustPackages."registry+https://github.com/rust-lang/crates.io-index".wasm-bindgen."0.2.83" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".webpki."0.22.0" = overridableMkRustCrate (profileName: rec { name = "webpki"; version = "0.22.0"; @@ -6058,7 +5671,6 @@ in untrusted = rustPackages."registry+https://github.com/rust-lang/crates.io-index".untrusted."0.7.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".webpki-roots."0.22.6" = overridableMkRustCrate (profileName: rec { name = "webpki-roots"; version = "0.22.6"; @@ -6068,7 +5680,6 @@ in webpki = rustPackages."registry+https://github.com/rust-lang/crates.io-index".webpki."0.22.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" = overridableMkRustCrate (profileName: rec { name = "winapi"; version = "0.3.9"; @@ -6102,14 +5713,12 @@ in ${ if hostPlatform.config == "x86_64-pc-windows-gnu" then "winapi_x86_64_pc_windows_gnu" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi-x86_64-pc-windows-gnu."0.4.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".winapi-i686-pc-windows-gnu."0.4.0" = overridableMkRustCrate (profileName: rec { name = "winapi-i686-pc-windows-gnu"; version = "0.4.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".winapi-util."0.1.5" = overridableMkRustCrate (profileName: rec { name = "winapi-util"; version = "0.1.5"; @@ -6119,14 +5728,12 @@ in ${ if hostPlatform.isWindows then "winapi" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".winapi-x86_64-pc-windows-gnu."0.4.0" = overridableMkRustCrate (profileName: rec { name = "winapi-x86_64-pc-windows-gnu"; version = "0.4.0"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".windows."0.43.0" = overridableMkRustCrate (profileName: rec { name = "windows"; version = "0.43.0"; @@ -6149,7 +5756,6 @@ in ${ if hostPlatform.config == "x86_64-pc-windows-msvc" || hostPlatform.config == "x86_64-uwp-windows-msvc" then "windows_x86_64_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_msvc."0.42.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".windows-sys."0.42.0" = overridableMkRustCrate (profileName: rec { name = "windows-sys"; version = "0.42.0"; @@ -6188,56 +5794,48 @@ in ${ if hostPlatform.config == "x86_64-pc-windows-msvc" || hostPlatform.config == "x86_64-uwp-windows-msvc" then "windows_x86_64_msvc" else null } = rustPackages."registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_msvc."0.42.1" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_gnullvm."0.42.1" = overridableMkRustCrate (profileName: rec { name = "windows_aarch64_gnullvm"; version = "0.42.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "8c9864e83243fdec7fc9c5444389dcbbfd258f745e7853198f365e3c4968a608"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".windows_aarch64_msvc."0.42.1" = overridableMkRustCrate (profileName: rec { name = "windows_aarch64_msvc"; version = "0.42.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "4c8b1b673ffc16c47a9ff48570a9d85e25d265735c503681332589af6253c6c7"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".windows_i686_gnu."0.42.1" = overridableMkRustCrate (profileName: rec { name = "windows_i686_gnu"; version = "0.42.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "de3887528ad530ba7bdbb1faa8275ec7a1155a45ffa57c37993960277145d640"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".windows_i686_msvc."0.42.1" = overridableMkRustCrate (profileName: rec { name = "windows_i686_msvc"; version = "0.42.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "bf4d1122317eddd6ff351aa852118a2418ad4214e6613a50e0191f7004372605"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnu."0.42.1" = overridableMkRustCrate (profileName: rec { name = "windows_x86_64_gnu"; version = "0.42.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "c1040f221285e17ebccbc2591ffdc2d44ee1f9186324dd3e84e99ac68d699c45"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_gnullvm."0.42.1" = overridableMkRustCrate (profileName: rec { name = "windows_x86_64_gnullvm"; version = "0.42.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "628bfdf232daa22b0d64fdb62b09fcc36bb01f05a3939e20ab73aaf9470d0463"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".windows_x86_64_msvc."0.42.1" = overridableMkRustCrate (profileName: rec { name = "windows_x86_64_msvc"; version = "0.42.1"; registry = "registry+https://github.com/rust-lang/crates.io-index"; src = fetchCratesIo { inherit name version; sha256 = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd"; }; }); - "registry+https://github.com/rust-lang/crates.io-index".winreg."0.10.1" = overridableMkRustCrate (profileName: rec { name = "winreg"; version = "0.10.1"; @@ -6247,7 +5845,6 @@ in winapi = rustPackages."registry+https://github.com/rust-lang/crates.io-index".winapi."0.3.9" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".wiremock."0.5.17" = overridableMkRustCrate (profileName: rec { name = "wiremock"; version = "0.5.17"; @@ -6270,7 +5867,6 @@ in tokio = rustPackages."registry+https://github.com/rust-lang/crates.io-index".tokio."1.25.0" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".xmlparser."0.13.5" = overridableMkRustCrate (profileName: rec { name = "xmlparser"; version = "0.13.5"; @@ -6281,7 +5877,6 @@ in (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "std") ]; }); - "registry+https://github.com/rust-lang/crates.io-index".yaml-rust."0.4.5" = overridableMkRustCrate (profileName: rec { name = "yaml-rust"; version = "0.4.5"; @@ -6291,7 +5886,6 @@ in linked_hash_map = rustPackages."registry+https://github.com/rust-lang/crates.io-index".linked-hash-map."0.5.6" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".zeroize."1.5.7" = overridableMkRustCrate (profileName: rec { name = "zeroize"; version = "1.5.7"; @@ -6302,7 +5896,6 @@ in (lib.optional (rootFeatures' ? "router/aws-config" || rootFeatures' ? "router/aws-sdk-kms" || rootFeatures' ? "router/kms" || rootFeatures' ? "router/sandbox") "default") ]; }); - "registry+https://github.com/rust-lang/crates.io-index".zstd."0.12.2+zstd.1.5.2" = overridableMkRustCrate (profileName: rec { name = "zstd"; version = "0.12.2+zstd.1.5.2"; @@ -6318,7 +5911,6 @@ in zstd_safe = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zstd-safe."6.0.2+zstd.1.5.2" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".zstd-safe."6.0.2+zstd.1.5.2" = overridableMkRustCrate (profileName: rec { name = "zstd-safe"; version = "6.0.2+zstd.1.5.2"; @@ -6335,7 +5927,6 @@ in zstd_sys = rustPackages."registry+https://github.com/rust-lang/crates.io-index".zstd-sys."2.0.5+zstd.1.5.2" { inherit profileName; }; }; }); - "registry+https://github.com/rust-lang/crates.io-index".zstd-sys."2.0.5+zstd.1.5.2" = overridableMkRustCrate (profileName: rec { name = "zstd-sys"; version = "2.0.5+zstd.1.5.2"; @@ -6354,5 +5945,4 @@ in pkg_config = buildRustPackages."registry+https://github.com/rust-lang/crates.io-index".pkg-config."0.3.26" { profileName = "__noProfile"; }; }; }); - } diff --git a/INSTALL_dependencies.sh b/INSTALL_dependencies.sh index e13f2247805..5c488611520 100755 --- a/INSTALL_dependencies.sh +++ b/INSTALL_dependencies.sh @@ -5,7 +5,7 @@ # # Global config -if [[ "${TRACE-0}" == "1" ]]; then +if [[ "${TRACE-0}" == "1" ]]; then set -o xtrace fi @@ -44,8 +44,8 @@ else SUDO="" fi -ver () { - printf "%03d%03d%03d%03d" `echo "$1" | tr '.' ' '`; +ver () { + printf "%03d%03d%03d%03d" `echo "$1" | tr '.' ' '`; } PROGNAME=`basename $0` @@ -59,7 +59,7 @@ err () { } need_cmd () { - if ! command -v $1 > /dev/null + if ! command -v $1 > /dev/null then err "Command \"${1}\" not found. Bailing out" fi @@ -187,7 +187,7 @@ if [[ ! -x "`command -v psql`" ]] || [[ ! -x "`command -v redis-server`" ]] ; th install_dep postgresql install_dep postgresql-contrib # not needed for macos? install_dep postgresql-devel # needed for diesel_cli in some linux distributions - install_dep postgresql-libs # needed for diesel_cli in some linux distributions + install_dep postgresql-libs # needed for diesel_cli in some linux distributions init_start_postgres # installing libpq messes with initdb creating two copies. better to run it better libpq. install_dep libpq-dev || install_dep libpq else diff --git a/config/config.example.toml b/config/config.example.toml index 645908ee8d9..358ff3489fd 100644 --- a/config/config.example.toml +++ b/config/config.example.toml @@ -247,7 +247,7 @@ region = "" # The AWS region used by the KMS SDK for decrypting data. # EmailClient configuration. Only applicable when the `email` feature flag is enabled. [email] from_email = "[email protected]" # Sender email -aws_region = "" # AWS region used by AWS SES +aws_region = "" # AWS region used by AWS SES base_url = "" # Base url used when adding links that should redirect to self [dummy_connector] diff --git a/config/redis.conf b/config/redis.conf index 1aa00660c47..6343bc3070a 100644 --- a/config/redis.conf +++ b/config/redis.conf @@ -909,10 +909,10 @@ replica-priority 100 # commands. For instance ~* allows all the keys. The pattern # is a glob-style pattern like the one of KEYS. # It is possible to specify multiple patterns. -# %R~<pattern> Add key read pattern that specifies which keys can be read +# %R~<pattern> Add key read pattern that specifies which keys can be read # from. # %W~<pattern> Add key write pattern that specifies which keys can be -# written to. +# written to. # allkeys Alias for ~* # resetkeys Flush the list of allowed keys patterns. # &<pattern> Add a glob-style pattern of Pub/Sub channels that can be @@ -939,10 +939,10 @@ replica-priority 100 # -@all. The user returns to the same state it has immediately # after its creation. # (<options>) Create a new selector with the options specified within the -# parentheses and attach it to the user. Each option should be -# space separated. The first character must be ( and the last +# parentheses and attach it to the user. Each option should be +# space separated. The first character must be ( and the last # character must be ). -# clearselectors Remove all of the currently attached selectors. +# clearselectors Remove all of the currently attached selectors. # Note this does not change the "root" user permissions, # which are the permissions directly applied onto the # user (outside the parentheses). @@ -968,7 +968,7 @@ replica-priority 100 # Basically ACL rules are processed left-to-right. # # The following is a list of command categories and their meanings: -# * keyspace - Writing or reading from keys, databases, or their metadata +# * keyspace - Writing or reading from keys, databases, or their metadata # in a type agnostic way. Includes DEL, RESTORE, DUMP, RENAME, EXISTS, DBSIZE, # KEYS, EXPIRE, TTL, FLUSHALL, etc. Commands that may modify the keyspace, # key or metadata will also have `write` category. Commands that only read @@ -1589,8 +1589,8 @@ cluster-config-file nodes-6379.conf # cluster-node-timeout 15000 -# The cluster port is the port that the cluster bus will listen for inbound connections on. When set -# to the default value, 0, it will be bound to the command port + 10000. Setting this value requires +# The cluster port is the port that the cluster bus will listen for inbound connections on. When set +# to the default value, 0, it will be bound to the command port + 10000. Setting this value requires # you to specify the cluster bus port when executing cluster meet. cluster-port 16379 @@ -1725,12 +1725,12 @@ cluster-allow-pubsubshard-when-down yes # PubSub message by default. (client-query-buffer-limit default value is 1gb) # cluster-link-sendbuf-limit 0 - -# Clusters can configure their announced hostname using this config. This is a common use case for + +# Clusters can configure their announced hostname using this config. This is a common use case for # applications that need to use TLS Server Name Indication (SNI) or dealing with DNS based # routing. By default this value is only shown as additional metadata in the CLUSTER SLOTS -# command, but can be changed using 'cluster-preferred-endpoint-type' config. This value is -# communicated along the clusterbus to all nodes, setting it to an empty string will remove +# command, but can be changed using 'cluster-preferred-endpoint-type' config. This value is +# communicated along the clusterbus to all nodes, setting it to an empty string will remove # the hostname and also propagate the removal. # # cluster-announce-hostname "" @@ -1739,13 +1739,13 @@ cluster-link-sendbuf-limit 0 # a user defined hostname, or by declaring they have no endpoint. Which endpoint is # shown as the preferred endpoint is set by using the cluster-preferred-endpoint-type # config with values 'ip', 'hostname', or 'unknown-endpoint'. This value controls how -# the endpoint returned for MOVED/ASKING requests as well as the first field of CLUSTER SLOTS. -# If the preferred endpoint type is set to hostname, but no announced hostname is set, a '?' +# the endpoint returned for MOVED/ASKING requests as well as the first field of CLUSTER SLOTS. +# If the preferred endpoint type is set to hostname, but no announced hostname is set, a '?' # will be returned instead. # # When a cluster advertises itself as having an unknown endpoint, it's indicating that -# the server doesn't know how clients can reach the cluster. This can happen in certain -# networking situations where there are multiple possible routes to the node, and the +# the server doesn't know how clients can reach the cluster. This can happen in certain +# networking situations where there are multiple possible routes to the node, and the # server doesn't know which one the client took. In this case, the server is expecting # the client to reach out on the same endpoint it used for making the last request, but use # the port provided in the response. @@ -2058,7 +2058,7 @@ client-output-buffer-limit pubsub 32mb 8mb 60 # errors or data eviction. To avoid this we can cap the accumulated memory # used by all client connections (all pubsub and normal clients). Once we # reach that limit connections will be dropped by the server freeing up -# memory. The server will attempt to drop the connections using the most +# memory. The server will attempt to drop the connections using the most # memory first. We call this mechanism "client eviction". # # Client eviction is configured using the maxmemory-clients setting as follows: diff --git a/crates/router/src/connector/globalpay/requests.rs b/crates/router/src/connector/globalpay/requests.rs index 2f06c121378..35cf25b9b88 100644 --- a/crates/router/src/connector/globalpay/requests.rs +++ b/crates/router/src/connector/globalpay/requests.rs @@ -351,7 +351,7 @@ pub struct Card { pub struct DigitalWallet { /// Identifies who provides the digital wallet for the Payer. pub provider: Option<DigitalWalletProvider>, - /// A token that represents, or is the payment method, stored with the digital wallet. + /// A token that represents, or is the payment method, stored with the digital wallet. pub payment_token: Option<serde_json::Value>, } diff --git a/docker-compose.yml b/docker-compose.yml index 1d13d558536..42844c486d9 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -14,7 +14,6 @@ networks: services: - promtail: image: grafana/promtail:latest volumes: @@ -92,21 +91,9 @@ services: volumes: - ./:/app - hyperswitch-server-init: - image: rust:1.70 - command: cargo build --bin router - working_dir: /app - networks: - - router_net - volumes: - - ./:/app - - cargo_cache:/cargo_cache - - cargo_build_cache:/cargo_build_cache - environment: - - CARGO_TARGET_DIR=/cargo_build_cache hyperswitch-server: image: rust:1.70 - command: /cargo_build_cache/debug/router -f ./config/docker_compose.toml + command: cargo run -- -f ./config/docker_compose.toml working_dir: /app ports: - "8080:8080" @@ -127,10 +114,6 @@ services: start_period: 20s timeout: 10s - depends_on: - hyperswitch-server-init: - condition: service_completed_successfully - hyperswitch-producer: image: rust:1.70 command: cargo run --bin scheduler -- -f ./config/docker_compose.toml diff --git a/docs/rfcs/000-issuing-template.md b/docs/rfcs/000-issuing-template.md index 12a694e47a1..61c1e77be7f 100644 --- a/docs/rfcs/000-issuing-template.md +++ b/docs/rfcs/000-issuing-template.md @@ -3,10 +3,10 @@ ### I. Objective A clear and concise title for the RFC -### II. Proposal +### II. Proposal A detailed description of the proposed changes, discussion time frame, technical details and potential drawbacks or alternative solutions that were considered -### III. Open Questions +### III. Open Questions Any questions or concerns that are still open for discussion and debate within the community ### IV. Additional Context / Previous Improvements diff --git a/docs/rfcs/guidelines.md b/docs/rfcs/guidelines.md index 1a53e3ff264..4cf3363bdab 100644 --- a/docs/rfcs/guidelines.md +++ b/docs/rfcs/guidelines.md @@ -2,7 +2,7 @@ Hyperswitch welcomes contributions from anyone in the open-source community. Although some contributions can be easily reviewed and implemented through regular GitHub pull requests, larger changes that require design decisions will require more discussion and collaboration within the community. -To facilitate this process, Hyperswitch has adopted the RFC (Request for Comments) process from other successful open-source projects like Rust and React. The RFC process is designed to encourage community-driven change and ensure that everyone has a voice in the decision-making process, including both core and non-core contributors. +To facilitate this process, Hyperswitch has adopted the RFC (Request for Comments) process from other successful open-source projects like Rust and React. The RFC process is designed to encourage community-driven change and ensure that everyone has a voice in the decision-making process, including both core and non-core contributors. Here are the steps involved: 1. Prepare an RFC Proposal @@ -15,7 +15,7 @@ Here are the steps involved: **Prepare an RFC Proposal:** Anyone interested in proposing a change to Hyperswitch should first create an RFC(in the format given below) that outlines the proposed change. This document should describe the problem the proposal is trying to solve, the proposed solution, and any relevant technical details. The document should also include any potential drawbacks or alternative solutions that were considered. -**Submit Proposal:** Once the RFC document is complete, the proposer should submit it to the Hyperswitch community for review. The proposal can be submitted either as a pull request to the RFC Documents folder or as a GitHub Issue. +**Submit Proposal:** Once the RFC document is complete, the proposer should submit it to the Hyperswitch community for review. The proposal can be submitted either as a pull request to the RFC Documents folder or as a GitHub Issue. **Complete Initial Review:** After the proposal is submitted, the Hyperswitch core team would review it and provide feedback. Feedback can include suggestions for improvements, questions about the proposal, or concerns about its potential impact. @@ -33,35 +33,35 @@ This RFC process for Hyperswitch is intended to encourage collaboration and comm ### Issuing an RFC ```text -**Title** +**Title** **Objective** A clear and concise title for the RFC -**Proposal** +**Proposal** A detailed description of the proposed changes, discussion time frame, technical details and potential drawbacks or alternative solutions that were considered -**Open Questions** +**Open Questions** Any questions or concerns that are still open for discussion and debate within the community -**Additional Context / Previous Improvements** +**Additional Context / Previous Improvements** Any relevant external resources or references like slack / discord threads that support the proposal ``` ### Resolving an RFC ```text -**Title** +**Title** The title of the resolved RFC -**Status** +**Status** The final status of the RFC (Accepted / Rejected) -**Resolution** +**Resolution** A description of the final resolution of the RFC, including any modifications or adjustments made during the discussion and review process -**Implementation** +**Implementation** A description of how the resolution will be implemented, including any relevant future scope for the solution -**Acknowledgements** +**Acknowledgements** Any final thoughts or acknowledgements for the community and contributors who participated in the RFC process ``` \ No newline at end of file diff --git a/generate_code_coverage.sh b/generate_code_coverage.sh index 3597ebb2589..7c04da57e9b 100755 --- a/generate_code_coverage.sh +++ b/generate_code_coverage.sh @@ -13,4 +13,4 @@ export LLVM_PROFILE_FILE="$$-%p-%m.profraw" echo "Running 'cargo test' and generating grcov reports.. This may take some time.." -cargo test && grcov . -s . -t html --branch --binary-path ./target/debug && rm -f $$*profraw && echo "starting server on localhost:$SERVER_PORT" && cd html && python3 -m http.server $SERVER_PORT +cargo test && grcov . -s . -t html --branch --binary-path ./target/debug && rm -f $$*profraw && echo "starting server on localhost:$SERVER_PORT" && cd html && python3 -m http.server $SERVER_PORT diff --git a/loadtest/README.md b/loadtest/README.md index 9ea276eae8a..6f768a55c8a 100644 --- a/loadtest/README.md +++ b/loadtest/README.md @@ -1,11 +1,11 @@ ## Performance Benchmarking Setup -The setup uses docker compose to get the required components up and running. It also handles running database migration -and starts [K6 load testing](https://k6.io/docs/) script at the end. The metrics are visible in the console as well as +The setup uses docker compose to get the required components up and running. It also handles running database migration +and starts [K6 load testing](https://k6.io/docs/) script at the end. The metrics are visible in the console as well as through Grafana dashboard. We have added a callback at the end of the script to compare result with existing baseline values. The env variable -`LOADTEST_RUN_NAME` can be used to change the name of the run which will be used to create json, result summary and diff +`LOADTEST_RUN_NAME` can be used to change the name of the run which will be used to create json, result summary and diff benchmark files. The default value is "baseline", and diff will be created by comparing new results against baseline. See 'How to run' section. @@ -15,10 +15,10 @@ See 'How to run' section. `grafana`: data source and dashboard files -`k6`: K6 load testing tool scripts. The `setup.js` contain common functions like creating merchant api key etc. +`k6`: K6 load testing tool scripts. The `setup.js` contain common functions like creating merchant api key etc. Each js files will contain load testing scenario of each APIs. Currently, we have `health.js` and `payment-confirm.js`. -`.env`: It provide default value to docker compose file. Developer can specify which js script they want to run using env +`.env`: It provide default value to docker compose file. Developer can specify which js script they want to run using env variable called `LOADTEST_K6_SCRIPT`. The default script is `health.js`. See 'How to run' section. ### How to run @@ -33,7 +33,7 @@ Run default (`health.js`) script. It will generate baseline result. bash loadtest.sh ``` -The `loadtest.sh` script takes following flags, +The `loadtest.sh` script takes following flags, `-c`: _compare_ with baseline results [without argument] auto assign run name based on current commit number @@ -42,7 +42,7 @@ The `loadtest.sh` script takes following flags, `-s`: _script name_ exists in `k6` directory without the file extension as argument (default: health) -`-a`: run loadtest for _all scripts_ existing in `k6` directory [without argument] +`-a`: run loadtest for _all scripts_ existing in `k6` directory [without argument] For example, to run the baseline for `payment-confirm.js` script. ```bash @@ -64,7 +64,7 @@ Assuming there is baseline files for all the script, following command will comp ```bash bash loadtest.sh -ca ``` -It uses `-c` compare flag and `-a` run loadtest using all the scripts. +It uses `-c` compare flag and `-a` run loadtest using all the scripts. Developer can observe live metrics using [K6 Load Testing Dashboard](http://localhost:3002/d/k6/k6-load-testing-results?orgId=1&refresh=5s&from=now-1m&to=now) in Grafana. The [Tempo datasource](http://localhost:3002/explore?orgId=1&left=%7B%22datasource%22:%22P214B5B846CF3925F%22,%22queries%22:%5B%7B%22refId%22:%22A%22,%22queryType%22:%22nativeSearch%22%7D%5D,%22range%22:%7B%22from%22:%22now-1m%22,%22to%22:%22now%22%7D%7D) @@ -74,6 +74,6 @@ is available to inspect tracing of individual requests. 1. The script will first "down" the already running docker compose to run loadtest on freshly created database. 2. Make sure that the Rust compiler is happy with your changes before you start running a performance test. This will save a lot of your time. -3. If the project image is available locally then `docker compose up` won't take your new changes into account. +3. If the project image is available locally then `docker compose up` won't take your new changes into account. Either first do `docker compose build` or `docker compose up --build k6`. 4. For baseline, make sure you in the right branch and have build the image before running the loadtest script. diff --git a/loadtest/grafana/grafana-dashboard.yaml b/loadtest/grafana/grafana-dashboard.yaml index 0e5b9117ed0..d51fd65a6ea 100644 --- a/loadtest/grafana/grafana-dashboard.yaml +++ b/loadtest/grafana/grafana-dashboard.yaml @@ -1,8 +1,8 @@ apiVersion: 1 providers: - - name: 'default' - org_id: 1 - folder: '' - type: 'file' + - name: 'default' + org_id: 1 + folder: '' + type: 'file' options: path: /var/lib/grafana/dashboards \ No newline at end of file diff --git a/migrations/2022-12-05-090521_single_use_mandate_fields/down.sql b/migrations/2022-12-05-090521_single_use_mandate_fields/down.sql index 177e00e7548..d60116e489b 100644 --- a/migrations/2022-12-05-090521_single_use_mandate_fields/down.sql +++ b/migrations/2022-12-05-090521_single_use_mandate_fields/down.sql @@ -1,4 +1,4 @@ -- This file should undo anything in `up.sql` -ALTER TABLE mandate +ALTER TABLE mandate DROP COLUMN IF EXISTS single_use_amount, DROP COLUMN IF EXISTS single_use_currency; \ No newline at end of file diff --git a/migrations/2022-12-05-090521_single_use_mandate_fields/up.sql b/migrations/2022-12-05-090521_single_use_mandate_fields/up.sql index 393506967fd..6300b98b0d0 100644 --- a/migrations/2022-12-05-090521_single_use_mandate_fields/up.sql +++ b/migrations/2022-12-05-090521_single_use_mandate_fields/up.sql @@ -1,4 +1,4 @@ -- Your SQL goes here -ALTER TABLE mandate +ALTER TABLE mandate ADD IF NOT EXISTS single_use_amount INTEGER DEFAULT NULL, ADD IF NOT EXISTS single_use_currency "Currency" DEFAULT NULL; diff --git a/migrations/2022-12-12-132936_reverse_lookup/up.sql b/migrations/2022-12-12-132936_reverse_lookup/up.sql index b19e34e236a..bb33cc2c4ed 100644 --- a/migrations/2022-12-12-132936_reverse_lookup/up.sql +++ b/migrations/2022-12-12-132936_reverse_lookup/up.sql @@ -1,7 +1,7 @@ CREATE TABLE reverse_lookup ( lookup_id VARCHAR(255) NOT NULL PRIMARY KEY, sk_id VARCHAR(50) NOT NULL, - pk_id VARCHAR(255) NOT NULL, + pk_id VARCHAR(255) NOT NULL, source VARCHAR(30) NOT NULL ); diff --git a/migrations/2023-02-07-070512_change_merchant_connector_id_data_type/down.sql b/migrations/2023-02-07-070512_change_merchant_connector_id_data_type/down.sql index b6e7d998b1a..4b48621ed89 100644 --- a/migrations/2023-02-07-070512_change_merchant_connector_id_data_type/down.sql +++ b/migrations/2023-02-07-070512_change_merchant_connector_id_data_type/down.sql @@ -6,5 +6,5 @@ SET merchant_connector_id = id; ALTER TABLE merchant_connector_account ALTER COLUMN merchant_connector_id TYPE INTEGER USING (trim(merchant_connector_id)::integer); -ALTER TABLE merchant_connector_account +ALTER TABLE merchant_connector_account ALTER COLUMN merchant_connector_id SET DEFAULT nextval('merchant_connector_id_seq'); diff --git a/migrations/2023-03-30-132338_add_start_end_date_for_mandates/down.sql b/migrations/2023-03-30-132338_add_start_end_date_for_mandates/down.sql index 7dfcf9c2d65..d1e4cbad266 100644 --- a/migrations/2023-03-30-132338_add_start_end_date_for_mandates/down.sql +++ b/migrations/2023-03-30-132338_add_start_end_date_for_mandates/down.sql @@ -1,4 +1,4 @@ -ALTER TABLE mandate +ALTER TABLE mandate DROP COLUMN IF EXISTS start_date, DROP COLUMN IF EXISTS end_date, DROP COLUMN IF EXISTS metadata; \ No newline at end of file diff --git a/migrations/2023-03-30-132338_add_start_end_date_for_mandates/up.sql b/migrations/2023-03-30-132338_add_start_end_date_for_mandates/up.sql index 8e57e2b8a15..de9d5e7da15 100644 --- a/migrations/2023-03-30-132338_add_start_end_date_for_mandates/up.sql +++ b/migrations/2023-03-30-132338_add_start_end_date_for_mandates/up.sql @@ -1,4 +1,4 @@ -ALTER TABLE mandate +ALTER TABLE mandate ADD IF NOT EXISTS start_date TIMESTAMP NULL, ADD IF NOT EXISTS end_date TIMESTAMP NULL, ADD COLUMN metadata JSONB DEFAULT NULL; \ No newline at end of file diff --git a/migrations/2023-04-11-084958_pii-migration/down.sql b/migrations/2023-04-11-084958_pii-migration/down.sql index 4c184965b90..646cb9a37ae 100644 --- a/migrations/2023-04-11-084958_pii-migration/down.sql +++ b/migrations/2023-04-11-084958_pii-migration/down.sql @@ -1,6 +1,6 @@ -- This file should undo anything in `up.sql` -ALTER TABLE merchant_connector_account +ALTER TABLE merchant_connector_account ALTER COLUMN connector_account_details TYPE JSON USING convert_from(connector_account_details, 'UTF8')::json; diff --git a/migrations/2023-04-11-084958_pii-migration/up.sql b/migrations/2023-04-11-084958_pii-migration/up.sql index 6b1cdcd3206..39e6ebe6422 100644 --- a/migrations/2023-04-11-084958_pii-migration/up.sql +++ b/migrations/2023-04-11-084958_pii-migration/up.sql @@ -1,5 +1,5 @@ -- Your SQL goes here -ALTER TABLE merchant_connector_account +ALTER TABLE merchant_connector_account ALTER COLUMN connector_account_details TYPE bytea USING convert_to(connector_account_details::text, 'UTF8'); diff --git a/migrations/2023-04-19-072152_merchant_account_add_intent_fulfilment_time/down.sql b/migrations/2023-04-19-072152_merchant_account_add_intent_fulfilment_time/down.sql index bfce5d026a4..f0a9b7642a6 100644 --- a/migrations/2023-04-19-072152_merchant_account_add_intent_fulfilment_time/down.sql +++ b/migrations/2023-04-19-072152_merchant_account_add_intent_fulfilment_time/down.sql @@ -1 +1 @@ -ALTER TABLE merchant_account DROP COLUMN IF EXISTS intent_fulfillment_time; +ALTER TABLE merchant_account DROP COLUMN IF EXISTS intent_fulfillment_time; diff --git a/migrations/2023-04-19-120503_update_customer_connector_customer/up.sql b/migrations/2023-04-19-120503_update_customer_connector_customer/up.sql index cab5c6a076a..a79d2509d8d 100644 --- a/migrations/2023-04-19-120503_update_customer_connector_customer/up.sql +++ b/migrations/2023-04-19-120503_update_customer_connector_customer/up.sql @@ -1,3 +1,3 @@ -- Your SQL goes here -ALTER TABLE customers +ALTER TABLE customers ADD COLUMN connector_customer JSONB; \ No newline at end of file diff --git a/monitoring/docker-compose-ckh.yaml b/monitoring/docker-compose-ckh.yaml index 33512943259..2bbf5b2ec4a 100644 --- a/monitoring/docker-compose-ckh.yaml +++ b/monitoring/docker-compose-ckh.yaml @@ -140,7 +140,7 @@ services: KAFKA_CLUSTERS_0_NAME: local KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka0:29092 KAFKA_CLUSTERS_0_JMXPORT: 9997 - + clickhouse-server: image: clickhouse/clickhouse-server:latest networks: @@ -154,7 +154,7 @@ services: nofile: soft: 262144 hard: 262144 - + hyperswitch-server: image: rust:1.65 command: cargo run -- -f ./config/docker_compose.toml @@ -193,9 +193,9 @@ services: - POSTGRES_USER=db_user - POSTGRES_PASSWORD=db_pass - POSTGRES_DB=hyperswitch_db - + redis-queue: - image: redis:7 + image: redis:7 command: redis-server /usr/local/etc/redis/redis.conf volumes: - ../config/redis.conf:/usr/local/etc/redis/redis.conf diff --git a/openapi/open_api_spec.yaml b/openapi/open_api_spec.yaml index c6057716f57..8b7b4fd2b6d 100644 --- a/openapi/open_api_spec.yaml +++ b/openapi/open_api_spec.yaml @@ -2593,7 +2593,7 @@ components: type: string description: | Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. - If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. + If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. Sequential and only numeric characters are not recommended. maxLength: 30 minLength: 30 @@ -2968,7 +2968,7 @@ components: type: string description: | Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. - If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. + If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. Sequential and only numeric characters are not recommended. maxLength: 30 example: "pay_mbabizu24mvu3mela5njyhpit4" @@ -3439,7 +3439,7 @@ components: type: string description: | Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. - If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. + If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. Sequential and only numeric characters are not recommended. maxLength: 30 minLength: 30 @@ -3509,7 +3509,7 @@ components: type: string description: | Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. - If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. + If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. Sequential and only numeric characters are not recommended. maxLength: 30 example: "pay_mbabizu24mvu3mela5njyhpit4" @@ -3554,7 +3554,7 @@ components: type: string description: | Unique Identifier for the Payment. It is always recommended to provide this ID while creating a payment. - If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. + If the identifiers in not provided in the Payment Request, this filed shall be auto generated and provide in the API response. It is suggested to keep the payment_id length as a maximum of 30 alphanumeric characters irrespective of payment methods and gateways. Sequential and only numeric characters are not recommended. maxLength: 30 minLength: 30 @@ -4596,7 +4596,7 @@ components: securitySchemes: ApiSecretKey: description: > - Unless explicitly stated, all endpoints require authentication using your secret key. + Unless explicitly stated, all endpoints require authentication using your secret key. You may generate your API keys from the Juspay Dashboard. #### Format diff --git a/postman/portman-config.json b/postman/portman-config.json index 2f51c929013..599767fd6f1 100644 --- a/postman/portman-config.json +++ b/postman/portman-config.json @@ -4023,7 +4023,7 @@ ] } - + ] } diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh index d9752d72fd1..d0b4f080459 100755 --- a/scripts/add_connector.sh +++ b/scripts/add_connector.sh @@ -10,7 +10,7 @@ function find_prev_connector() { sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp for i in "${!sorted[@]}"; do if [ "${sorted[$i]}" = "$1" ] && [ $i != "0" ]; then - # find and return the connector name where this new connector should be added next to it + # find and return the connector name where this new connector should be added next to it eval "$2='${sorted[i-1]}'" mv $self.tmp $self rm $self.tmp-e @@ -20,7 +20,7 @@ function find_prev_connector() { mv $self.tmp $self rm $self.tmp-e # if the new connector needs to be added in first place, add it after Aci, sorted order needs to be covered in code review - eval "$2='aci'" + eval "$2='aci'" } pg=$1; base_url=$2; @@ -33,7 +33,7 @@ RED='\033[0;31m' GREEN='\033[0;32m' ORANGE='\033[0;33m' -if [ -z "$pg" ] || [ -z "$base_url" ]; then +if [ -z "$pg" ] || [ -z "$base_url" ]; then echo "$RED Connector name or base_url not present: try $GREEN\"sh add_connector.sh adyen https://test.adyen.com\"" exit fi @@ -48,7 +48,7 @@ prvc='' find_prev_connector $1 prvc prvcc="$(tr '[:lower:]' '[:upper:]' <<< ${prvc:0:1})${prvc:1}" sed -i'' -e "s|pub mod $prvc;|pub mod $prvc;\npub mod ${pg};|" $conn.rs -sed -i'' -e "s/};/${pg}::${pgc},\n};/" $conn.rs +sed -i'' -e "s/};/${pg}::${pgc},\n};/" $conn.rs sed -i'' -e "s|\"$prvc\" \(.*\)|\"$prvc\" \1\n\t\t\t\"${pg}\" => Ok(Box::new(\&connector::${pgc})),|" $src/types/api.rs sed -i'' -e "s/pub $prvc: \(.*\)/pub $prvc: \1\n\tpub ${pg}: ConnectorParams,/" $src/configs/settings.rs sed -i'' -e "s|$prvc.base_url \(.*\)|$prvc.base_url \1\n${pg}.base_url = \"$base_url\"|" config/development.toml config/docker_compose.toml config/config.example.toml loadtest/config/development.toml @@ -59,7 +59,7 @@ sed -i'' -e "s/^default_imp_for_\(.*\)/default_imp_for_\1\n\tconnector::${pgc},/ # remove temporary files created in above step rm $conn.rs-e $src/types/api.rs-e $src/configs/settings.rs-e config/development.toml-e config/docker_compose.toml-e config/config.example.toml-e loadtest/config/development.toml-e crates/api_models/src/enums.rs-e $src/core/payments/flows.rs-e -cd $conn/ +cd $conn/ # generate template files for the connector cargo install cargo-generate @@ -74,7 +74,7 @@ git checkout ${tests}/main.rs ${tests}/connector_auth.rs ${tests}/sample_auth.to # add enum for this connector in test folder sed -i'' -e "s/mod utils;/mod ${pg};\nmod utils;/" ${tests}/main.rs -sed -i'' -e "s/ pub $prvc: \(.*\)/\tpub $prvc: \1\n\tpub ${pg}: Option<HeaderKey>,/; s/auth.toml/sample_auth.toml/" ${tests}/connector_auth.rs +sed -i'' -e "s/ pub $prvc: \(.*\)/\tpub $prvc: \1\n\tpub ${pg}: Option<HeaderKey>,/; s/auth.toml/sample_auth.toml/" ${tests}/connector_auth.rs echo "\n\n[${pg}]\napi_key=\"API Key\"" >> ${tests}/sample_auth.toml # remove temporary files created in above step
fix
fix docker compose local setup (#1372)
228a36deeb02049999e5ad10f3511def6561d3ca
2025-01-09 15:23:39
github-actions
chore(version): 2025.01.09.1
false
diff --git a/CHANGELOG.md b/CHANGELOG.md index a8be15b40fc..68a584ed68d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,16 @@ All notable changes to HyperSwitch will be documented here. - - - +## 2025.01.09.1 + +### Bug Fixes + +- **dummyconnector:** Add tenant id in dummyconnector requests ([#7008](https://github.com/juspay/hyperswitch/pull/7008)) ([`9c983b6`](https://github.com/juspay/hyperswitch/commit/9c983b68bd834e33c5c57d1d050aa5d41cb10f56)) + +**Full Changelog:** [`2025.01.09.0...2025.01.09.1`](https://github.com/juspay/hyperswitch/compare/2025.01.09.0...2025.01.09.1) + +- - - + ## 2025.01.09.0 ### Features
chore
2025.01.09.1
b88d93023159a56987cdbd21983af397d7a13110
2024-08-22 17:24:25
GORAKHNATH YADAV
docs(README): Adding Contributors guide (#5184)
false
diff --git a/README.md b/README.md index f4729db9539..0428ff38694 100644 --- a/README.md +++ b/README.md @@ -9,19 +9,20 @@ The single API to access payment ecosystems across 130+ countries</div> <p align="center"> - <a href="#%EF%B8%8F-quick-start-guide">Quick Start Guide</a> β€’ - <a href="/docs/try_local_system.md">Local Setup Guide</a> β€’ - <a href="#-fast-integration-for-stripe-users">Fast Integration for Stripe Users</a> β€’ - <a href="https://api-reference.hyperswitch.io/introduction"> API Docs </a> β€’ - <a href="#-supported-features">Supported Features</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="#-FAQs">FAQs</a> β€’ - <a href="#-versioning">Versioning</a> β€’ - <a href="#%EF%B8%8F-copyright-and-license">Copyright and License</a> + <a href="#try-a-payment">Try a Payment</a> β€’ + <a href="#for-enterprises">For Enterprises</a> β€’ + <a href="#for-contributors">For Contributors</a> β€’ + <a href="#quick-setup">Quick Setup</a> β€’ + <a href="/docs/try_local_system.md">Local Setup Guide (Hyperswitch App Server)</a> β€’ + <a href="#fast-integration-for-stripe-users">Fast Integration for Stripe Users</a> β€’ + <a href="https://api-reference.hyperswitch.io/introduction"> API Docs </a> + <br> + <a href="#supported-features">Supported Features</a> β€’ + <a href="#community">Community</a> β€’ + <a href="#bugs-and-feature-requests">Bugs and feature requests</a> β€’ + <a href="#versioning">Versioning</a> β€’ + <a href="#FAQs">FAQs</a> β€’ + <a href="#copyright-and-license">Copyright and License</a> </p> <p align="center"> @@ -64,8 +65,38 @@ Using Hyperswitch, you can: <br> <img src="./docs/imgs/hyperswitch-product.png" alt="Hyperswitch-Product" width="50%"/> -<a href="#Quick Start Guide"> - <h2 id="Quick Start Guide">⚑️ Quick Start Guide</h2> +<a href="https://app.hyperswitch.io/"> + <h2 id="try-a-payment">⚑️ Try a Payment</h2> +</a> + +To quickly experience the ease that Hyperswitch provides while handling the payment, you can signup on [hyperswitch-control-center][dashboard-link], and try a payment. + +Congratulations πŸŽ‰ on making your first payment with Hyperswitch. + +<a href="#Get Started with Hyperswitch"> + <h2 id="get-started-with-hyperswitch">Get Started with Hyperswitch</h2> +</a> + +### [For Enterprises][docs-link-for-enterprise] + Hyperswitch helps enterprises in - + - Improving profitability + - Increasing conversion rates + - Lowering payment costs + - Streamlining payment operations + + Hyperswitch has ample features for businesses of all domains and sizes. [**Check out our offerings**][website-link]. + +### [For Contributors][contributing-guidelines] + + Hyperswitch is an open-source project that aims to make digital payments accessible to people across the globe like a basic utility. With the vision of developing Hyperswitch as the **Linux of Payments**, we seek support from developers worldwide. + + Utilise the following resources to quickstart your journey with Hyperswitch - + - [Guide for contributors][contributing-guidelines] + - [Developer Docs][docs-link-for-developers] + - [Learning Resources][learning-resources] + +<a href="#Quick Setup"> + <h2 id="quick-setup">⚑️ Quick Setup</h2> </a> ### One-click deployment on AWS cloud @@ -96,11 +127,16 @@ This will start the app server, web client and control center. Check out the [local setup guide][local-setup-guide] for a more comprehensive setup, which includes the [scheduler and monitoring services][docker-compose-scheduler-monitoring]. +[docs-link-for-enterprise]: https://docs.hyperswitch.io/hyperswitch-cloud/quickstart +[docs-link-for-developers]: https://docs.hyperswitch.io/hyperswitch-open-source/overview +[contributing-guidelines]: docs/CONTRIBUTING.md +[dashboard-link]: https://app.hyperswitch.io/ +[website-link]: https://hyperswitch.io/ +[learning-resources]: https://docs.hyperswitch.io/learn-more/payment-flows [local-setup-guide]: /docs/try_local_system.md [docker-compose-scheduler-monitoring]: /docs/try_local_system.md#run-the-scheduler-and-monitoring-services - <a href="#Fast-Integration-for-Stripe-Users"> - <h2 id="Fast Integration for Stripe Users">πŸ”Œ Fast Integration for Stripe Users</h2> + <h2 id="fast-integration-for-stripe-users">πŸ”Œ Fast Integration for Stripe Users</h2> </a> If you are already using Stripe, integrating with Hyperswitch is fun, fast & easy. @@ -114,14 +150,14 @@ Try the steps below to get a feel for how quick the setup is: [migrate-from-stripe]: https://hyperswitch.io/docs/migrateFromStripe <a href="#Supported-Features"> - <h2 id="Supported Features">βœ… Supported Features</h2> + <h2 id="supported-features">βœ… Supported Features</h2> </a> ### 🌟 Supported Payment Processors and Methods -As of Sept 2023, we support 50+ payment processors and multiple global payment methods. +As of Aug 2024, Hyperswitch supports 50+ payment processors and multiple global payment methods. In addition, we are continuously integrating new processors based on their reach and community requests. -Our target is to support 100+ processors by H2 2023. +Our target is to support 100+ processors by H2 2024. You can find the latest list of payment processors, supported methods, and features [here][supported-connectors-and-features]. [supported-connectors-and-features]: https://hyperswitch.io/pm-list @@ -157,15 +193,6 @@ analytics, and operations end-to-end: You can [try the hosted version in our sandbox][dashboard]. -<a href="#FAQs"> - <h2 id="FAQs">πŸ€” FAQs</h2> -</a> - -Got more questions? -Please refer to our [FAQs page][faqs]. - -[faqs]: https://hyperswitch.io/docs/devSupport - <!-- ## Documentation @@ -178,58 +205,10 @@ Please refer to the following documentation pages: - Router Architecture [Link] --> -<a href="#what's-Included❓"> - <h2 id="what's-Included❓">What's Included❓</h2> -</a> - -Within the repositories, you'll find the following directories and files, -logically grouping common assets and providing both compiled and minified -variations. - -### Repositories - -The current setup contains a single repo, which contains the core payment router -and the various connector integrations under the `src/connector` sub-directory. - <!-- ### Sub-Crates --> -### 🌳 Files Tree Layout - -<!-- FIXME: this table should either be generated by a script or smoke test -should be introduced, checking it agrees with the actual structure --> - -```text -. -β”œβ”€β”€ config : Initial startup config files for the router -β”œβ”€β”€ connector-template : boilerplate code for connectors -β”œβ”€β”€ crates : sub-crates -β”‚ β”œβ”€β”€ api_models : Request/response models for the `router` crate -β”‚ β”œβ”€β”€ cards : Types to handle card masking and validation -β”‚ β”œβ”€β”€ common_enums : Enums shared across the request/response types and database types -β”‚ β”œβ”€β”€ common_utils : Utilities shared across `router` and other crates -β”‚ β”œβ”€β”€ data_models : Represents the data/domain models used by the business/domain layer -β”‚ β”œβ”€β”€ diesel_models : Database models shared across `router` and other crates -β”‚ β”œβ”€β”€ drainer : Application that reads Redis streams and executes queries in database -β”‚ β”œβ”€β”€ external_services : Interactions with external systems like emails, AWS KMS, etc. -β”‚ β”œβ”€β”€ masking : Personal Identifiable Information protection -β”‚ β”œβ”€β”€ redis_interface : A user-friendly interface to Redis -β”‚ β”œβ”€β”€ router : Main crate of the project -β”‚ β”œβ”€β”€ router_derive : Utility macros for the `router` crate -β”‚ β”œβ”€β”€ router_env : Environment of payment router: logger, basic config, its environment awareness -β”‚ β”œβ”€β”€ scheduler : Scheduling and executing deferred tasks like mail scheduling -β”‚ β”œβ”€β”€ storage_impl : Storage backend implementations for data structures & objects -β”‚ └── test_utils : Utilities to run Postman and connector UI tests -β”œβ”€β”€ docs : hand-written documentation -β”œβ”€β”€ loadtest : performance benchmarking setup -β”œβ”€β”€ migrations : diesel DB setup -β”œβ”€β”€ monitoring : Grafana & Loki monitoring related configuration files -β”œβ”€β”€ openapi : automatically generated OpenAPI spec -β”œβ”€β”€ postman : postman scenarios API -└── scripts : automation, testing, and other utility scripts -``` - <a href="#Join-us-in-building-Hyperswitch"> - <h2 id="Join-us-in-building-Hyperswitch">πŸ’ͺ Join us in building Hyperswitch</h2> + <h2 id="join-us-in-building-hyperswitch">πŸ’ͺ Join us in building Hyperswitch</h2> </a> ### 🀝 Our Belief @@ -283,7 +262,7 @@ development. For example, some of the code in core functions (e.g., `payments_core`) is written to be more readable than pure-idiomatic. <a href="#Community"> - <h2 id="Community">πŸ‘₯ Community</h2> + <h2 id="community">πŸ‘₯ Community</h2> </a> Get updates on Hyperswitch development and chat with the community: @@ -315,7 +294,7 @@ Get updates on Hyperswitch development and chat with the community: </div> <a href="#Bugs and feature requests"> - <h2 id="Bugs and feature requests">🐞 Bugs and feature requests</h2> + <h2 id="bugs-and-feature-requests">🐞 Bugs and feature requests</h2> </a> Please read the issue guidelines and search for [existing and closed issues]. @@ -325,13 +304,22 @@ If your problem or idea is not addressed yet, please [open a new issue]. [open a new issue]: https://github.com/juspay/hyperswitch/issues/new/choose <a href="#Versioning"> - <h2 id="Versioning">πŸ”– Versioning</h2> + <h2 id="versioning">πŸ”– Versioning</h2> </a> Check the [CHANGELOG.md](./CHANGELOG.md) file for details. +<a href="#FAQs"> + <h2 id="FAQs">πŸ€” FAQs</h2> +</a> + +Got more questions? +Please refer to our [FAQs page][faqs]. + +[faqs]: https://hyperswitch.io/docs/devSupport + <a href="#Β©Copyright and License"> - <h2 id="Β©Copyright and License">©️ Copyright and License</h2> + <h2 id="copyright-and-license">©️ Copyright and License</h2> </a> This product is licensed under the [Apache 2.0 License](LICENSE). diff --git a/docs/CONTRIBUTING.md b/docs/CONTRIBUTING.md index da4eed2c0b9..feed9b9cb66 100644 --- a/docs/CONTRIBUTING.md +++ b/docs/CONTRIBUTING.md @@ -24,6 +24,9 @@ Please join us! ## Table of Contents - [Code of Conduct](#code-of-conduct) +- [What's Included?](#whats-included) + - [Repositories](#repositories) + - [Files Tree Layout](#files-tree-layout) - [Contributing in Issues](#contributing-in-issues) - [Asking for General Help](#asking-for-general-help) - [Submitting a Bug Report](#submitting-a-bug-report) @@ -55,6 +58,60 @@ This describes the _minimum_ behavior expected from all contributors. [coc]: https://www.rust-lang.org/policies/code-of-conduct +## What's Included❓ + +### Repositories +The current setup contains three different repositories, corresponding to the different Hyperswitch components. + +- [App Server][app-server] - The core payments engine responsible for managing payment flows, payment unification and smart routing. App server is maintained in this repo itself. + +- [Web Client (SDK)][web-client] - An inclusive, consistent and blended payment experience optimized for the best payment conversions. + +- [Control center][control-center] - A dashboard for payment analytics and operations, managing payment processors or payment methods and configuring payment routing rules. + +[app-server]: https://github.com/juspay/hyperswitch +[web-client]: https://github.com/juspay/hyperswitch-web +[control-center]: https://github.com/juspay/hyperswitch-control-center + +### Files Tree Layout + +Within the repositories, you'll find the following directories and files, +logically grouping common assets and providing both compiled and minified +variations. + +<!-- FIXME: this table should either be generated by a script or smoke test +should be introduced, checking it agrees with the actual structure --> + +```text +. +β”œβ”€β”€ config : Initial startup config files for the router +β”œβ”€β”€ connector-template : boilerplate code for connectors +β”œβ”€β”€ crates : sub-crates +β”‚ β”œβ”€β”€ api_models : Request/response models for the `router` crate +β”‚ β”œβ”€β”€ cards : Types to handle card masking and validation +β”‚ β”œβ”€β”€ common_enums : Enums shared across the request/response types and database types +β”‚ β”œβ”€β”€ common_utils : Utilities shared across `router` and other crates +β”‚ β”œβ”€β”€ data_models : Represents the data/domain models used by the business/domain layer +β”‚ β”œβ”€β”€ diesel_models : Database models shared across `router` and other crates +β”‚ β”œβ”€β”€ drainer : Application that reads Redis streams and executes queries in database +β”‚ β”œβ”€β”€ external_services : Interactions with external systems like emails, AWS KMS, etc. +β”‚ β”œβ”€β”€ masking : Personal Identifiable Information protection +β”‚ β”œβ”€β”€ redis_interface : A user-friendly interface to Redis +β”‚ β”œβ”€β”€ router : Main crate of the project +β”‚ β”œβ”€β”€ router_derive : Utility macros for the `router` crate +β”‚ β”œβ”€β”€ router_env : Environment of payment router: logger, basic config, its environment awareness +β”‚ β”œβ”€β”€ scheduler : Scheduling and executing deferred tasks like mail scheduling +β”‚ β”œβ”€β”€ storage_impl : Storage backend implementations for data structures & objects +β”‚ └── test_utils : Utilities to run Postman and connector UI tests +β”œβ”€β”€ docs : hand-written documentation +β”œβ”€β”€ loadtest : performance benchmarking setup +β”œβ”€β”€ migrations : diesel DB setup +β”œβ”€β”€ monitoring : Grafana & Loki monitoring related configuration files +β”œβ”€β”€ openapi : automatically generated OpenAPI spec +β”œβ”€β”€ postman : postman scenarios API +└── scripts : automation, testing, and other utility scripts +``` + ## Contributing in Issues For any issue, there are fundamentally three ways an individual can contribute:
docs
Adding Contributors guide (#5184)
bf674380d5c7e856d0bae75554326aa9017c0201
2023-12-08 13:45:17
harsh-sharma-juspay
fix(analytics): adding api_path to api logs event and to auditlogs api response (#3079)
false
diff --git a/crates/analytics/docs/clickhouse/scripts/api_events_v2.sql b/crates/analytics/docs/clickhouse/scripts/api_events_v2.sql index b41a75fe67e..33f158ce48b 100644 --- a/crates/analytics/docs/clickhouse/scripts/api_events_v2.sql +++ b/crates/analytics/docs/clickhouse/scripts/api_events_v2.sql @@ -20,6 +20,7 @@ CREATE TABLE api_events_v2_queue ( `latency` UInt128, `user_agent` String, `ip_addr` String, + `url_path` String ) ENGINE = Kafka SETTINGS kafka_broker_list = 'kafka0:29092', kafka_topic_list = 'hyperswitch-api-log-events', kafka_group_name = 'hyper-c1', @@ -50,6 +51,7 @@ CREATE TABLE api_events_v2_dist ( `latency` UInt128, `user_agent` String, `ip_addr` String, + `url_path` String, INDEX flowIndex flow_type TYPE bloom_filter GRANULARITY 1, INDEX apiIndex api_flow TYPE bloom_filter GRANULARITY 1, INDEX statusIndex status_code TYPE bloom_filter GRANULARITY 1 @@ -82,7 +84,8 @@ CREATE MATERIALIZED VIEW api_events_v2_mv TO api_events_v2_dist ( `inserted_at` DateTime CODEC(T64, LZ4), `latency` UInt128, `user_agent` String, - `ip_addr` String + `ip_addr` String, + `url_path` String ) AS SELECT merchant_id, @@ -106,7 +109,8 @@ SELECT now() as inserted_at, latency, user_agent, - ip_addr + ip_addr, + url_path FROM api_events_v2_queue where length(_error) = 0; diff --git a/crates/analytics/src/api_event/events.rs b/crates/analytics/src/api_event/events.rs index 73b3fb9cbad..eb9b2d561c5 100644 --- a/crates/analytics/src/api_event/events.rs +++ b/crates/analytics/src/api_event/events.rs @@ -102,4 +102,6 @@ pub struct ApiLogsResult { pub ip_addr: Option<String>, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, + pub http_method: Option<String>, + pub url_path: Option<String>, }
fix
adding api_path to api logs event and to auditlogs api response (#3079)
0f22d707ba16d7e39602af22ba04f2b4237ef856
2022-12-01 14:32:42
Abhishek
feat(router): added request body for stripe capture request which now accepts amount to capture (#51)
false
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs index 1252969c1bf..88d86840abf 100644 --- a/crates/router/src/connector/stripe.rs +++ b/crates/router/src/connector/stripe.rs @@ -70,11 +70,7 @@ impl { fn get_headers( &self, - req: &types::RouterData< - api::PCapture, - types::PaymentsRequestCaptureData, - types::PaymentsResponseData, - >, + req: &types::PaymentsRouterCaptureData, ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> { let mut header = vec![ ( @@ -94,11 +90,7 @@ impl fn get_url( &self, - req: &types::RouterData< - api::PCapture, - types::PaymentsRequestCaptureData, - types::PaymentsResponseData, - >, + req: &types::PaymentsRouterCaptureData, connectors: Connectors, ) -> CustomResult<String, errors::ConnectorError> { let id = req.request.connector_transaction_id.as_str(); @@ -111,13 +103,18 @@ impl )) } + fn get_request_body( + &self, + req: &types::PaymentsRouterCaptureData, + ) -> CustomResult<Option<String>, errors::ConnectorError> { + let stripe_req = utils::Encode::<stripe::CaptureRequest>::convert_and_url_encode(req) + .change_context(errors::ConnectorError::RequestEncodingFailed)?; + Ok(Some(stripe_req)) + } + fn build_request( &self, - req: &types::RouterData< - api::PCapture, - types::PaymentsRequestCaptureData, - types::PaymentsResponseData, - >, + req: &types::PaymentsRouterCaptureData, connectors: Connectors, ) -> CustomResult<Option<services::Request>, errors::ConnectorError> { Ok(Some( @@ -132,11 +129,7 @@ impl fn handle_response( &self, - data: &types::RouterData< - api::PCapture, - types::PaymentsRequestCaptureData, - types::PaymentsResponseData, - >, + data: &types::PaymentsRouterCaptureData, res: Response, ) -> CustomResult<types::PaymentsRouterCaptureData, errors::ConnectorError> where diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs index f4367967d52..9722c31b2a9 100644 --- a/crates/router/src/connector/stripe/transformers.rs +++ b/crates/router/src/connector/stripe/transformers.rs @@ -539,6 +539,22 @@ pub enum CancellationReason { Abandoned, } +/// Represents the capture request body for stripe connector. +#[derive(Debug, Serialize, Clone, Copy)] +pub struct CaptureRequest { + /// If amount_to_capture is None stripe captures the amount in the payment intent. + amount_to_capture: Option<i32>, +} + +impl TryFrom<&types::PaymentsRouterCaptureData> for CaptureRequest { + type Error = error_stack::Report<errors::ParsingError>; + fn try_from(item: &types::PaymentsRouterCaptureData) -> Result<Self, Self::Error> { + Ok(Self { + amount_to_capture: item.request.amount_to_capture, + }) + } +} + // #[cfg(test)] // mod test_stripe_transformers { // use super::*;
feat
added request body for stripe capture request which now accepts amount to capture (#51)
a3e01bb4ae5893f639f3846ccb73adcca6b25ee0
2024-08-05 17:08:29
Hrithikesh
feat(core): accept profile_id in merchant_account, connectors and customers core functions (#5505)
false
diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs index eeb09b1104a..39616e007bc 100644 --- a/crates/router/src/compatibility/stripe/customers.rs +++ b/crates/router/src/compatibility/stripe/customers.rs @@ -85,7 +85,7 @@ pub async fn customer_retrieve( &req, payload, |state, auth, req, _| { - customers::retrieve_customer(state, auth.merchant_account, auth.key_store, req) + customers::retrieve_customer(state, auth.merchant_account, None, auth.key_store, req) }, &auth::HeaderAuth(auth::ApiKeyAuth), api_locking::LockAction::NotApplicable, diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs index 5df24b5c94e..a85cb1f8fae 100644 --- a/crates/router/src/core/admin.rs +++ b/crates/router/src/core/admin.rs @@ -737,6 +737,7 @@ pub async fn list_merchant_account( pub async fn get_merchant_account( state: SessionState, req: api::MerchantId, + _profile_id: Option<String>, ) -> RouterResponse<api::MerchantAccountResponse> { let db = state.store.as_ref(); let key_manager_state = &(&state).into(); @@ -904,6 +905,7 @@ pub async fn update_business_profile_cascade( pub async fn merchant_account_update( state: SessionState, merchant_id: &id_type::MerchantId, + _profile_id: Option<String>, req: api::MerchantAccountUpdate, ) -> RouterResponse<api::MerchantAccountResponse> { let db = state.store.as_ref(); @@ -2759,6 +2761,7 @@ async fn validate_pm_auth( pub async fn retrieve_payment_connector( state: SessionState, merchant_id: id_type::MerchantId, + _profile_id: Option<String>, merchant_connector_id: String, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { let store = state.store.as_ref(); @@ -2807,6 +2810,7 @@ pub async fn retrieve_payment_connector( pub async fn list_payment_connectors( state: SessionState, merchant_id: id_type::MerchantId, + _profile_id_list: Option<Vec<String>>, ) -> RouterResponse<Vec<api_models::admin::MerchantConnectorListResponse>> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); @@ -2847,6 +2851,7 @@ pub async fn list_payment_connectors( pub async fn update_payment_connector( state: SessionState, merchant_id: &id_type::MerchantId, + _profile_id: Option<String>, merchant_connector_id: &str, req: api_models::admin::MerchantConnectorUpdate, ) -> RouterResponse<api_models::admin::MerchantConnectorResponse> { diff --git a/crates/router/src/core/connector_onboarding/paypal.rs b/crates/router/src/core/connector_onboarding/paypal.rs index 176789b4bbb..b285f6d2af1 100644 --- a/crates/router/src/core/connector_onboarding/paypal.rs +++ b/crates/router/src/core/connector_onboarding/paypal.rs @@ -180,7 +180,7 @@ pub async fn update_mca( merchant_id: merchant_id.clone(), }; let mca_response = - admin::update_payment_connector(state.clone(), &merchant_id, &connector_id, request) + admin::update_payment_connector(state.clone(), &merchant_id, None, &connector_id, request) .await?; match mca_response { diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs index a2081abddca..c14b7e1e258 100644 --- a/crates/router/src/core/customers.rs +++ b/crates/router/src/core/customers.rs @@ -366,6 +366,7 @@ impl<'a> MerchantReferenceIdForCustomer<'a> { pub async fn retrieve_customer( state: SessionState, merchant_account: domain::MerchantAccount, + _profile_id: Option<String>, key_store: domain::MerchantKeyStore, req: customers::CustomerId, ) -> errors::CustomerResponse<customers::CustomerResponse> { @@ -399,6 +400,7 @@ pub async fn retrieve_customer( pub async fn list_customers( state: SessionState, merchant_id: id_type::MerchantId, + _profile_id_list: Option<Vec<String>>, key_store: domain::MerchantKeyStore, ) -> errors::CustomerResponse<Vec<customers::CustomerResponse>> { let db = state.store.as_ref(); diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs index e2593ddd231..78d0d8fd79d 100644 --- a/crates/router/src/core/payments.rs +++ b/crates/router/src/core/payments.rs @@ -3045,7 +3045,7 @@ pub async fn get_payment_filters( _profile_id_list: Option<Vec<String>>, ) -> RouterResponse<api::PaymentListFiltersV2> { let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) = - super::admin::list_payment_connectors(state, merchant.get_id().to_owned()).await? + super::admin::list_payment_connectors(state, merchant.get_id().to_owned(), None).await? { data } else { diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs index 5868b062174..9f8fc2e30a9 100644 --- a/crates/router/src/core/refunds.rs +++ b/crates/router/src/core/refunds.rs @@ -990,7 +990,8 @@ pub async fn get_filters_for_refunds( _profile_id_list: Option<Vec<String>>, ) -> RouterResponse<api_models::refunds::RefundListFilters> { let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) = - super::admin::list_payment_connectors(state, merchant_account.get_id().to_owned()).await? + super::admin::list_payment_connectors(state, merchant_account.get_id().to_owned(), None) + .await? { data } else { diff --git a/crates/router/src/core/verify_connector.rs b/crates/router/src/core/verify_connector.rs index 4dce96ec9fc..b6f03c27ab0 100644 --- a/crates/router/src/core/verify_connector.rs +++ b/crates/router/src/core/verify_connector.rs @@ -19,6 +19,7 @@ use crate::{ pub async fn verify_connector_credentials( state: SessionState, req: VerifyConnectorRequest, + _profile_id: Option<String>, ) -> errors::RouterResponse<()> { let boxed_connector = api::ConnectorData::get_connector_by_name( &state.conf.connectors, diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs index 0bebf1e39bb..f66ec94d9f2 100644 --- a/crates/router/src/routes/admin.rs +++ b/crates/router/src/routes/admin.rs @@ -124,7 +124,7 @@ pub async fn retrieve_merchant_account( state, &req, payload, - |state, _, req, _| get_merchant_account(state, req), + |state, _, req, _| get_merchant_account(state, req, None), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -189,7 +189,7 @@ pub async fn update_merchant_account( state, &req, json_payload.into_inner(), - |state, _, req, _| merchant_account_update(state, &merchant_id, req), + |state, _, req, _| merchant_account_update(state, &merchant_id, None, req), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -369,7 +369,7 @@ pub async fn payment_connector_retrieve( &req, payload, |state, _, req, _| { - retrieve_payment_connector(state, req.merchant_id, req.merchant_connector_id) + retrieve_payment_connector(state, req.merchant_id, None, req.merchant_connector_id) }, auth::auth_type( &auth::AdminApiAuth, @@ -415,7 +415,7 @@ pub async fn payment_connector_list( state, &req, merchant_id.to_owned(), - |state, _, merchant_id, _| list_payment_connectors(state, merchant_id), + |state, _, merchant_id, _| list_payment_connectors(state, merchant_id, None), auth::auth_type( &auth::AdminApiAuth, &auth::JWTAuthMerchantFromRoute { @@ -468,7 +468,7 @@ pub async fn payment_connector_update( &req, json_payload.into_inner(), |state, _, req, _| { - update_payment_connector(state, &merchant_id, &merchant_connector_id, req) + update_payment_connector(state, &merchant_id, None, &merchant_connector_id, req) }, auth::auth_type( &auth::AdminApiAuth, diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs index fe9408dc135..182f5cc2373 100644 --- a/crates/router/src/routes/customers.rs +++ b/crates/router/src/routes/customers.rs @@ -63,7 +63,9 @@ pub async fn customers_retrieve( state, &req, payload, - |state, auth, req, _| retrieve_customer(state, auth.merchant_account, auth.key_store, req), + |state, auth, req, _| { + retrieve_customer(state, auth.merchant_account, None, auth.key_store, req) + }, &*auth, api_locking::LockAction::NotApplicable, )) @@ -84,6 +86,7 @@ pub async fn customers_list(state: web::Data<AppState>, req: HttpRequest) -> Htt list_customers( state, auth.merchant_account.get_id().to_owned(), + None, auth.key_store, ) }, diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs index e226f3f07ab..4c5af4acd53 100644 --- a/crates/router/src/routes/payments.rs +++ b/crates/router/src/routes/payments.rs @@ -130,6 +130,7 @@ pub async fn payments_create( state, req_state, auth.merchant_account, + None, auth.key_store, HeaderPayload::default(), req, @@ -422,6 +423,7 @@ pub async fn payments_update( state, req_state, auth.merchant_account, + None, auth.key_store, HeaderPayload::default(), req, @@ -500,6 +502,7 @@ pub async fn payments_confirm( state, req_state, auth.merchant_account, + None, auth.key_store, header_payload.clone(), req, @@ -1176,6 +1179,7 @@ async fn authorize_verify_select<Op>( state: app::SessionState, req_state: ReqState, merchant_account: domain::MerchantAccount, + profile_id: Option<String>, key_store: domain::MerchantKeyStore, header_payload: HeaderPayload, req: api_models::payments::PaymentsRequest, @@ -1211,7 +1215,7 @@ where state, req_state, merchant_account, - None, + profile_id, key_store, operation, req, @@ -1232,7 +1236,7 @@ where state, req_state, merchant_account, - None, + profile_id, key_store, operation, req, diff --git a/crates/router/src/routes/verify_connector.rs b/crates/router/src/routes/verify_connector.rs index c045b3a8e6a..74b115e6200 100644 --- a/crates/router/src/routes/verify_connector.rs +++ b/crates/router/src/routes/verify_connector.rs @@ -20,7 +20,7 @@ pub async fn payment_connector_verify( state, &req, json_payload.into_inner(), - |state, _: (), req, _| verify_connector::verify_connector_credentials(state, req), + |state, _: (), req, _| verify_connector::verify_connector_credentials(state, req, None), &auth::JWTAuth(Permission::MerchantConnectorAccountWrite), api_locking::LockAction::NotApplicable, ))
feat
accept profile_id in merchant_account, connectors and customers core functions (#5505)
1ffabb4063850a49c49bae01d5cf924c2b9d0665
2023-03-10 12:56:37
Sanchith Hegde
chore: address Rust 1.68 clippy lints (#728)
false
diff --git a/crates/router/src/scheduler/utils.rs b/crates/router/src/scheduler/utils.rs index c9faf265c33..866ff0c6c0a 100644 --- a/crates/router/src/scheduler/utils.rs +++ b/crates/router/src/scheduler/utils.rs @@ -345,13 +345,14 @@ where let lock_val = "LOCKED"; let ttl = settings.producer.lock_ttl; - let result = if state + if state .store .acquire_pt_lock(tag, lock_key, lock_val, ttl) .await .change_context(errors::ProcessTrackerError::ERedisError( errors::RedisError::RedisConnectionError.into(), - ))? { + ))? + { let result = callback().await; state .store @@ -361,8 +362,7 @@ where result } else { Ok(()) - }; - result + } } pub(crate) async fn signal_handler(
chore
address Rust 1.68 clippy lints (#728)
21d3071f317e153f9ff83446c29b0f88c4bbd973
2024-11-08 17:28:42
Anurag Thakur
fix(docs): Fix broken pages in API reference (#6507)
false
diff --git a/api-reference/api-reference/api-key/api-key--create.mdx b/api-reference/api-reference/api-key/api-key--create.mdx index 977d4b92851..663ec4e6645 100644 --- a/api-reference/api-reference/api-key/api-key--create.mdx +++ b/api-reference/api-reference/api-key/api-key--create.mdx @@ -1,3 +1,3 @@ --- -openapi: post /api_keys/{merchant_id) +openapi: post /api_keys/{merchant_id} --- \ No newline at end of file diff --git a/api-reference/api-reference/api-key/api-key--revoke.mdx b/api-reference/api-reference/api-key/api-key--revoke.mdx index d95f088533e..62bbf020321 100644 --- a/api-reference/api-reference/api-key/api-key--revoke.mdx +++ b/api-reference/api-reference/api-key/api-key--revoke.mdx @@ -1,3 +1,3 @@ --- -openapi: delete /api_keys/{merchant_id)/{key_id} +openapi: delete /api_keys/{merchant_id}/{key_id} --- \ No newline at end of file diff --git a/api-reference/api-reference/routing/routing--activate-config.mdx b/api-reference/api-reference/routing/routing--activate-config.mdx index 990723a90c7..12e39e519e9 100644 --- a/api-reference/api-reference/routing/routing--activate-config.mdx +++ b/api-reference/api-reference/routing/routing--activate-config.mdx @@ -1,3 +1,3 @@ --- -openapi: post /routing/{algorithm_id}/activate +openapi: post /routing/{routing_algorithm_id}/activate --- \ No newline at end of file diff --git a/api-reference/api-reference/routing/routing--retrieve.mdx b/api-reference/api-reference/routing/routing--retrieve.mdx index f39e44c824c..3c5d31cb2fa 100644 --- a/api-reference/api-reference/routing/routing--retrieve.mdx +++ b/api-reference/api-reference/routing/routing--retrieve.mdx @@ -1,3 +1,3 @@ --- -openapi: get /routing/{algorithm_id} +openapi: get /routing/{routing_algorithm_id} --- \ No newline at end of file
fix
Fix broken pages in API reference (#6507)
d44daaf539021a9cbc33c9391172c38825d74dcd
2023-12-19 17:11:41
Sakil Mostak
fix(connector): [NMI] Fix response deserialization for vault id creation (#3166)
false
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs index b0403d11e3e..5dfcdcf8b99 100644 --- a/crates/router/src/connector/nmi/transformers.rs +++ b/crates/router/src/connector/nmi/transformers.rs @@ -129,7 +129,7 @@ fn get_card_details( pub struct NmiVaultResponse { pub response: Response, pub responsetext: String, - pub customer_vault_id: String, + pub customer_vault_id: Option<String>, pub response_code: String, } @@ -178,7 +178,11 @@ impl )? .to_string(), currency: currency_data, - customer_vault_id: item.response.customer_vault_id, + customer_vault_id: item.response.customer_vault_id.ok_or( + errors::ConnectorError::MissingRequiredField { + field_name: "customer_vault_id", + }, + )?, public_key: auth_type.public_key.ok_or( errors::ConnectorError::InvalidConnectorConfig { config: "public_key",
fix
[NMI] Fix response deserialization for vault id creation (#3166)
0b54b375ef42bc46830871db6d0f7b68e386c3f5
2025-01-08 16:45:27
Pa1NarK
fix(cypress): backup and restore sessions when using user apis (#6978)
false
diff --git a/cypress-tests/cypress/e2e/RoutingTest/00000-PriorityRouting.cy.js b/cypress-tests/cypress/e2e/RoutingTest/00000-PriorityRouting.cy.js index 22e4b3783af..5699712ec2e 100644 --- a/cypress-tests/cypress/e2e/RoutingTest/00000-PriorityRouting.cy.js +++ b/cypress-tests/cypress/e2e/RoutingTest/00000-PriorityRouting.cy.js @@ -7,7 +7,16 @@ let globalState; describe("Priority Based Routing Test", () => { let shouldContinue = true; - context("Login", () => { + beforeEach(() => { + // Restore the session if it exists + cy.session("login", () => { + cy.userLogin(globalState); + cy.terminate2Fa(globalState); + cy.userInfo(globalState); + }); + }); + + context("Get merchant info", () => { before("seed global state", () => { cy.task("getGlobalState").then((state) => { globalState = new State(state); @@ -18,12 +27,6 @@ describe("Priority Based Routing Test", () => { cy.task("setGlobalState", globalState.data); }); - it("User login", () => { - cy.userLogin(globalState); - cy.terminate2Fa(globalState); - cy.userInfo(globalState); - }); - it("merchant retrieve call", () => { cy.merchantRetrieveCall(globalState); }); @@ -39,6 +42,7 @@ describe("Priority Based Routing Test", () => { after("flush global state", () => { cy.task("setGlobalState", globalState.data); }); + it("list-mca-by-mid", () => { cy.ListMcaByMid(globalState); }); @@ -117,6 +121,7 @@ describe("Priority Based Routing Test", () => { after("flush global state", () => { cy.task("setGlobalState", globalState.data); }); + it("list-mca-by-mid", () => { cy.ListMcaByMid(globalState); }); diff --git a/cypress-tests/cypress/e2e/RoutingTest/00001-VolumeBasedRouting.cy.js b/cypress-tests/cypress/e2e/RoutingTest/00001-VolumeBasedRouting.cy.js index 7d7f75e3519..16b640bc03d 100644 --- a/cypress-tests/cypress/e2e/RoutingTest/00001-VolumeBasedRouting.cy.js +++ b/cypress-tests/cypress/e2e/RoutingTest/00001-VolumeBasedRouting.cy.js @@ -5,7 +5,16 @@ import * as utils from "../RoutingUtils/Utils"; let globalState; describe("Volume Based Routing Test", () => { - context("Login", () => { + beforeEach(() => { + // Restore the session if it exists + cy.session("login", () => { + cy.userLogin(globalState); + cy.terminate2Fa(globalState); + cy.userInfo(globalState); + }); + }); + + context("Get merchant info", () => { before("seed global state", () => { cy.task("getGlobalState").then((state) => { globalState = new State(state); @@ -16,12 +25,6 @@ describe("Volume Based Routing Test", () => { cy.task("setGlobalState", globalState.data); }); - it("User login", () => { - cy.userLogin(globalState); - cy.terminate2Fa(globalState); - cy.userInfo(globalState); - }); - it("merchant retrieve call", () => { cy.merchantRetrieveCall(globalState); }); diff --git a/cypress-tests/cypress/e2e/RoutingTest/00002-RuleBasedRouting.cy.js b/cypress-tests/cypress/e2e/RoutingTest/00002-RuleBasedRouting.cy.js index 304668752cd..a1621a530ae 100644 --- a/cypress-tests/cypress/e2e/RoutingTest/00002-RuleBasedRouting.cy.js +++ b/cypress-tests/cypress/e2e/RoutingTest/00002-RuleBasedRouting.cy.js @@ -5,7 +5,16 @@ import * as utils from "../RoutingUtils/Utils"; let globalState; describe("Rule Based Routing Test", () => { - context("Login", () => { + beforeEach(() => { + // Restore the session if it exists + cy.session("login", () => { + cy.userLogin(globalState); + cy.terminate2Fa(globalState); + cy.userInfo(globalState); + }); + }); + + context("Get merchant info", () => { before("seed global state", () => { cy.task("getGlobalState").then((state) => { globalState = new State(state); @@ -16,12 +25,6 @@ describe("Rule Based Routing Test", () => { cy.task("setGlobalState", globalState.data); }); - it("User login", () => { - cy.userLogin(globalState); - cy.terminate2Fa(globalState); - cy.userInfo(globalState); - }); - it("merchant retrieve call", () => { cy.merchantRetrieveCall(globalState); }); diff --git a/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js b/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js index 74c02d7ac9f..94fcaed104d 100644 --- a/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js +++ b/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js @@ -5,7 +5,16 @@ import * as utils from "../RoutingUtils/Utils"; let globalState; describe("Auto Retries & Step Up 3DS", () => { - context("Login", () => { + beforeEach(() => { + // Restore the session if it exists + cy.session("login", () => { + cy.userLogin(globalState); + cy.terminate2Fa(globalState); + cy.userInfo(globalState); + }); + }); + + context("Get merchant info", () => { before("seed global state", () => { cy.task("getGlobalState").then((state) => { globalState = new State(state); @@ -16,12 +25,6 @@ describe("Auto Retries & Step Up 3DS", () => { cy.task("setGlobalState", globalState.data); }); - it("User login", () => { - cy.userLogin(globalState); - cy.terminate2Fa(globalState); - cy.userInfo(globalState); - }); - it("List MCA", () => { cy.ListMcaByMid(globalState); }); diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js index bcbe64512fa..e2e83edaf0c 100644 --- a/cypress-tests/cypress/support/commands.js +++ b/cypress-tests/cypress/support/commands.js @@ -3005,14 +3005,13 @@ Cypress.Commands.add("retrievePayoutCallTest", (globalState) => { // User API calls // Below 3 commands should be called in sequence to login a user Cypress.Commands.add("userLogin", (globalState) => { - // Define the necessary variables and constant - const base_url = globalState.get("baseUrl"); - const query_params = `token_only=true`; - const signin_body = { - email: `${globalState.get("email")}`, - password: `${globalState.get("password")}`, + const baseUrl = globalState.get("baseUrl"); + const queryParams = `token_only=true`; + const signinBody = { + email: globalState.get("email"), + password: globalState.get("password"), }; - const url = `${base_url}/user/v2/signin?${query_params}`; + const url = `${baseUrl}/user/v2/signin?${queryParams}`; cy.request({ method: "POST", @@ -3020,37 +3019,38 @@ Cypress.Commands.add("userLogin", (globalState) => { headers: { "Content-Type": "application/json", }, - body: signin_body, + body: signinBody, failOnStatusCode: false, }).then((response) => { logRequestId(response.headers["x-request-id"]); if (response.status === 200) { if (response.body.token_type === "totp") { - expect(response.body).to.have.property("token").and.to.not.be.empty; + expect(response.body, "totp_token").to.have.property("token").and.to.not + .be.empty; - globalState.set("totpToken", response.body.token); - cy.task("setGlobalState", globalState.data); + const totpToken = response.body.token; + globalState.set("totpToken", totpToken); } } else { throw new Error( - `User login call failed to get totp token with status ${response.status} and message ${response.body.message}` + `User login call failed to get totp token with status: "${response.status}" and message: "${response.body.error.message}"` ); } }); }); Cypress.Commands.add("terminate2Fa", (globalState) => { // Define the necessary variables and constant - const base_url = globalState.get("baseUrl"); - const query_params = `skip_two_factor_auth=true`; - const api_key = globalState.get("totpToken"); - const url = `${base_url}/user/2fa/terminate?${query_params}`; + const baseUrl = globalState.get("baseUrl"); + const queryParams = `skip_two_factor_auth=true`; + const apiKey = globalState.get("totpToken"); + const url = `${baseUrl}/user/2fa/terminate?${queryParams}`; cy.request({ method: "GET", url: url, headers: { - Authorization: `Bearer ${api_key}`, + Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", }, failOnStatusCode: false, @@ -3059,29 +3059,30 @@ Cypress.Commands.add("terminate2Fa", (globalState) => { if (response.status === 200) { if (response.body.token_type === "user_info") { - expect(response.body).to.have.property("token").and.to.not.be.empty; + expect(response.body, "user_info_token").to.have.property("token").and + .to.not.be.empty; - globalState.set("userInfoToken", response.body.token); - cy.task("setGlobalState", globalState.data); + const userInfoToken = response.body.token; + globalState.set("userInfoToken", userInfoToken); } } else { throw new Error( - `2FA terminate call failed with status ${response.status} and message ${response.body.message}` + `2FA terminate call failed with status: "${response.status}" and message: "${response.body.error.message}"` ); } }); }); Cypress.Commands.add("userInfo", (globalState) => { // Define the necessary variables and constant - const base_url = globalState.get("baseUrl"); - const api_key = globalState.get("userInfoToken"); - const url = `${base_url}/user`; + const baseUrl = globalState.get("baseUrl"); + const apiKey = globalState.get("userInfoToken"); + const url = `${baseUrl}/user`; cy.request({ method: "GET", url: url, headers: { - Authorization: `Bearer ${api_key}`, + Authorization: `Bearer ${apiKey}`, "Content-Type": "application/json", }, failOnStatusCode: false, @@ -3089,16 +3090,21 @@ Cypress.Commands.add("userInfo", (globalState) => { logRequestId(response.headers["x-request-id"]); if (response.status === 200) { - expect(response.body).to.have.property("merchant_id").and.to.not.be.empty; - expect(response.body).to.have.property("org_id").and.to.not.be.empty; - expect(response.body).to.have.property("profile_id").and.to.not.be.empty; + expect(response.body, "merchant_id").to.have.property("merchant_id").and + .to.not.be.empty; + expect(response.body, "organization_id").to.have.property("org_id").and.to + .not.be.empty; + expect(response.body, "profile_id").to.have.property("profile_id").and.to + .not.be.empty; globalState.set("merchantId", response.body.merchant_id); globalState.set("organizationId", response.body.org_id); globalState.set("profileId", response.body.profile_id); + + globalState.set("userInfoToken", apiKey); } else { throw new Error( - `User login call failed to fetch user info with status ${response.status} and message ${response.body.message}` + `User login call failed to fetch user info with status: "${response.status}" and message: "${response.body.error.message}"` ); } }); @@ -3146,7 +3152,6 @@ Cypress.Commands.add( headers: { Authorization: `Bearer ${globalState.get("userInfoToken")}`, "Content-Type": "application/json", - Cookie: `${globalState.get("cookie")}`, }, failOnStatusCode: false, body: routingBody, @@ -3169,15 +3174,14 @@ Cypress.Commands.add( Cypress.Commands.add("activateRoutingConfig", (data, globalState) => { const { Response: resData } = data || {}; - const routing_config_id = globalState.get("routingConfigId"); + cy.request({ method: "POST", url: `${globalState.get("baseUrl")}/routing/${routing_config_id}/activate`, headers: { Authorization: `Bearer ${globalState.get("userInfoToken")}`, "Content-Type": "application/json", - Cookie: `${globalState.get("cookie")}`, }, failOnStatusCode: false, }).then((response) => { @@ -3197,15 +3201,14 @@ Cypress.Commands.add("activateRoutingConfig", (data, globalState) => { Cypress.Commands.add("retrieveRoutingConfig", (data, globalState) => { const { Response: resData } = data || {}; - const routing_config_id = globalState.get("routingConfigId"); + cy.request({ method: "GET", url: `${globalState.get("baseUrl")}/routing/${routing_config_id}`, headers: { Authorization: `Bearer ${globalState.get("userInfoToken")}`, "Content-Type": "application/json", - Cookie: `${globalState.get("cookie")}`, }, failOnStatusCode: false, }).then((response) => {
fix
backup and restore sessions when using user apis (#6978)