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
|
|---|---|---|---|---|---|---|---|
6305bb57269fb5f6803edbad58d6e574ad4f6509
|
2024-03-06 05:47:03
|
github-actions
|
chore(postman): update Postman collection files
| false
|
diff --git a/postman/collection-json/nuvei.postman_collection.json b/postman/collection-json/nuvei.postman_collection.json
index 4c6b80a3d5c..6d842c43578 100644
--- a/postman/collection-json/nuvei.postman_collection.json
+++ b/postman/collection-json/nuvei.postman_collection.json
@@ -1,1662 +1,1661 @@
-
{
- "info": {
- "_postman_id": "d329ee53-0de4-4154-b0b1-78708ec6e708",
- "name": "nuvei",
- "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])",
- "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
- "_exporter_id": "19204656"
- },
- "item": [
- {
- "name": "Health check",
- "item": [
- {
- "name": "New Request",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/accounts - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [
- {
- "key": "x-feature",
- "value": "router-custom",
- "type": "text",
- "disabled": true
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/health",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "health"
- ]
- }
- },
- "response": []
- }
- ]
- },
- {
- "name": "Flow Testcases",
- "item": [
- {
- "name": "QuickStart",
- "item": [
- {
- "name": "Merchant Account - Create",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/accounts - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/accounts - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id",
- "if (jsonData?.merchant_id) {",
- " pm.collectionVariables.set(\"merchant_id\", jsonData.merchant_id);",
- " console.log(",
- " \"- use {{merchant_id}} as collection variable for value\",",
- " jsonData.merchant_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{merchant_id}}, as jsonData.merchant_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set api_key as variable for jsonData.api_key",
- "if (jsonData?.api_key) {",
- " pm.collectionVariables.set(\"api_key\", jsonData.api_key);",
- " console.log(",
- " \"- use {{api_key}} as collection variable for value\",",
- " jsonData.api_key,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key",
- "if (jsonData?.publishable_key) {",
- " pm.collectionVariables.set(\"publishable_key\", jsonData.publishable_key);",
- " console.log(",
- " \"- use {{publishable_key}} as collection variable for value\",",
- " jsonData.publishable_key,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.\",",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{admin_api_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"merchant_id\":\"postman_merchant_GHAction_{{$guid}}\",\"locker_id\":\"m0010\",\"merchant_name\":\"NewAge Retailer\",\"primary_business_details\":[{\"country\":\"US\",\"business\":\"default\"}],\"merchant_details\":{\"primary_contact_person\":\"John Test\",\"primary_email\":\"[email protected]\",\"primary_phone\":\"sunt laborum\",\"secondary_contact_person\":\"John Test2\",\"secondary_email\":\"[email protected]\",\"secondary_phone\":\"cillum do dolor id\",\"website\":\"www.example.com\",\"about_business\":\"Online Retail with a wide selection of organic products for North America\",\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"return_url\":\"https://duck.com\",\"webhook_details\":{\"webhook_version\":\"1.0.1\",\"webhook_username\":\"ekart_retail\",\"webhook_password\":\"password_ekart@123\",\"payment_created_enabled\":true,\"payment_succeeded_enabled\":true,\"payment_failed_enabled\":true},\"sub_merchants_enabled\":false,\"metadata\":{\"city\":\"NY\",\"unit\":\"245\"}}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/accounts",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "accounts"
- ]
- },
- "description": "Create a new account for a merchant. The merchant could be a seller or retailer or client who likes to receive and send payments."
- },
- "response": []
- },
- {
- "name": "API Key - Create",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[POST]::/api_keys/:merchant_id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/api_keys/:merchant_id - Content-Type is application/json\",",
- " function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- " },",
- ");",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id",
- "if (jsonData?.key_id) {",
- " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);",
- " console.log(",
- " \"- use {{api_key_id}} as collection variable for value\",",
- " jsonData.key_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set api_key as variable for jsonData.api_key",
- "if (jsonData?.api_key) {",
- " pm.collectionVariables.set(\"api_key\", jsonData.api_key);",
- " console.log(",
- " \"- use {{api_key}} as collection variable for value\",",
- " jsonData.api_key,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.\",",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{admin_api_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- }
- ]
- },
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"name\":\"API Key 1\",\"description\":null,\"expiration\":\"2069-09-23T01:02:03.000Z\"}"
- },
- "url": {
- "raw": "{{baseUrl}}/api_keys/:merchant_id",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "api_keys",
- ":merchant_id"
- ],
- "variable": [
- {
- "key": "merchant_id",
- "value": "{{merchant_id}}"
- }
- ]
- }
- },
- "response": []
- },
- {
- "name": "Payment Connector - Create",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(",
- " \"[POST]::/account/:account_id/connectors - Status code is 2xx\",",
- " function () {",
- " pm.response.to.be.success;",
- " },",
- ");",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(",
- " \"[POST]::/account/:account_id/connectors - Content-Type is application/json\",",
- " function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- " },",
- ");",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id",
- "if (jsonData?.merchant_connector_id) {",
- " pm.collectionVariables.set(",
- " \"merchant_connector_id\",",
- " jsonData.merchant_connector_id,",
- " );",
- " console.log(",
- " \"- use {{merchant_connector_id}} as collection variable for value\",",
- " jsonData.merchant_connector_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.\",",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{admin_api_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"connector_type\":\"payment_processor\",\"connector_name\":\"nuvei\",\"connector_account_details\":{\"auth_type\":\"SignatureKey\",\"key1\":\"{{connector_key1}}\",\"api_key\":\"{{connector_api_key}}\",\"api_secret\":\"{{connector_api_secret}}\"},\"test_mode\":true,\"disabled\":false,\"payment_methods_enabled\":[{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}]}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/account/:account_id/connectors",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "account",
- ":account_id",
- "connectors"
- ],
- "variable": [
- {
- "key": "account_id",
- "value": "{{merchant_id}}",
- "description": "(Required) The unique identifier for the merchant account"
- }
- ]
- },
- "description": "Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialised services like Fraud / Accounting etc."
- },
- "response": []
- },
- {
- "name": "Payments - Create",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(1000, 100000));",
- "",
- "// Set the environment variable 'amount' with the value from the response",
- "pm.environment.set(\"amount\", pm.response.json().amount);",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(1000, 100000));",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Retrieve",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
- " console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/payments/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{payment_id}}",
- "description": "(Required) unique refund id"
- }
- ]
- },
- "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
- },
- "response": []
- },
- {
- "name": "Refunds - Create",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Get the value of 'amount' from the environment",
- "const amount = pm.environment.get(\"amount\");",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
- " console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"amount\": {{amount}},\n \"reason\": \"Customer returned product\",\n \"refund_type\": \"instant\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/refunds",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "refunds"
- ]
- },
- "description": "To create a refund against an already processed payment"
- },
- "response": []
- },
- {
- "name": "Refunds - Retrieve",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Validate status 2xx",
- "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
- "if (jsonData?.refund_id) {",
- " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
- " console.log(",
- " \"- use {{refund_id}} as collection variable for value\",",
- " jsonData.refund_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
- " );",
- "}",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "GET",
- "header": [
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "url": {
- "raw": "{{baseUrl}}/refunds/:id?force_sync=true",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "refunds",
- ":id"
- ],
- "query": [
- {
- "key": "force_sync",
- "value": "true"
- }
- ],
- "variable": [
- {
- "key": "id",
- "value": "{{refund_id}}",
- "description": "(Required) unique refund id"
- }
- ]
- },
- "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
- },
- "response": []
- }
- ]
- },
- {
- "name": "Variation Cases",
- "item": [
- {
- "name": "Scenario1- Create Payment with Invalid card",
- "item": [
- {
- "name": "Payments - Create(Expired Card)",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "",
- "// Response body should have \"error_message: Expired Card\"",
- "pm.test(\"[POST]::/payments - Content check if 'error_message : Expired Card' exists\", function () {",
- " pm.expect(jsonData.error_message).to.eql(\"Expired Card\");",
- "});",
- "",
- "",
- "",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000247422310226\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Create(Invalid CVV)",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "",
- "// Response body should have \"error_message: Invalid CVV\"",
- "pm.test(\"[POST]::/payments - Content check if 'error_message : Invalid CVV' exists\", function () {",
- " pm.expect(jsonData.error_message).to.eql(\"Invalid CVV\");",
- "});",
- "",
- "",
- "",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"5333583123003909\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Create(Lost Card)",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "",
- "// Response body should have \"error_message: Lost/Stolen\"",
- "pm.test(\"[POST]::/payments - Content check if 'error_message : Lost/Stolen' exists\", function () {",
- " pm.expect(jsonData.error_message).to.eql(\"Lost/Stolen\");",
- "});",
- "",
- "",
- "",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"5333452804487502\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- }
- ]
- },
- {
- "name": "Scenario1- Payment Decline scenario",
- "item": [
- {
- "name": "Payments - Create(Decline)",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "",
- "// Response body should have \"error_message: Decline\"",
- "pm.test(\"[POST]::/payments - Content check if 'error_message : Decline' exists\", function () {",
- " pm.expect(jsonData.error_message).to.eql(\"Decline\");",
- "});",
- "",
- "",
- "",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"375521501910816\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Create(Do Not Honor)",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "",
- "// Response body should have \"error_message: Do Not Honor\"",
- "pm.test(\"[POST]::/payments - Content check if 'error_message : Do Not Honor' exists\", function () {",
- " pm.expect(jsonData.error_message).to.eql(\"Do Not Honor\");",
- "});",
- "",
- "",
- "",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"5333463046218753\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- },
- {
- "name": "Payments - Create(Insufficient Funds)",
- "event": [
- {
- "listen": "test",
- "script": {
- "exec": [
- "pm.environment.set(\"random_number\", _.random(100, 100000));",
- "",
- "// Validate status 2xx",
- "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
- " pm.response.to.be.success;",
- "});",
- "",
- "",
- "// Validate if response header has matching content-type",
- "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
- " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
- " \"application/json\",",
- " );",
- "});",
- "",
- "// Validate if response has JSON Body",
- "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
- " pm.response.to.have.jsonBody();",
- "});",
- "",
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(",
- " \"- use {{payment_id}} as collection variable for value\",",
- " jsonData.payment_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
- "if (jsonData?.mandate_id) {",
- " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
- " console.log(",
- " \"- use {{mandate_id}} as collection variable for value\",",
- " jsonData.mandate_id,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
- " );",
- "}",
- "",
- "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
- "if (jsonData?.client_secret) {",
- " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
- " console.log(",
- " \"- use {{client_secret}} as collection variable for value\",",
- " jsonData.client_secret,",
- " );",
- "} else {",
- " console.log(",
- " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
- " );",
- "}",
- "",
- "",
- "// Response body should have \"error_message: Insufficient Funds\"",
- "pm.test(\"[POST]::/payments - Content check if 'error_message : Insufficient Funds' exists\", function () {",
- " pm.expect(jsonData.error_message).to.eql(\"Insufficient Funds\");",
- "});",
- "",
- "",
- "",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "request": {
- "method": "POST",
- "header": [
- {
- "key": "Content-Type",
- "value": "application/json"
- },
- {
- "key": "Accept",
- "value": "application/json"
- }
- ],
- "body": {
- "mode": "raw",
- "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"5333475572200849\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}",
- "options": {
- "raw": {
- "language": "json"
- }
- }
- },
- "url": {
- "raw": "{{baseUrl}}/payments",
- "host": [
- "{{baseUrl}}"
- ],
- "path": [
- "payments"
- ]
- },
- "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
- },
- "response": []
- }
- ]
- }
- ]
- }
- ]
- }
- ],
- "auth": {
- "type": "apikey",
- "apikey": [
- {
- "key": "value",
- "value": "{{api_key}}",
- "type": "string"
- },
- {
- "key": "key",
- "value": "api-key",
- "type": "string"
- },
- {
- "key": "in",
- "value": "header",
- "type": "string"
- }
- ]
- },
- "event": [
- {
- "listen": "prerequest",
- "script": {
- "exec": [
- ""
- ],
- "type": "text/javascript"
- }
- },
- {
- "listen": "test",
- "script": {
- "exec": [
- "// Set response object as internal variable",
- "let jsonData = {};",
- "try {",
- " jsonData = pm.response.json();",
- "} catch (e) {}",
- "",
- "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
- "if (jsonData?.payment_id) {",
- " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
- " console.log(\"[LOG]::payment_id - \" + jsonData.payment_id);",
- "}",
- "",
- "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
- ""
- ],
- "type": "text/javascript"
- }
- }
- ],
- "variable": [
- {
- "key": "baseUrl",
- "value": "https://sandbox.hyperswitch.io",
- "type": "string"
- },
- {
- "key": "admin_api_key",
- "value": "",
- "type": "string"
- },
- {
- "key": "api_key",
- "value": "",
- "type": "string"
- },
- {
- "key": "merchant_id",
- "value": ""
- },
- {
- "key": "payment_id",
- "value": ""
- },
- {
- "key": "customer_id",
- "value": ""
- },
- {
- "key": "mandate_id",
- "value": ""
- },
- {
- "key": "payment_method_id",
- "value": ""
- },
- {
- "key": "refund_id",
- "value": ""
- },
- {
- "key": "merchant_connector_id",
- "value": ""
- },
- {
- "key": "client_secret",
- "value": "",
- "type": "string"
- },
- {
- "key": "connector_api_key",
- "value": "",
- "type": "string"
- },
- {
- "key": "publishable_key",
- "value": "",
- "type": "string"
- },
- {
- "key": "api_key_id",
- "value": "",
- "type": "string"
- },
- {
- "key": "payment_token",
- "value": ""
- },
- {
- "key": "gateway_merchant_id",
- "value": "",
- "type": "string"
- },
- {
- "key": "certificate",
- "value": "",
- "type": "string"
- },
- {
- "key": "certificate_keys",
- "value": "",
- "type": "string"
- }
- ]
-}
\ No newline at end of file
+ "event": [
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(\"[LOG]::payment_id - \" + jsonData.payment_id);",
+ "}",
+ "",
+ "console.log(\"[LOG]::x-request-id - \" + pm.response.headers.get(\"x-request-id\"));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "item": [
+ {
+ "name": "Health check",
+ "item": [
+ {
+ "name": "New Request",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/accounts - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text",
+ "disabled": true
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/health",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "health"
+ ]
+ }
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Flow Testcases",
+ "item": [
+ {
+ "name": "QuickStart",
+ "item": [
+ {
+ "name": "Merchant Account - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/accounts - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/accounts - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id",
+ "if (jsonData?.merchant_id) {",
+ " pm.collectionVariables.set(\"merchant_id\", jsonData.merchant_id);",
+ " console.log(",
+ " \"- use {{merchant_id}} as collection variable for value\",",
+ " jsonData.merchant_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{merchant_id}}, as jsonData.merchant_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set api_key as variable for jsonData.api_key",
+ "if (jsonData?.api_key) {",
+ " pm.collectionVariables.set(\"api_key\", jsonData.api_key);",
+ " console.log(",
+ " \"- use {{api_key}} as collection variable for value\",",
+ " jsonData.api_key,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key",
+ "if (jsonData?.publishable_key) {",
+ " pm.collectionVariables.set(\"publishable_key\", jsonData.publishable_key);",
+ " console.log(",
+ " \"- use {{publishable_key}} as collection variable for value\",",
+ " jsonData.publishable_key,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{admin_api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"merchant_id\":\"postman_merchant_GHAction_{{$guid}}\",\"locker_id\":\"m0010\",\"merchant_name\":\"NewAge Retailer\",\"primary_business_details\":[{\"country\":\"US\",\"business\":\"default\"}],\"merchant_details\":{\"primary_contact_person\":\"John Test\",\"primary_email\":\"[email protected]\",\"primary_phone\":\"sunt laborum\",\"secondary_contact_person\":\"John Test2\",\"secondary_email\":\"[email protected]\",\"secondary_phone\":\"cillum do dolor id\",\"website\":\"www.example.com\",\"about_business\":\"Online Retail with a wide selection of organic products for North America\",\"address\":{\"line1\":\"1467\",\"line2\":\"Harrison Street\",\"line3\":\"Harrison Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"US\"}},\"return_url\":\"https://duck.com\",\"webhook_details\":{\"webhook_version\":\"1.0.1\",\"webhook_username\":\"ekart_retail\",\"webhook_password\":\"password_ekart@123\",\"payment_created_enabled\":true,\"payment_succeeded_enabled\":true,\"payment_failed_enabled\":true},\"sub_merchants_enabled\":false,\"metadata\":{\"city\":\"NY\",\"unit\":\"245\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/accounts",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "accounts"
+ ]
+ },
+ "description": "Create a new account for a merchant. The merchant could be a seller or retailer or client who likes to receive and send payments."
+ },
+ "response": []
+ },
+ {
+ "name": "API Key - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/api_keys/:merchant_id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/api_keys/:merchant_id - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id",
+ "if (jsonData?.key_id) {",
+ " pm.collectionVariables.set(\"api_key_id\", jsonData.key_id);",
+ " console.log(",
+ " \"- use {{api_key_id}} as collection variable for value\",",
+ " jsonData.key_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set api_key as variable for jsonData.api_key",
+ "if (jsonData?.api_key) {",
+ " pm.collectionVariables.set(\"api_key\", jsonData.api_key);",
+ " console.log(",
+ " \"- use {{api_key}} as collection variable for value\",",
+ " jsonData.api_key,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{admin_api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\"name\":\"API Key 1\",\"description\":null,\"expiration\":\"2069-09-23T01:02:03.000Z\"}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/api_keys/:merchant_id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api_keys",
+ ":merchant_id"
+ ],
+ "variable": [
+ {
+ "key": "merchant_id",
+ "value": "{{merchant_id}}"
+ }
+ ]
+ }
+ },
+ "response": []
+ },
+ {
+ "name": "Payment Connector - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(",
+ " \"[POST]::/account/:account_id/connectors - Status code is 2xx\",",
+ " function () {",
+ " pm.response.to.be.success;",
+ " },",
+ ");",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(",
+ " \"[POST]::/account/:account_id/connectors - Content-Type is application/json\",",
+ " function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ " },",
+ ");",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id",
+ "if (jsonData?.merchant_connector_id) {",
+ " pm.collectionVariables.set(",
+ " \"merchant_connector_id\",",
+ " jsonData.merchant_connector_id,",
+ " );",
+ " console.log(",
+ " \"- use {{merchant_connector_id}} as collection variable for value\",",
+ " jsonData.merchant_connector_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{admin_api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"connector_type\":\"payment_processor\",\"connector_name\":\"nuvei\",\"connector_account_details\":{\"auth_type\":\"SignatureKey\",\"key1\":\"{{connector_key1}}\",\"api_key\":\"{{connector_api_key}}\",\"api_secret\":\"{{connector_api_secret}}\"},\"test_mode\":true,\"disabled\":false,\"payment_methods_enabled\":[{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"credit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]},{\"payment_method\":\"card\",\"payment_method_types\":[{\"payment_method_type\":\"debit\",\"minimum_amount\":1,\"maximum_amount\":68607706,\"recurring_enabled\":true,\"installment_payment_enabled\":true}]}]}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/account/:account_id/connectors",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "account",
+ ":account_id",
+ "connectors"
+ ],
+ "variable": [
+ {
+ "key": "account_id",
+ "value": "{{merchant_id}}",
+ "description": "(Required) The unique identifier for the merchant account"
+ }
+ ]
+ },
+ "description": "Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialised services like Fraud / Accounting etc."
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ "",
+ "// Set the environment variable 'amount' with the value from the response",
+ "pm.environment.set(\"amount\", pm.response.json().amount);",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ },
+ {
+ "listen": "prerequest",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(1000, 100000));",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"4111111111111111\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique refund id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Create",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Get the value of 'amount' from the environment",
+ "const amount = pm.environment.get(\"amount\");",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/refunds - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/refunds - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw": "{\n \"payment_id\": \"{{payment_id}}\",\n \"amount\": {{amount}},\n \"reason\": \"Customer returned product\",\n \"refund_type\": \"instant\",\n \"metadata\": {\n \"udf1\": \"value1\",\n \"new_customer\": \"true\",\n \"login_date\": \"2019-09-10T10:11:12Z\"\n }\n}",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/refunds",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds"
+ ]
+ },
+ "description": "To create a refund against an already processed payment"
+ },
+ "response": []
+ },
+ {
+ "name": "Refunds - Retrieve",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "// Validate status 2xx",
+ "pm.test(\"[GET]::/refunds/:id - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[GET]::/refunds/:id - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set refund_id as variable for jsonData.payment_id",
+ "if (jsonData?.refund_id) {",
+ " pm.collectionVariables.set(\"refund_id\", jsonData.refund_id);",
+ " console.log(",
+ " \"- use {{refund_id}} as collection variable for value\",",
+ " jsonData.refund_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{refund_id}}, as jsonData.refund_id is undefined.\",",
+ " );",
+ "}",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/refunds/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "refunds",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{refund_id}}",
+ "description": "(Required) unique refund id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Refund. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Variation Cases",
+ "item": [
+ {
+ "name": "Scenario1- Create Payment with Invalid card",
+ "item": [
+ {
+ "name": "Payments - Create(Expired Card)",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(100, 100000));",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// Response body should have \"error_message: Expired Card\"",
+ "pm.test(\"[POST]::/payments - Content check if 'error_message : Expired Card' exists\", function () {",
+ " pm.expect(jsonData.error_message).to.eql(\"Expired Card\");",
+ "});",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"4000247422310226\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Create(Invalid CVV)",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(100, 100000));",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// Response body should have \"error_message: Invalid CVV\"",
+ "pm.test(\"[POST]::/payments - Content check if 'error_message : Invalid CVV' exists\", function () {",
+ " pm.expect(jsonData.error_message).to.eql(\"Invalid CVV\");",
+ "});",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"5333583123003909\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Create(Lost Card)",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(100, 100000));",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// Response body should have \"error_message: Lost/Stolen\"",
+ "pm.test(\"[POST]::/payments - Content check if 'error_message : Lost/Stolen' exists\", function () {",
+ " pm.expect(jsonData.error_message).to.eql(\"Lost/Stolen\");",
+ "});",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"5333452804487502\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ }
+ ]
+ },
+ {
+ "name": "Scenario1- Payment Decline scenario",
+ "item": [
+ {
+ "name": "Payments - Create(Decline)",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(100, 100000));",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// Response body should have \"error_message: Decline\"",
+ "pm.test(\"[POST]::/payments - Content check if 'error_message : Decline' exists\", function () {",
+ " pm.expect(jsonData.error_message).to.eql(\"Decline\");",
+ "});",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"375521501910816\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Create(Do Not Honor)",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(100, 100000));",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// Response body should have \"error_message: Do Not Honor\"",
+ "pm.test(\"[POST]::/payments - Content check if 'error_message : Do Not Honor' exists\", function () {",
+ " pm.expect(jsonData.error_message).to.eql(\"Do Not Honor\");",
+ "});",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"5333463046218753\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ },
+ {
+ "name": "Payments - Create(Insufficient Funds)",
+ "event": [
+ {
+ "listen": "test",
+ "script": {
+ "exec": [
+ "pm.environment.set(\"random_number\", _.random(100, 100000));",
+ "",
+ "// Validate status 2xx",
+ "pm.test(\"[POST]::/payments - Status code is 2xx\", function () {",
+ " pm.response.to.be.success;",
+ "});",
+ "",
+ "",
+ "// Validate if response header has matching content-type",
+ "pm.test(\"[POST]::/payments - Content-Type is application/json\", function () {",
+ " pm.expect(pm.response.headers.get(\"Content-Type\")).to.include(",
+ " \"application/json\",",
+ " );",
+ "});",
+ "",
+ "// Validate if response has JSON Body",
+ "pm.test(\"[POST]::/payments - Response has JSON Body\", function () {",
+ " pm.response.to.have.jsonBody();",
+ "});",
+ "",
+ "// Set response object as internal variable",
+ "let jsonData = {};",
+ "try {",
+ " jsonData = pm.response.json();",
+ "} catch (e) {}",
+ "",
+ "// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id",
+ "if (jsonData?.payment_id) {",
+ " pm.collectionVariables.set(\"payment_id\", jsonData.payment_id);",
+ " console.log(",
+ " \"- use {{payment_id}} as collection variable for value\",",
+ " jsonData.payment_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id",
+ "if (jsonData?.mandate_id) {",
+ " pm.collectionVariables.set(\"mandate_id\", jsonData.mandate_id);",
+ " console.log(",
+ " \"- use {{mandate_id}} as collection variable for value\",",
+ " jsonData.mandate_id,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.\",",
+ " );",
+ "}",
+ "",
+ "// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret",
+ "if (jsonData?.client_secret) {",
+ " pm.collectionVariables.set(\"client_secret\", jsonData.client_secret);",
+ " console.log(",
+ " \"- use {{client_secret}} as collection variable for value\",",
+ " jsonData.client_secret,",
+ " );",
+ "} else {",
+ " console.log(",
+ " \"INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.\",",
+ " );",
+ "}",
+ "",
+ "",
+ "// Response body should have \"error_message: Insufficient Funds\"",
+ "pm.test(\"[POST]::/payments - Content check if 'error_message : Insufficient Funds' exists\", function () {",
+ " pm.expect(jsonData.error_message).to.eql(\"Insufficient Funds\");",
+ "});",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "type": "text/javascript"
+ }
+ }
+ ],
+ "request": {
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw": "{\"amount\":100,\"currency\":\"USD\",\"confirm\":true,\"capture_method\":\"automatic\",\"connector\":[\"nuvei\"],\"customer_id\":\"futurebilling\",\"email\":\"[email protected]\",\"name\":\"John Doe\",\"phone\":\"999999999\",\"phone_country_code\":\"+65\",\"description\":\"testing\",\"authentication_type\":\"no_three_ds\",\"return_url\":\"https://google.com\",\"payment_method\":\"card\",\"payment_method_type\":\"credit\",\"setup_future_usage\":\"off_session\",\"payment_method_data\":{\"card\":{\"card_number\":\"5333475572200849\",\"card_exp_month\":\"12\",\"card_exp_year\":\"2030\",\"card_holder_name\":\"joseph Doe\",\"card_cvc\":\"123\"}},\"mandate_data\":{\"customer_acceptance\":{\"acceptance_type\":\"offline\",\"accepted_at\":\"1963-05-03T04:07:52.723Z\",\"online\":{\"ip_address\":\"127.0.0.1\",\"user_agent\":\"amet irure esse\"}},\"mandate_type\":{\"multi_use\":{\"amount\":100,\"currency\":\"USD\",\"metadata\":{\"frequency\":\"1\"},\"end_date\":\"2025-05-03T04:07:52.723Z\"}}},\"billing\":{\"address\":{\"line1\":\"1467\",\"line2\":\"jkjj Street\",\"line3\":\"no 1111 Street\",\"city\":\"San Fransico\",\"state\":\"California\",\"zip\":\"94122\",\"country\":\"JP\",\"first_name\":\"joseph\",\"last_name\":\"Doe\"}},\"statement_descriptor_name\":\"joseph\",\"metadata\":{\"udf1\":\"value1\",\"new_customer\":\"true\",\"login_date\":\"2019-09-10T10:11:12Z\"},\"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\"}}"
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+ },
+ "response": []
+ }
+ ]
+ }
+ ]
+ }
+ ]
+ }
+ ],
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "info": {
+ "_postman_id": "d329ee53-0de4-4154-b0b1-78708ec6e708",
+ "name": "nuvei",
+ "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])",
+ "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
+ "_exporter_id": "19204656"
+ },
+ "variable": [
+ {
+ "key": "baseUrl",
+ "value": "https://sandbox.hyperswitch.io",
+ "type": "string"
+ },
+ {
+ "key": "admin_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "merchant_id",
+ "value": ""
+ },
+ {
+ "key": "payment_id",
+ "value": ""
+ },
+ {
+ "key": "customer_id",
+ "value": ""
+ },
+ {
+ "key": "mandate_id",
+ "value": ""
+ },
+ {
+ "key": "payment_method_id",
+ "value": ""
+ },
+ {
+ "key": "refund_id",
+ "value": ""
+ },
+ {
+ "key": "merchant_connector_id",
+ "value": ""
+ },
+ {
+ "key": "client_secret",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "publishable_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "payment_token",
+ "value": ""
+ },
+ {
+ "key": "gateway_merchant_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate_keys",
+ "value": "",
+ "type": "string"
+ }
+ ]
+}
|
chore
|
update Postman collection files
|
b0346e08f45c6739da22f370b657a41cf2a9cd67
|
2024-08-12 13:12:54
|
Kashif
|
feat(payout_link): add localisation support for payout link's templates (#5552)
| false
|
diff --git a/.typos.toml b/.typos.toml
index 82fb84ecf38..2f68e039cde 100644
--- a/.typos.toml
+++ b/.typos.toml
@@ -62,5 +62,20 @@ extend-exclude = [
"openapi/open_api_spec.yaml", # no longer updated
"crates/router/src/utils/user/blocker_emails.txt", # this file contains various email domains
"CHANGELOG.md", # This file contains all the commits
+ "crates/router/locales/ar.yml", # locales
+ "crates/router/locales/ca.yml", # locales
+ "crates/router/locales/de.yml", # locales
+ "crates/router/locales/es.yml", # locales
+ "crates/router/locales/fr-BE.yml", # locales
+ "crates/router/locales/fr.yml", # locales
+ "crates/router/locales/he.yml", # locales
+ "crates/router/locales/it.yml", # locales
+ "crates/router/locales/ja.yml", # locales
+ "crates/router/locales/nl.yml", # locales
+ "crates/router/locales/pl.yml", # locales
+ "crates/router/locales/pt.yml", # locales
+ "crates/router/locales/ru.yml", # locales
+ "crates/router/locales/sv.yml", # locales
+ "crates/router/locales/zh.yml", # locales
"crates/router/src/core/payment_link/locale.js" # this file contains converision of static strings in various languages
]
diff --git a/Cargo.lock b/Cargo.lock
index 9d37e75077f..c0ff88bfcf6 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1488,6 +1488,12 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "23ce669cd6c8588f79e15cf450314f9638f967fc5770ff1c7c1deb0925ea7cfa"
+[[package]]
+name = "base62"
+version = "2.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f879ef8fc74665ed7f0e6127cb106315888fc2744f68e14b74f83edbb2a08992"
+
[[package]]
name = "base64"
version = "0.13.1"
@@ -4321,6 +4327,12 @@ dependencies = [
"vcpkg",
]
+[[package]]
+name = "libyml"
+version = "0.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64804cc6a5042d4f05379909ba25b503ec04e2c082151d62122d5dcaa274b961"
+
[[package]]
name = "libz-sys"
version = "1.1.16"
@@ -4383,9 +4395,9 @@ dependencies = [
[[package]]
name = "log"
-version = "0.4.21"
+version = "0.4.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c"
+checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
[[package]]
name = "lru-cache"
@@ -4474,9 +4486,9 @@ checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"
[[package]]
name = "memchr"
-version = "2.7.2"
+version = "2.7.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6c8640c5d730cb13ebd907d8d04b52f55ac9a2eec55b440c8892f40d56c76c1d"
+checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
[[package]]
name = "memoffset"
@@ -4693,6 +4705,15 @@ dependencies = [
"minimal-lexical",
]
+[[package]]
+name = "normpath"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ec60c60a693226186f5d6edf073232bfb6464ed97eb22cf3b01c1e8198fd97f5"
+dependencies = [
+ "windows-sys 0.48.0",
+]
+
[[package]]
name = "nu-ansi-term"
version = "0.46.0"
@@ -5323,7 +5344,7 @@ version = "0.11.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90fcb95eef784c2ac79119d1dd819e162b5da872ce6f3c3abe1e8ca1c082f72b"
dependencies = [
- "siphasher",
+ "siphasher 0.3.11",
]
[[package]]
@@ -6126,6 +6147,7 @@ dependencies = [
"router_derive",
"router_env",
"roxmltree",
+ "rust-i18n",
"rust_decimal",
"rustc-hash",
"rustls 0.22.4",
@@ -6229,6 +6251,57 @@ dependencies = [
"zeroize",
]
+[[package]]
+name = "rust-i18n"
+version = "3.1.1"
+source = "git+https://github.com/kashif-m/rust-i18n?rev=f2d8096aaaff7a87a847c35a5394c269f75e077a#f2d8096aaaff7a87a847c35a5394c269f75e077a"
+dependencies = [
+ "globwalk",
+ "once_cell",
+ "regex",
+ "rust-i18n-macro",
+ "rust-i18n-support",
+ "smallvec 1.13.2",
+]
+
+[[package]]
+name = "rust-i18n-macro"
+version = "3.1.1"
+source = "git+https://github.com/kashif-m/rust-i18n?rev=f2d8096aaaff7a87a847c35a5394c269f75e077a#f2d8096aaaff7a87a847c35a5394c269f75e077a"
+dependencies = [
+ "glob",
+ "once_cell",
+ "proc-macro2",
+ "quote",
+ "rust-i18n-support",
+ "serde",
+ "serde_json",
+ "serde_yml",
+ "syn 2.0.57",
+]
+
+[[package]]
+name = "rust-i18n-support"
+version = "3.1.1"
+source = "git+https://github.com/kashif-m/rust-i18n?rev=f2d8096aaaff7a87a847c35a5394c269f75e077a#f2d8096aaaff7a87a847c35a5394c269f75e077a"
+dependencies = [
+ "arc-swap",
+ "base62",
+ "globwalk",
+ "itertools 0.11.0",
+ "lazy_static",
+ "normpath",
+ "once_cell",
+ "proc-macro2",
+ "regex",
+ "serde",
+ "serde_json",
+ "serde_yml",
+ "siphasher 1.0.1",
+ "toml 0.7.8",
+ "triomphe",
+]
+
[[package]]
name = "rust-ini"
version = "0.19.0"
@@ -6465,9 +6538,9 @@ dependencies = [
[[package]]
name = "ryu"
-version = "1.0.17"
+version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1"
+checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"
[[package]]
name = "same-file"
@@ -6607,9 +6680,9 @@ checksum = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3"
[[package]]
name = "serde"
-version = "1.0.197"
+version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2"
+checksum = "e33aedb1a7135da52b7c21791455563facbbcc43d0f0f66165b42c21b3dfb150"
dependencies = [
"serde_derive",
]
@@ -6648,9 +6721,9 @@ dependencies = [
[[package]]
name = "serde_derive"
-version = "1.0.197"
+version = "1.0.205"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b"
+checksum = "692d6f5ac90220161d6774db30c662202721e64aed9058d2c394f451261420c1"
dependencies = [
"proc-macro2",
"quote",
@@ -6659,12 +6732,13 @@ dependencies = [
[[package]]
name = "serde_json"
-version = "1.0.115"
+version = "1.0.122"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "12dc5c46daa8e9fdf4f5e71b6cf9a53f2487da0e86e55808e2d35539666497dd"
+checksum = "784b6203951c57ff748476b126ccb5e8e2959a5c19e5c617ab1956be3dbc68da"
dependencies = [
"indexmap 2.3.0",
"itoa",
+ "memchr",
"ryu",
"serde",
]
@@ -6761,6 +6835,23 @@ dependencies = [
"syn 2.0.57",
]
+[[package]]
+name = "serde_yml"
+version = "0.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "48e76bab63c3fd98d27c17f9cbce177f64a91f5e69ac04cafe04e1bb25d1dc3c"
+dependencies = [
+ "indexmap 2.3.0",
+ "itoa",
+ "libyml",
+ "log",
+ "memchr",
+ "ryu",
+ "serde",
+ "serde_json",
+ "tempfile",
+]
+
[[package]]
name = "serial_test"
version = "3.0.0"
@@ -6888,6 +6979,12 @@ version = "0.3.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d"
+[[package]]
+name = "siphasher"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "56199f7ddabf13fe5074ce809e7d3f42b42ae711800501b5b16ea82ad029c39d"
+
[[package]]
name = "skeptic"
version = "0.13.7"
@@ -7189,6 +7286,12 @@ dependencies = [
"urlencoding",
]
+[[package]]
+name = "stable_deref_trait"
+version = "1.2.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"
+
[[package]]
name = "storage_impl"
version = "0.1.0"
@@ -8231,6 +8334,11 @@ name = "triomphe"
version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "859eb650cfee7434994602c3a68b25d77ad9e68c8a6cd491616ef86661382eb3"
+dependencies = [
+ "arc-swap",
+ "serde",
+ "stable_deref_trait",
+]
[[package]]
name = "try-lock"
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index 3333fb6f546..b90b34cdff7 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -764,6 +764,7 @@ pub struct PayoutLinkDetails {
pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>,
pub amount: common_utils::types::StringMajorUnit,
pub currency: common_enums::Currency,
+ pub locale: String,
}
#[derive(Clone, Debug, serde::Serialize)]
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index a331a05f6fa..fd155963968 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -127,3 +127,6 @@ pub const WILDCARD_DOMAIN_REGEX: &str = r"^((\*|https?)?://)?((\*\.|[A-Za-z0-9][
/// Maximum allowed length for MerchantName
pub const MAX_ALLOWED_MERCHANT_NAME_LENGTH: usize = 64;
+
+/// Default locale
+pub const DEFAULT_LOCALE: &str = "en";
diff --git a/crates/hyperswitch_domain_models/src/api.rs b/crates/hyperswitch_domain_models/src/api.rs
index b013d2b7902..d8a4f998e1b 100644
--- a/crates/hyperswitch_domain_models/src/api.rs
+++ b/crates/hyperswitch_domain_models/src/api.rs
@@ -64,6 +64,7 @@ pub struct PaymentLinkStatusData {
pub struct GenericLinks {
pub allowed_domains: HashSet<String>,
pub data: GenericLinksData,
+ pub locale: String,
}
#[derive(Debug, Eq, PartialEq)]
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 3e0470cc08d..8040979abbf 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -97,6 +97,7 @@ reqwest = { version = "0.11.27", features = ["json", "native-tls", "__rustls", "
ring = "0.17.8"
roxmltree = "0.19.0"
rust_decimal = { version = "1.35.0", features = ["serde-with-float", "serde-with-str"] }
+rust-i18n = { git = "https://github.com/kashif-m/rust-i18n", rev = "f2d8096aaaff7a87a847c35a5394c269f75e077a" }
rustc-hash = "1.1.0"
rustls = "0.22"
rustls-pemfile = "2"
@@ -161,7 +162,6 @@ time = { version = "0.3.35", features = ["macros"] }
tokio = "1.37.0"
wiremock = "0.6.0"
-
# First party dev-dependencies
test_utils = { version = "0.1.0", path = "../test_utils" }
diff --git a/crates/router/locales/ar.yml b/crates/router/locales/ar.yml
new file mode 100644
index 00000000000..5cc89daa47a
--- /dev/null
+++ b/crates/router/locales/ar.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "لا يُسمح لك بمشاهدة هذا المحتوى"
+ title: "روابط الدفع"
+ status:
+ title: "حالة الدفع"
+ info:
+ ref_id: "معرف المرجع"
+ error_code: "رمز الخطأ"
+ error_message: "رسالة الخطأ"
+ message:
+ failed: "فشل في معالجة الدفع الخاص بك. يرجى التحقق مع مزود الخدمة للحصول على مزيد من التفاصيل."
+ processing: "يجب معالجة الدفع الخاص بك خلال 2-3 أيام عمل."
+ success: "تم تنفيذ الدفع إلى طريقة الدفع المختارة."
+ redirection_text:
+ redirecting: "جارٍ إعادة التوجيه..."
+ redirecting_in: "إعادة التوجيه خلال"
+ seconds: "ثوانٍ..."
+ text:
+ failed: "فشل الدفع"
+ processing: "الدفع قيد المعالجة"
+ success: "الدفع ناجح"
+
+time:
+ am: "صباحا"
+ pm: "مساء"
+
+months:
+ january: "يناير"
+ february: "فبراير"
+ march: "مارس"
+ april: "أبريل"
+ may: "مايو"
+ june: "يونيو"
+ july: "يوليو"
+ august: "أغسطس"
+ september: "سبتمبر"
+ october: "أكتوبر"
+ november: "نوفمبر"
+ december: "ديسمبر"
diff --git a/crates/router/locales/ca.yml b/crates/router/locales/ca.yml
new file mode 100644
index 00000000000..df4d40bb204
--- /dev/null
+++ b/crates/router/locales/ca.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "No tens permís per veure aquest contingut"
+ title: "Enllaços de Pagament"
+ status:
+ title: "Estat del Pagament"
+ info:
+ ref_id: "ID de Referència"
+ error_code: "Codi d'Error"
+ error_message: "Missatge d'Error"
+ message:
+ failed: "No s'ha pogut processar el teu pagament. Si us plau, comprova-ho amb el teu proveïdor per obtenir més detalls."
+ processing: "El teu pagament hauria de ser processat en 2-3 dies hàbils."
+ success: "El teu pagament s'ha realitzat al mètode de pagament seleccionat."
+ redirection_text:
+ redirecting: "Redirigint..."
+ redirecting_in: "Redirigint en"
+ seconds: "segons..."
+ text:
+ failed: "Falla en el Pagament"
+ processing: "Pagament en Procés"
+ success: "Pagament Exitos"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Gener"
+ february: "Febrer"
+ march: "Març"
+ april: "Abril"
+ may: "Maig"
+ june: "Juny"
+ july: "Juliol"
+ august: "Agost"
+ september: "Setembre"
+ october: "Octubre"
+ november: "Novembre"
+ december: "Desembre"
diff --git a/crates/router/locales/de.yml b/crates/router/locales/de.yml
new file mode 100644
index 00000000000..4a2ac4c4ea4
--- /dev/null
+++ b/crates/router/locales/de.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Sie dürfen diesen Inhalt nicht anzeigen"
+ title: "Auszahlungslinks"
+ status:
+ title: "Auszahlungsstatus"
+ info:
+ ref_id: "Referenz-ID"
+ error_code: "Fehlercode"
+ error_message: "Fehlermeldung"
+ message:
+ failed: "Die Auszahlung konnte nicht verarbeitet werden. Bitte überprüfen Sie weitere Details bei Ihrem Anbieter."
+ processing: "Ihre Auszahlung sollte innerhalb von 2-3 Werktagen verarbeitet werden."
+ success: "Ihre Auszahlung wurde auf die ausgewählte Zahlungsmethode vorgenommen."
+ redirection_text:
+ redirecting: "Weiterleitung..."
+ redirecting_in: "Weiterleitung in"
+ seconds: "Sekunden..."
+ text:
+ failed: "Auszahlung fehlgeschlagen"
+ processing: "Auszahlung wird bearbeitet"
+ success: "Auszahlung erfolgreich"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Januar"
+ february: "Februar"
+ march: "März"
+ april: "April"
+ may: "Mai"
+ june: "Juni"
+ july: "Juli"
+ august: "August"
+ september: "September"
+ october: "Oktober"
+ november: "November"
+ december: "Dezember"
diff --git a/crates/router/locales/en-GB.yml b/crates/router/locales/en-GB.yml
new file mode 100644
index 00000000000..5d0cdca4f0a
--- /dev/null
+++ b/crates/router/locales/en-GB.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "You are not allowed to view this content"
+ title: "Payout Links"
+ status:
+ title: "Payout Status"
+ info:
+ ref_id: "Ref Id"
+ error_code: "Error Code"
+ error_message: "Error Message"
+ message:
+ failed: "Failed to process your payout. Please check with your provider for more details."
+ processing: "Your payout should be processed within 2-3 business days."
+ success: "Your payout was made to selected payment method."
+ redirection_text:
+ redirecting: "Redirecting..."
+ redirecting_in: "Redirecting in"
+ seconds: "seconds..."
+ text:
+ failed: "Payout Failed"
+ processing: "Payout Processing"
+ success: "Payout Successful"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "January"
+ february: "February"
+ march: "March"
+ april: "April"
+ may: "May"
+ june: "June"
+ july: "July"
+ august: "August"
+ september: "September"
+ october: "October"
+ november: "November"
+ december: "December"
diff --git a/crates/router/locales/en.yml b/crates/router/locales/en.yml
new file mode 100644
index 00000000000..c85be7ccf46
--- /dev/null
+++ b/crates/router/locales/en.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "You are not allowed to view this content"
+ title: "Payout Links"
+ status:
+ title: "Payout Status"
+ info:
+ ref_id: "Ref Id"
+ error_code: "Error Code"
+ error_message: "Error Message"
+ message:
+ failed: "Failed to process your payout. Please check with your provider for more details."
+ processing: "Your payout should be processed within 2-3 business days."
+ success: "Your payout was made to selected payment method."
+ redirection_text:
+ redirecting: "Redirecting ..."
+ redirecting_in: "Redirecting in"
+ seconds: "seconds ..."
+ text:
+ failed: "Payout Failed"
+ processing: "Payout Processing"
+ success: "Payout Successful"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "January"
+ february: "February"
+ march: "March"
+ april: "April"
+ may: "May"
+ june: "June"
+ july: "July"
+ august: "August"
+ september: "September"
+ october: "October"
+ november: "November"
+ december: "December"
\ No newline at end of file
diff --git a/crates/router/locales/es.yml b/crates/router/locales/es.yml
new file mode 100644
index 00000000000..ebe296d067b
--- /dev/null
+++ b/crates/router/locales/es.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "No tienes permiso para ver este contenido"
+ title: "Enlaces de Pago"
+ status:
+ title: "Estado del Pago"
+ info:
+ ref_id: "ID de Referencia"
+ error_code: "Código de Error"
+ error_message: "Mensaje de Error"
+ message:
+ failed: "No se pudo procesar tu pago. Consulta con tu proveedor para más detalles."
+ processing: "Tu pago debería ser procesado en 2-3 días hábiles."
+ success: "Tu pago se realizó al método de pago seleccionado."
+ redirection_text:
+ redirecting: "Redirigiendo..."
+ redirecting_in: "Redirigiendo en"
+ seconds: "segundos..."
+ text:
+ failed: "Fallo en el Pago"
+ processing: "Pago en Proceso"
+ success: "Pago Exitoso"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Enero"
+ february: "Febrero"
+ march: "Marzo"
+ april: "Abril"
+ may: "Mayo"
+ june: "Junio"
+ july: "Julio"
+ august: "Agosto"
+ september: "Septiembre"
+ october: "Octubre"
+ november: "Noviembre"
+ december: "Diciembre"
diff --git a/crates/router/locales/fr-BE.yml b/crates/router/locales/fr-BE.yml
new file mode 100644
index 00000000000..5f5116ea92d
--- /dev/null
+++ b/crates/router/locales/fr-BE.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Vous n'êtes pas autorisé à voir ce contenu"
+ title: "Liens de paiement"
+ status:
+ title: "Statut du paiement"
+ info:
+ ref_id: "ID de référence"
+ error_code: "Code d'erreur"
+ error_message: "Message d'erreur"
+ message:
+ failed: "Échec du traitement de votre paiement. Veuillez vérifier auprès de votre fournisseur pour plus de détails."
+ processing: "Votre paiement devrait être traité dans les 2 à 3 jours ouvrables."
+ success: "Votre paiement a été effectué sur le mode de paiement sélectionné."
+ redirection_text:
+ redirecting: "Redirection..."
+ redirecting_in: "Redirection dans"
+ seconds: "secondes..."
+ text:
+ failed: "Échec du paiement"
+ processing: "Paiement en cours"
+ success: "Paiement réussi"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Janvier"
+ february: "Février"
+ march: "Mars"
+ april: "Avril"
+ may: "Mai"
+ june: "Juin"
+ july: "Juillet"
+ august: "Août"
+ september: "Septembre"
+ october: "Octobre"
+ november: "Novembre"
+ december: "Décembre"
diff --git a/crates/router/locales/fr.yml b/crates/router/locales/fr.yml
new file mode 100644
index 00000000000..d12dc361d4c
--- /dev/null
+++ b/crates/router/locales/fr.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Vous n'êtes pas autorisé à voir ce contenu"
+ title: "Liens de Paiement"
+ status:
+ title: "Statut de Paiement"
+ info:
+ ref_id: "Id de Réf"
+ error_code: "Code d'Erreur"
+ error_message: "Message d'Erreur"
+ message:
+ failed: "Échec du traitement de votre paiement. Veuillez vérifier auprès de votre fournisseur pour plus de détails."
+ processing: "Votre paiement devrait être traité dans les 2 à 3 jours ouvrables."
+ success: "Votre paiement a été effectué sur le mode de paiement sélectionné."
+ redirection_text:
+ redirecting: "Redirection ..."
+ redirecting_in: "Redirection dans"
+ seconds: "secondes ..."
+ text:
+ failed: "Échec du Paiement"
+ processing: "Traitement du Paiement"
+ success: "Paiement Réussi"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Janvier"
+ february: "Février"
+ march: "Mars"
+ april: "Avril"
+ may: "Mai"
+ june: "Juin"
+ july: "Juillet"
+ august: "Août"
+ september: "Septembre"
+ october: "Octobre"
+ november: "Novembre"
+ december: "Décembre"
diff --git a/crates/router/locales/he.yml b/crates/router/locales/he.yml
new file mode 100644
index 00000000000..dbb3da209cf
--- /dev/null
+++ b/crates/router/locales/he.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "אינך מורשה לצפות בתוכן זה"
+ title: "קישורי תשלום"
+ status:
+ title: "סטטוס תשלום"
+ info:
+ ref_id: "מספר הפניה"
+ error_code: "קוד שגיאה"
+ error_message: "הודעת שגיאה"
+ message:
+ failed: "נכשל בעיבוד התשלום שלך. אנא בדוק עם הספק שלך למידע נוסף."
+ processing: "התשלום שלך צריך להיות מעובד בתוך 2-3 ימי עסקים."
+ success: "התשלום שלך בוצע לשיטת התשלום שנבחרה."
+ redirection_text:
+ redirecting: "מופנה..."
+ redirecting_in: "מופנה בעוד"
+ seconds: "שניות..."
+ text:
+ failed: "תשלום נכשל"
+ processing: "תשלום בתהליך"
+ success: "תשלום הצליח"
+
+time:
+ am: "בבוקר"
+ pm: "בערב"
+
+months:
+ january: "ינואר"
+ february: "פברואר"
+ march: "מרץ"
+ april: "אפריל"
+ may: "מאי"
+ june: "יוני"
+ july: "יולי"
+ august: "אוגוסט"
+ september: "ספטמבר"
+ october: "אוקטובר"
+ november: "נובמבר"
+ december: "דצמבר"
diff --git a/crates/router/locales/it.yml b/crates/router/locales/it.yml
new file mode 100644
index 00000000000..21f36a9af51
--- /dev/null
+++ b/crates/router/locales/it.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Non sei autorizzato a visualizzare questo contenuto"
+ title: "Link di Pagamento"
+ status:
+ title: "Stato del Pagamento"
+ info:
+ ref_id: "ID di Riferimento"
+ error_code: "Codice di Errore"
+ error_message: "Messaggio di Errore"
+ message:
+ failed: "Impossibile elaborare il tuo pagamento. Contatta il tuo fornitore per ulteriori dettagli."
+ processing: "Il tuo pagamento dovrebbe essere elaborato entro 2-3 giorni lavorativi."
+ success: "Il tuo pagamento è stato effettuato al metodo di pagamento selezionato."
+ redirection_text:
+ redirecting: "Reindirizzamento..."
+ redirecting_in: "Reindirizzamento tra"
+ seconds: "secondi..."
+ text:
+ failed: "Pagamento Fallito"
+ processing: "Pagamento in Corso"
+ success: "Pagamento Riuscito"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Gennaio"
+ february: "Febbraio"
+ march: "Marzo"
+ april: "Aprile"
+ may: "Maggio"
+ june: "Giugno"
+ july: "Luglio"
+ august: "Agosto"
+ september: "Settembre"
+ october: "Ottobre"
+ november: "Novembre"
+ december: "Dicembre"
diff --git a/crates/router/locales/ja.yml b/crates/router/locales/ja.yml
new file mode 100644
index 00000000000..4691374297b
--- /dev/null
+++ b/crates/router/locales/ja.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "このコンテンツを見ることはできません"
+ title: "支払いリンク"
+ status:
+ title: "支払いステータス"
+ info:
+ ref_id: "参照ID"
+ error_code: "エラーコード"
+ error_message: "エラーメッセージ"
+ message:
+ failed: "支払いの処理に失敗しました。詳細については提供者に確認してください。"
+ processing: "支払いは2〜3営業日以内に処理される予定です。"
+ success: "支払いが選択した支払い方法に対して行われました。"
+ redirection_text:
+ redirecting: "リダイレクト中..."
+ redirecting_in: "リダイレクトまで"
+ seconds: "秒..."
+ text:
+ failed: "支払い失敗"
+ processing: "支払い処理中"
+ success: "支払い成功"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "1月"
+ february: "2月"
+ march: "3月"
+ april: "4月"
+ may: "5月"
+ june: "6月"
+ july: "7月"
+ august: "8月"
+ september: "9月"
+ october: "10月"
+ november: "11月"
+ december: "12月"
diff --git a/crates/router/locales/nl.yml b/crates/router/locales/nl.yml
new file mode 100644
index 00000000000..1cf808d3935
--- /dev/null
+++ b/crates/router/locales/nl.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Je bent niet toegestaan om deze inhoud te bekijken"
+ title: "Betalingslinks"
+ status:
+ title: "Betalingsstatus"
+ info:
+ ref_id: "Referentie-ID"
+ error_code: "Foutcode"
+ error_message: "Foutmelding"
+ message:
+ failed: "Het is niet gelukt om je betaling te verwerken. Controleer bij je aanbieder voor meer details."
+ processing: "Je betaling moet binnen 2-3 werkdagen worden verwerkt."
+ success: "Je betaling is uitgevoerd naar de geselecteerde betaalmethode."
+ redirection_text:
+ redirecting: "Doorverwijzen..."
+ redirecting_in: "Doorverwijzen in"
+ seconds: "seconden..."
+ text:
+ failed: "Betaling Mislukt"
+ processing: "Betaling in Behandeling"
+ success: "Betaling Succesvol"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Januari"
+ february: "Februari"
+ march: "Maart"
+ april: "April"
+ may: "Mei"
+ june: "Juni"
+ july: "Juli"
+ august: "Augustus"
+ september: "September"
+ october: "Oktober"
+ november: "November"
+ december: "December"
diff --git a/crates/router/locales/pl.yml b/crates/router/locales/pl.yml
new file mode 100644
index 00000000000..71faae35945
--- /dev/null
+++ b/crates/router/locales/pl.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Nie masz uprawnień do wyświetlania tej treści"
+ title: "Linki do wypłat"
+ status:
+ title: "Status wypłaty"
+ info:
+ ref_id: "ID referencyjny"
+ error_code: "Kod błędu"
+ error_message: "Komunikat o błędzie"
+ message:
+ failed: "Nie udało się przetworzyć Twojej wypłaty. Skontaktuj się z dostawcą w celu uzyskania szczegółowych informacji."
+ processing: "Twoja wypłata powinna zostać przetworzona w ciągu 2-3 dni roboczych."
+ success: "Twoja wypłata została zrealizowana metodą płatności, którą wybrałeś."
+ redirection_text:
+ redirecting: "Przekierowywanie..."
+ redirecting_in: "Przekierowywanie za"
+ seconds: "sekund..."
+ text:
+ failed: "Wypłata Nieudana"
+ processing: "Wypłata w Trakcie"
+ success: "Wypłata Udała się"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Styczeń"
+ february: "Luty"
+ march: "Marzec"
+ april: "Kwiecień"
+ may: "Maj"
+ june: "Czerwiec"
+ july: "Lipiec"
+ august: "Sierpień"
+ september: "Wrzesień"
+ october: "Październik"
+ november: "Listopad"
+ december: "Grudzień"
diff --git a/crates/router/locales/pt.yml b/crates/router/locales/pt.yml
new file mode 100644
index 00000000000..8a419c2df21
--- /dev/null
+++ b/crates/router/locales/pt.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Você não tem permissão para visualizar este conteúdo"
+ title: "Links de Pagamento"
+ status:
+ title: "Status do Pagamento"
+ info:
+ ref_id: "ID de Referência"
+ error_code: "Código de Erro"
+ error_message: "Mensagem de Erro"
+ message:
+ failed: "Falha ao processar seu pagamento. Verifique com seu provedor para mais detalhes."
+ processing: "Seu pagamento deve ser processado em 2-3 dias úteis."
+ success: "Seu pagamento foi realizado no método de pagamento selecionado."
+ redirection_text:
+ redirecting: "Redirecionando..."
+ redirecting_in: "Redirecionando em"
+ seconds: "segundos..."
+ text:
+ failed: "Falha no Pagamento"
+ processing: "Pagamento em Processamento"
+ success: "Pagamento Bem-Sucedido"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Janeiro"
+ february: "Fevereiro"
+ march: "Março"
+ april: "Abril"
+ may: "Maio"
+ june: "Junho"
+ july: "Julho"
+ august: "Agosto"
+ september: "Setembro"
+ october: "Outubro"
+ november: "Novembro"
+ december: "Dezembro"
diff --git a/crates/router/locales/ru.yml b/crates/router/locales/ru.yml
new file mode 100644
index 00000000000..8257ee67025
--- /dev/null
+++ b/crates/router/locales/ru.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Вам не разрешено просматривать этот контент"
+ title: "Ссылки на выплаты"
+ status:
+ title: "Статус выплаты"
+ info:
+ ref_id: "ID ссылки"
+ error_code: "Код ошибки"
+ error_message: "Сообщение об ошибке"
+ message:
+ failed: "Не удалось обработать вашу выплату. Пожалуйста, проверьте у вашего поставщика более подробную информацию."
+ processing: "Ваша выплата должна быть обработана в течение 2-3 рабочих дней."
+ success: "Ваша выплата была произведена на выбранный метод оплаты."
+ redirection_text:
+ redirecting: "Перенаправление..."
+ redirecting_in: "Перенаправление через"
+ seconds: "секунд..."
+ text:
+ failed: "Выплата не удалась"
+ processing: "Выплата в процессе"
+ success: "Выплата успешна"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Январь"
+ february: "Февраль"
+ march: "Март"
+ april: "Апрель"
+ may: "Май"
+ june: "Июнь"
+ july: "Июль"
+ august: "Август"
+ september: "Сентябрь"
+ october: "Октябрь"
+ november: "Ноябрь"
+ december: "Декабрь"
diff --git a/crates/router/locales/sv.yml b/crates/router/locales/sv.yml
new file mode 100644
index 00000000000..8c053a2b096
--- /dev/null
+++ b/crates/router/locales/sv.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "Du har inte tillåtelse att visa detta innehåll"
+ title: "Utbetalningslänkar"
+ status:
+ title: "Utbetalningsstatus"
+ info:
+ ref_id: "Referens-ID"
+ error_code: "Felkod"
+ error_message: "Felmeddelande"
+ message:
+ failed: "Det gick inte att behandla din utbetalning. Kontrollera med din leverantör för mer information."
+ processing: "Din utbetalning bör behandlas inom 2-3 arbetsdagar."
+ success: "Din utbetalning har genomförts till vald betalningsmetod."
+ redirection_text:
+ redirecting: "Omdirigerar..."
+ redirecting_in: "Omdirigerar om"
+ seconds: "sekunder..."
+ text:
+ failed: "Utbetalning Misslyckades"
+ processing: "Utbetalning Under Behandling"
+ success: "Utbetalning Lyckad"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "Januari"
+ february: "Februari"
+ march: "Mars"
+ april: "April"
+ may: "Maj"
+ june: "Juni"
+ july: "Juli"
+ august: "Augusti"
+ september: "September"
+ october: "Oktober"
+ november: "November"
+ december: "December"
diff --git a/crates/router/locales/zh.yml b/crates/router/locales/zh.yml
new file mode 100644
index 00000000000..ce7cd3d3f95
--- /dev/null
+++ b/crates/router/locales/zh.yml
@@ -0,0 +1,42 @@
+_version: 1
+
+payout_link:
+ initiate:
+ not_allowed: "您没有权限查看此内容"
+ title: "支付链接"
+ status:
+ title: "支付状态"
+ info:
+ ref_id: "参考ID"
+ error_code: "错误代码"
+ error_message: "错误信息"
+ message:
+ failed: "处理您的支付时失败。请与您的服务提供商确认更多详细信息。"
+ processing: "您的支付应在2-3个工作日内处理完毕。"
+ success: "您的支付已成功完成,使用了选定的支付方式。"
+ redirection_text:
+ redirecting: "正在重定向..."
+ redirecting_in: "重定向中"
+ seconds: "秒..."
+ text:
+ failed: "支付失败"
+ processing: "支付处理中"
+ success: "支付成功"
+
+time:
+ am: "AM"
+ pm: "PM"
+
+months:
+ january: "一月"
+ february: "二月"
+ march: "三月"
+ april: "四月"
+ may: "五月"
+ june: "六月"
+ july: "七月"
+ august: "八月"
+ september: "九月"
+ october: "十月"
+ november: "十一月"
+ december: "十二月"
diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs
index ec43259ad2f..2c1dea5f6db 100644
--- a/crates/router/src/compatibility/wrap.rs
+++ b/crates/router/src/compatibility/wrap.rs
@@ -142,6 +142,7 @@ where
let link_type = (boxed_generic_link_data).data.to_string();
match services::generic_link_response::build_generic_link_html(
boxed_generic_link_data.data,
+ boxed_generic_link_data.locale,
) {
Ok(rendered_html) => api::http_response_html_data(rendered_html, None),
Err(_) => {
diff --git a/crates/router/src/core/generic_link/payout_link/initiate/index.html b/crates/router/src/core/generic_link/payout_link/initiate/index.html
index 1857e497d3f..fe574c37c3c 100644
--- a/crates/router/src/core/generic_link/payout_link/initiate/index.html
+++ b/crates/router/src/core/generic_link/payout_link/initiate/index.html
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Payout Links</title>
+ <title>{{ i18n_payout_link_title }}</title>
</head>
{{ css_style_tag }}
<body>
diff --git a/crates/router/src/core/generic_link/payout_link/initiate/script.js b/crates/router/src/core/generic_link/payout_link/initiate/script.js
index 731f3f76d0a..2327bfba13c 100644
--- a/crates/router/src/core/generic_link/payout_link/initiate/script.js
+++ b/crates/router/src/core/generic_link/payout_link/initiate/script.js
@@ -14,7 +14,7 @@ try {
// Remove the script from DOM incase it's not iframed
if (!isFramed) {
function initializePayoutSDK() {
- var errMsg = "You are not allowed to view this content.";
+ var errMsg = "{{i18n_not_allowed}}";
var contentElement = document.getElementById("payout-link");
if (contentElement instanceof HTMLDivElement) {
contentElement.innerHTML = errMsg;
@@ -34,25 +34,25 @@ if (!isFramed) {
**/
function formatDate(date) {
var months = [
- "January",
- "February",
- "March",
- "April",
- "May",
- "June",
- "July",
- "August",
- "September",
- "October",
- "November",
- "December",
+ "{{i18n_january}}",
+ "{{i18n_february}}",
+ "{{i18n_march}}",
+ "{{i18n_april}}",
+ "{{i18n_may}}",
+ "{{i18n_june}}",
+ "{{i18n_july}}",
+ "{{i18n_august}}",
+ "{{i18n_september}}",
+ "{{i18n_october}}",
+ "{{i18n_november}}",
+ "{{i18n_december}}",
];
var hours = date.getHours();
var minutes = date.getMinutes();
// @ts-ignore
minutes = minutes < 10 ? "0" + minutes : minutes;
- var suffix = hours > 11 ? "PM" : "AM";
+ var suffix = hours > 11 ? "{{i18n_pm}}" : "{{i18n_am}}";
hours = hours % 12;
hours = hours ? hours : 12;
var day = date.getDate();
@@ -127,6 +127,7 @@ if (!isFramed) {
// @ts-ignore
var payoutDetails = window.__PAYOUT_DETAILS;
var clientSecret = payoutDetails.client_secret;
+ var locale = payoutDetails.locale;
var publishableKey = payoutDetails.publishable_key;
var appearance = {
variables: {
@@ -143,6 +144,7 @@ if (!isFramed) {
widgets = hyper.widgets({
appearance: appearance,
clientSecret: clientSecret,
+ locale: locale,
});
// Create payment method collect widget
diff --git a/crates/router/src/core/generic_link/payout_link/status/index.html b/crates/router/src/core/generic_link/payout_link/status/index.html
index f0fb564f64b..4a4f0260563 100644
--- a/crates/router/src/core/generic_link/payout_link/status/index.html
+++ b/crates/router/src/core/generic_link/payout_link/status/index.html
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Payout Status</title>
+ <title>{{ i18n_payout_link_status_title }}</title>
{{ css_style_tag }}
</head>
<body>
diff --git a/crates/router/src/core/generic_link/payout_link/status/script.js b/crates/router/src/core/generic_link/payout_link/status/script.js
index 829006a4311..42b57903593 100644
--- a/crates/router/src/core/generic_link/payout_link/status/script.js
+++ b/crates/router/src/core/generic_link/payout_link/status/script.js
@@ -69,8 +69,8 @@ function renderStatusDetails(payoutDetails) {
var statusInfo = {
statusImageSrc:
"https://live.hyperswitch.io/payment-link-assets/success.png",
- statusText: "Payout Successful",
- statusMessage: "Your payout was made to selected payment method.",
+ statusText: "{{i18n_success_text}}",
+ statusMessage: "{{i18n_success_message}}",
};
switch (status) {
case "success":
@@ -80,9 +80,8 @@ function renderStatusDetails(payoutDetails) {
case "pending":
statusInfo.statusImageSrc =
"https://live.hyperswitch.io/payment-link-assets/pending.png";
- statusInfo.statusText = "Payout Processing";
- statusInfo.statusMessage =
- "Your payout should be processed within 2-3 business days.";
+ statusInfo.statusText = "{{i18n_pending_text}}";
+ statusInfo.statusMessage = "{{i18n_pending_message}}";
break;
case "failed":
case "cancelled":
@@ -96,9 +95,8 @@ function renderStatusDetails(payoutDetails) {
default:
statusInfo.statusImageSrc =
"https://live.hyperswitch.io/payment-link-assets/failed.png";
- statusInfo.statusText = "Payout Failed";
- statusInfo.statusMessage =
- "Failed to process your payout. Please check with your provider for more details.";
+ statusInfo.statusText = "{{i18n_failed_text}}";
+ statusInfo.statusMessage = "{{i18n_failed_message}}";
break;
}
@@ -120,13 +118,13 @@ function renderStatusDetails(payoutDetails) {
}
var resourceInfo = {
- "Ref Id": payoutDetails.payout_id,
+ "{{i18n_ref_id_text}}": payoutDetails.payout_id,
};
if (typeof payoutDetails.error_code === "string") {
- resourceInfo["Error Code"] = payoutDetails.error_code;
+ resourceInfo["{{i18n_error_code_text}}"] = payoutDetails.error_code;
}
if (typeof payoutDetails.error_message === "string") {
- resourceInfo["Error Message"] = payoutDetails.error_message;
+ resourceInfo["{{i18n_error_message}}"] = payoutDetails.error_message;
}
var resourceNode = document.createElement("div");
resourceNode.id = "resource-info-container";
@@ -166,8 +164,10 @@ function redirectToEndUrl(returnUrl) {
var secondsLeft = timeout - j++;
var innerText =
secondsLeft === 0
- ? "Redirecting ..."
- : "Redirecting in " + secondsLeft + " seconds ...";
+ ? "{{i18n_redirecting_text}}"
+ : "{{i18n_redirecting_in_text}} " +
+ secondsLeft +
+ " {{i18n_seconds_text}} ...";
if (statusRedirectTextNode instanceof HTMLDivElement) {
statusRedirectTextNode.innerText = innerText;
}
diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs
index 643b69511c7..df87637f4e4 100644
--- a/crates/router/src/core/payment_link.rs
+++ b/crates/router/src/core/payment_link.rs
@@ -7,8 +7,9 @@ use api_models::{
use common_utils::{
consts::{
DEFAULT_ALLOWED_DOMAINS, DEFAULT_BACKGROUND_COLOR, DEFAULT_DISPLAY_SDK_ONLY,
- DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG,
- DEFAULT_SDK_LAYOUT, DEFAULT_SESSION_EXPIRY, DEFAULT_TRANSACTION_DETAILS,
+ DEFAULT_ENABLE_SAVED_PAYMENT_METHOD, DEFAULT_LOCALE, DEFAULT_MERCHANT_LOGO,
+ DEFAULT_PRODUCT_IMG, DEFAULT_SDK_LAYOUT, DEFAULT_SESSION_EXPIRY,
+ DEFAULT_TRANSACTION_DETAILS,
},
ext_traits::{OptionExt, ValueExt},
types::{AmountConvertor, MinorUnit, StringMajorUnitForCore},
@@ -342,6 +343,7 @@ pub async fn initiate_secure_payment_link_flow(
let link_data = GenericLinks {
allowed_domains,
data: GenericLinksData::SecurePaymentLink(payment_link_data),
+ locale: DEFAULT_LOCALE.to_string(),
};
logger::info!(
"payment link data, for building secure payment link {:?}",
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index a33fe5bb06a..977727d9115 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -12,7 +12,7 @@ pub use api_models::enums::Connector;
use api_models::payment_methods;
#[cfg(feature = "payouts")]
pub use api_models::{enums::PayoutConnectors, payouts as payout_types};
-use common_utils::{ext_traits::Encode, id_type::CustomerId};
+use common_utils::{consts::DEFAULT_LOCALE, ext_traits::Encode, id_type::CustomerId};
use diesel_models::{
enums, GenericLinkNew, PaymentMethodCollectLink, PaymentMethodCollectLinkData,
};
@@ -251,6 +251,7 @@ pub async fn render_pm_collect_link(
GenericLinks {
allowed_domains: HashSet::from([]),
data: GenericLinksData::ExpiredLink(expired_link_data),
+ locale: DEFAULT_LOCALE.to_string(),
},
)))
@@ -312,8 +313,8 @@ pub async fn render_pm_collect_link(
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
-
data: GenericLinksData::PaymentMethodCollect(generic_form_data),
+ locale: DEFAULT_LOCALE.to_string(),
},
)))
}
@@ -357,8 +358,8 @@ pub async fn render_pm_collect_link(
Ok(services::ApplicationResponse::GenericLinkForm(Box::new(
GenericLinks {
allowed_domains: HashSet::from([]),
-
data: GenericLinksData::PaymentMethodCollectStatus(generic_status_data),
+ locale: DEFAULT_LOCALE.to_string(),
},
)))
}
diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs
index da34a82a854..1b9445f180e 100644
--- a/crates/router/src/core/payout_link.rs
+++ b/crates/router/src/core/payout_link.rs
@@ -30,6 +30,7 @@ pub async fn initiate_payout_link(
key_store: domain::MerchantKeyStore,
req: payouts::PayoutLinkInitiateRequest,
request_headers: &header::HeaderMap,
+ locale: String,
) -> RouterResponse<services::GenericLinkFormData> {
let db: &dyn StorageInterface = &*state.store;
let merchant_id = merchant_account.get_id();
@@ -108,6 +109,7 @@ pub async fn initiate_payout_link(
GenericLinks {
allowed_domains: (link_data.allowed_domains),
data: GenericLinksData::ExpiredLink(expired_link_data),
+ locale,
},
)))
}
@@ -187,6 +189,7 @@ pub async fn initiate_payout_link(
enabled_payment_methods,
amount,
currency: payout.destination_currency,
+ locale: locale.clone(),
};
let serialized_css_content = String::new();
@@ -209,6 +212,7 @@ pub async fn initiate_payout_link(
GenericLinks {
allowed_domains: (link_data.allowed_domains),
data: GenericLinksData::PayoutLink(generic_form_data),
+ locale,
},
)))
}
@@ -251,6 +255,7 @@ pub async fn initiate_payout_link(
GenericLinks {
allowed_domains: (link_data.allowed_domains),
data: GenericLinksData::PayoutLinkStatus(generic_status_data),
+ locale,
},
)))
}
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 2debb492ada..07b50d3a154 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -300,6 +300,7 @@ pub async fn payouts_create_core(
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
req: payouts::PayoutCreateRequest,
+ locale: &String,
) -> RouterResponse<payouts::PayoutCreateResponse> {
// Validate create request
let (payout_id, payout_method_data, profile_id, customer) =
@@ -314,6 +315,7 @@ pub async fn payouts_create_core(
&payout_id,
&profile_id,
payout_method_data.as_ref(),
+ locale,
customer.as_ref(),
)
.await?;
@@ -2206,6 +2208,7 @@ pub async fn payout_create_db_entries(
payout_id: &String,
profile_id: &String,
stored_payout_method_data: Option<&payouts::PayoutMethodData>,
+ locale: &String,
customer: Option<&domain::Customer>,
) -> RouterResult<PayoutData> {
let db = &*state.store;
@@ -2227,6 +2230,7 @@ pub async fn payout_create_db_entries(
merchant_id,
req,
payout_id,
+ locale,
)
.await?,
),
@@ -2552,6 +2556,7 @@ pub async fn create_payout_link(
merchant_id: &common_utils::id_type::MerchantId,
req: &payouts::PayoutCreateRequest,
payout_id: &String,
+ locale: &String,
) -> RouterResult<PayoutLink> {
let payout_link_config_req = req.payout_link_config.to_owned();
@@ -2595,8 +2600,9 @@ pub async fn create_payout_link(
.as_ref()
.map_or(default_config.expiry, |expiry| *expiry);
let url = format!(
- "{base_url}/payout_link/{}/{payout_id}",
- merchant_id.get_string_repr()
+ "{base_url}/payout_link/{}/{payout_id}?locale={}",
+ merchant_id.get_string_repr(),
+ locale
);
let link = url::Url::parse(&url)
.change_context(errors::ApiErrorResponse::InternalServerError)
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 9691a536626..9f419831026 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -11,6 +11,7 @@ pub mod core;
pub mod cors;
pub mod db;
pub mod env;
+pub mod locale;
pub(crate) mod macros;
pub mod routes;
@@ -44,6 +45,9 @@ use crate::{configs::settings, core::errors};
#[global_allocator]
static ALLOC: mimalloc::MiMalloc = mimalloc::MiMalloc;
+// Import translate fn in root
+use crate::locale::{_rust_i18n_t, _rust_i18n_try_translate};
+
/// Header Constants
pub mod headers {
pub const ACCEPT: &str = "Accept";
diff --git a/crates/router/src/locale.rs b/crates/router/src/locale.rs
new file mode 100644
index 00000000000..94961434508
--- /dev/null
+++ b/crates/router/src/locale.rs
@@ -0,0 +1,3 @@
+use rust_i18n::i18n;
+
+i18n!("locales", fallback = "en");
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index 304a0cde0ba..561f96ab71a 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -28,6 +28,7 @@ pub mod metrics;
pub mod payment_link;
pub mod payment_methods;
pub mod payments;
+#[cfg(feature = "payouts")]
pub mod payout_link;
#[cfg(feature = "payouts")]
pub mod payouts;
diff --git a/crates/router/src/routes/payout_link.rs b/crates/router/src/routes/payout_link.rs
index 7bac4c5519c..87157435721 100644
--- a/crates/router/src/routes/payout_link.rs
+++ b/crates/router/src/routes/payout_link.rs
@@ -1,17 +1,17 @@
-#[cfg(feature = "payouts")]
use actix_web::{web, Responder};
-#[cfg(feature = "payouts")]
use api_models::payouts::PayoutLinkInitiateRequest;
-#[cfg(feature = "payouts")]
+use common_utils::consts::DEFAULT_LOCALE;
use router_env::Flow;
-#[cfg(feature = "payouts")]
use crate::{
core::{api_locking, payout_link::*},
- services::{api, authentication as auth},
+ headers::ACCEPT_LANGUAGE,
+ services::{
+ api,
+ authentication::{self as auth, get_header_value_by_key},
+ },
AppState,
};
-#[cfg(feature = "payouts")]
pub async fn render_payout_link(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
@@ -24,13 +24,25 @@ pub async fn render_payout_link(
payout_id,
};
let headers = req.headers();
+ let locale = get_header_value_by_key(ACCEPT_LANGUAGE.into(), headers)
+ .ok()
+ .flatten()
+ .map(|val| val.to_string())
+ .unwrap_or(DEFAULT_LOCALE.to_string());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload.clone(),
|state, auth, req, _| {
- initiate_payout_link(state, auth.merchant_account, auth.key_store, req, headers)
+ initiate_payout_link(
+ state,
+ auth.merchant_account,
+ auth.key_store,
+ req,
+ headers,
+ locale.clone(),
+ )
},
&auth::MerchantIdAuth(merchant_id),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 3c3d0f0a16b..40c2e36cc58 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -2,6 +2,7 @@ use actix_web::{
body::{BoxBody, MessageBody},
web, HttpRequest, HttpResponse, Responder,
};
+use common_utils::consts;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -9,7 +10,12 @@ use super::app::AppState;
use crate::types::api::payments as payment_types;
use crate::{
core::{api_locking, payouts::*},
- services::{api, authentication as auth, authorization::permissions::Permission},
+ headers::ACCEPT_LANGUAGE,
+ services::{
+ api,
+ authentication::{self as auth, get_header_value_by_key},
+ authorization::permissions::Permission,
+ },
types::api::payouts as payout_types,
};
@@ -21,13 +27,18 @@ pub async fn payouts_create(
json_payload: web::Json<payout_types::PayoutCreateRequest>,
) -> HttpResponse {
let flow = Flow::PayoutsCreate;
+ let locale = get_header_value_by_key(ACCEPT_LANGUAGE.into(), req.headers())
+ .ok()
+ .flatten()
+ .map(|val| val.to_string())
+ .unwrap_or(consts::DEFAULT_LOCALE.to_string());
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth, req, _| {
- payouts_create_core(state, auth.merchant_account, auth.key_store, req)
+ payouts_create_core(state, auth.merchant_account, auth.key_store, req, &locale)
},
&auth::HeaderAuth(auth::ApiKeyAuth),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index c715594e8d5..b2571e66231 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -982,7 +982,10 @@ where
Ok(ApplicationResponse::GenericLinkForm(boxed_generic_link_data)) => {
let link_type = boxed_generic_link_data.data.to_string();
- match build_generic_link_html(boxed_generic_link_data.data) {
+ match build_generic_link_html(
+ boxed_generic_link_data.data,
+ boxed_generic_link_data.locale,
+ ) {
Ok(rendered_html) => {
let headers = if !boxed_generic_link_data.allowed_domains.is_empty() {
let domains_str = boxed_generic_link_data
diff --git a/crates/router/src/services/api/generic_link_response.rs b/crates/router/src/services/api/generic_link_response.rs
index f180e3d3f33..c47539eb8db 100644
--- a/crates/router/src/services/api/generic_link_response.rs
+++ b/crates/router/src/services/api/generic_link_response.rs
@@ -7,9 +7,11 @@ use tera::{Context, Tera};
use super::build_secure_payment_link_html;
use crate::core::errors;
+pub mod context;
pub fn build_generic_link_html(
boxed_generic_link_data: GenericLinksData,
+ locale: String,
) -> CustomResult<String, errors::ApiErrorResponse> {
match boxed_generic_link_data {
GenericLinksData::ExpiredLink(link_data) => build_generic_expired_link_html(&link_data),
@@ -20,10 +22,12 @@ pub fn build_generic_link_html(
GenericLinksData::PaymentMethodCollectStatus(pm_collect_data) => {
build_pm_collect_link_status_html(&pm_collect_data)
}
- GenericLinksData::PayoutLink(payout_link_data) => build_payout_link_html(&payout_link_data),
+ GenericLinksData::PayoutLink(payout_link_data) => {
+ build_payout_link_html(&payout_link_data, locale.as_str())
+ }
GenericLinksData::PayoutLinkStatus(pm_collect_data) => {
- build_payout_link_status_html(&pm_collect_data)
+ build_payout_link_status_html(&pm_collect_data, locale.as_str())
}
GenericLinksData::SecurePaymentLink(payment_link_data) => {
build_secure_payment_link_html(payment_link_data)
@@ -52,7 +56,6 @@ pub fn build_generic_expired_link_html(
fn build_html_template(
link_data: &GenericLinkFormData,
document: &'static str,
- script: &'static str,
styles: &'static str,
) -> CustomResult<(Tera, Context), errors::ApiErrorResponse> {
let mut tera: Tera = Tera::default();
@@ -65,42 +68,43 @@ fn build_html_template(
let _ = tera.add_raw_template("document_styles", &final_css);
context.insert("color_scheme", &link_data.css_data);
- // Insert dynamic context in JS
- let js_dynamic_context = "{{ script_data }}";
- let js_template = script.to_string();
- let final_js = format!("{}\n{}", js_dynamic_context, js_template);
- let _ = tera.add_raw_template("document_scripts", &final_js);
- context.insert("script_data", &link_data.js_data);
-
let css_style_tag = tera
.render("document_styles", &context)
.map(|css| format!("<style>{}</style>", css))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render CSS template")?;
- let js_script_tag = tera
- .render("document_scripts", &context)
- .map(|js| format!("<script>{}</script>", js))
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to render JS template")?;
-
// Insert HTML context
let html_template = document.to_string();
let _ = tera.add_raw_template("html_template", &html_template);
context.insert("css_style_tag", &css_style_tag);
- context.insert("js_script_tag", &js_script_tag);
Ok((tera, context))
}
pub fn build_payout_link_html(
link_data: &GenericLinkFormData,
+ locale: &str,
) -> CustomResult<String, errors::ApiErrorResponse> {
let document = include_str!("../../core/generic_link/payout_link/initiate/index.html");
- let script = include_str!("../../core/generic_link/payout_link/initiate/script.js");
let styles = include_str!("../../core/generic_link/payout_link/initiate/styles.css");
- let (tera, mut context) = build_html_template(link_data, document, script, styles)
+ let (mut tera, mut context) = build_html_template(link_data, document, styles)
.attach_printable("Failed to build context for payout link's HTML template")?;
+
+ // Insert dynamic context in JS
+ let script = include_str!("../../core/generic_link/payout_link/initiate/script.js");
+ let js_template = script.to_string();
+ let js_dynamic_context = "{{ script_data }}";
+ let final_js = format!("{}\n{}", js_dynamic_context, js_template);
+ let _ = tera.add_raw_template("document_scripts", &final_js);
+ context.insert("script_data", &link_data.js_data);
+ context::insert_locales_in_context_for_payout_link(&mut context, locale);
+ let js_script_tag = tera
+ .render("document_scripts", &context)
+ .map(|js| format!("<script>{}</script>", js))
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to render JS template")?;
+ context.insert("js_script_tag", &js_script_tag);
context.insert(
"hyper_sdk_loader_script_tag",
&format!(
@@ -109,6 +113,7 @@ pub fn build_payout_link_html(
),
);
+ // Render HTML template
tera.render("html_template", &context)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payout link's HTML template")
@@ -119,12 +124,25 @@ pub fn build_pm_collect_link_html(
) -> CustomResult<String, errors::ApiErrorResponse> {
let document =
include_str!("../../core/generic_link/payment_method_collect/initiate/index.html");
- let script = include_str!("../../core/generic_link/payment_method_collect/initiate/script.js");
let styles = include_str!("../../core/generic_link/payment_method_collect/initiate/styles.css");
- let (tera, mut context) = build_html_template(link_data, document, script, styles)
+ let (mut tera, mut context) = build_html_template(link_data, document, styles)
.attach_printable(
"Failed to build context for payment method collect link's HTML template",
)?;
+
+ // Insert dynamic context in JS
+ let script = include_str!("../../core/generic_link/payment_method_collect/initiate/script.js");
+ let js_template = script.to_string();
+ let js_dynamic_context = "{{ script_data }}";
+ let final_js = format!("{}\n{}", js_dynamic_context, js_template);
+ let _ = tera.add_raw_template("document_scripts", &final_js);
+ context.insert("script_data", &link_data.js_data);
+ let js_script_tag = tera
+ .render("document_scripts", &context)
+ .map(|js| format!("<script>{}</script>", js))
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to render JS template")?;
+ context.insert("js_script_tag", &js_script_tag);
context.insert(
"hyper_sdk_loader_script_tag",
&format!(
@@ -133,6 +151,7 @@ pub fn build_pm_collect_link_html(
),
);
+ // Render HTML template
tera.render("html_template", &context)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to render payment method collect link's HTML template")
@@ -140,6 +159,7 @@ pub fn build_pm_collect_link_html(
pub fn build_payout_link_status_html(
link_data: &GenericLinkStatusData,
+ locale: &str,
) -> CustomResult<String, errors::ApiErrorResponse> {
let mut tera = Tera::default();
let mut context = Context::new();
@@ -159,13 +179,13 @@ pub fn build_payout_link_status_html(
.attach_printable("Failed to render payout link status CSS template")?;
// Insert dynamic context in JS
- let js_dynamic_context = "{{ collect_link_status_context }}";
+ let js_dynamic_context = "{{ script_data }}";
let js_template =
include_str!("../../core/generic_link/payout_link/status/script.js").to_string();
let final_js = format!("{}\n{}", js_dynamic_context, js_template);
let _ = tera.add_raw_template("payout_link_status_script", &final_js);
- context.insert("collect_link_status_context", &link_data.js_data);
-
+ context.insert("script_data", &link_data.js_data);
+ context::insert_locales_in_context_for_payout_link_status(&mut context, locale);
let js_script_tag = tera
.render("payout_link_status_script", &context)
.map(|js| format!("<script>{}</script>", js))
diff --git a/crates/router/src/services/api/generic_link_response/context.rs b/crates/router/src/services/api/generic_link_response/context.rs
new file mode 100644
index 00000000000..1ea45bd1083
--- /dev/null
+++ b/crates/router/src/services/api/generic_link_response/context.rs
@@ -0,0 +1,80 @@
+use rust_i18n::t;
+use tera::Context;
+
+pub fn insert_locales_in_context_for_payout_link(context: &mut Context, locale: &str) {
+ let i18n_payout_link_title = t!("payout_link.initiate.title", locale = locale);
+ let i18n_january = t!("months.january", locale = locale);
+ let i18n_february = t!("months.february", locale = locale);
+ let i18n_march = t!("months.march", locale = locale);
+ let i18n_april = t!("months.april", locale = locale);
+ let i18n_may = t!("months.may", locale = locale);
+ let i18n_june = t!("months.june", locale = locale);
+ let i18n_july = t!("months.july", locale = locale);
+ let i18n_august = t!("months.august", locale = locale);
+ let i18n_september = t!("months.september", locale = locale);
+ let i18n_october = t!("months.october", locale = locale);
+ let i18n_november = t!("months.november", locale = locale);
+ let i18n_december = t!("months.december", locale = locale);
+ let i18n_not_allowed = t!("payout_link.initiate.not_allowed", locale = locale);
+ let i18n_am = t!("time.am", locale = locale);
+ let i18n_pm = t!("time.pm", locale = locale);
+
+ context.insert("i18n_payout_link_title", &i18n_payout_link_title);
+ context.insert("i18n_january", &i18n_january);
+ context.insert("i18n_february", &i18n_february);
+ context.insert("i18n_march", &i18n_march);
+ context.insert("i18n_april", &i18n_april);
+ context.insert("i18n_may", &i18n_may);
+ context.insert("i18n_june", &i18n_june);
+ context.insert("i18n_july", &i18n_july);
+ context.insert("i18n_august", &i18n_august);
+ context.insert("i18n_september", &i18n_september);
+ context.insert("i18n_october", &i18n_october);
+ context.insert("i18n_november", &i18n_november);
+ context.insert("i18n_december", &i18n_december);
+ context.insert("i18n_not_allowed", &i18n_not_allowed);
+ context.insert("i18n_am", &i18n_am);
+ context.insert("i18n_pm", &i18n_pm);
+}
+
+pub fn insert_locales_in_context_for_payout_link_status(context: &mut Context, locale: &str) {
+ let i18n_payout_link_status_title = t!("payout_link.status.title", locale = locale);
+ let i18n_success_text = t!("payout_link.status.text.success", locale = locale);
+ let i18n_success_message = t!("payout_link.status.message.success", locale = locale);
+ let i18n_pending_text = t!("payout_link.status.text.pending", locale = locale);
+ let i18n_pending_message = t!("payout_link.status.message.pending", locale = locale);
+ let i18n_failed_text = t!("payout_link.status.text.failed", locale = locale);
+ let i18n_failed_message = t!("payout_link.status.message.failed", locale = locale);
+ let i18n_ref_id_text = t!("payout_link.status.info.ref_id", locale = locale);
+ let i18n_error_code_text = t!("payout_link.status.info.error_code", locale = locale);
+ let i18n_error_message = t!("payout_link.status.info.error_message", locale = locale);
+ let i18n_redirecting_text = t!(
+ "payout_link.status.redirection_text.redirecting",
+ locale = locale
+ );
+ let i18n_redirecting_in_text = t!(
+ "payout_link.status.redirection_text.redirecting_in",
+ locale = locale
+ );
+ let i18n_seconds_text = t!(
+ "payout_link.status.redirection_text.seconds",
+ locale = locale
+ );
+
+ context.insert(
+ "i18n_payout_link_status_title",
+ &i18n_payout_link_status_title,
+ );
+ context.insert("i18n_success_text", &i18n_success_text);
+ context.insert("i18n_success_message", &i18n_success_message);
+ context.insert("i18n_pending_text", &i18n_pending_text);
+ context.insert("i18n_pending_message", &i18n_pending_message);
+ context.insert("i18n_failed_text", &i18n_failed_text);
+ context.insert("i18n_failed_message", &i18n_failed_message);
+ context.insert("i18n_ref_id_text", &i18n_ref_id_text);
+ context.insert("i18n_error_code_text", &i18n_error_code_text);
+ context.insert("i18n_error_message", &i18n_error_message);
+ context.insert("i18n_redirecting_text", &i18n_redirecting_text);
+ context.insert("i18n_redirecting_in_text", &i18n_redirecting_in_text);
+ context.insert("i18n_seconds_text", &i18n_seconds_text);
+}
|
feat
|
add localisation support for payout link's templates (#5552)
|
07733a5c5eb94c318626421f2b4420dce0ddd39b
|
2025-03-11 19:15:57
|
Pa1NarK
|
feat(connector): implement wallet mandates for authorizedotnet (#7412)
| false
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 1a3bbed136e..ad910ef415a 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -474,9 +474,9 @@ bank_debit.bacs = { connector_list = "adyen" }
bank_debit.sepa = { connector_list = "gocardless,adyen" } # Mandate supported payment method type and connector for bank_debit
bank_redirect.ideal = { connector_list = "stripe,adyen,globalpay" } # Mandate supported payment method type and connector for bank_redirect
bank_redirect.sofort = { connector_list = "stripe,globalpay" }
-wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica" }
+wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica,authorizedotnet" }
wallet.samsung_pay = { connector_list = "cybersource" }
-wallet.google_pay = { connector_list = "bankofamerica" }
+wallet.google_pay = { connector_list = "bankofamerica,authorizedotnet" }
bank_redirect.giropay = { connector_list = "globalpay" }
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index a2572b35728..47b65efabc4 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -177,9 +177,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" }
card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal"
card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal"
pay_later.klarna.connector_list = "adyen"
-wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet"
+wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet"
wallet.samsung_pay.connector_list = "cybersource"
-wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet"
+wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet"
wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal"
wallet.momo.connector_list = "adyen"
wallet.kakao_pay.connector_list = "adyen"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 430bb94d960..fc4bca222a9 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -177,9 +177,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" }
card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal"
card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal"
pay_later.klarna.connector_list = "adyen"
-wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet"
+wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet"
wallet.samsung_pay.connector_list = "cybersource"
-wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet"
+wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet"
wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal"
wallet.momo.connector_list = "adyen"
wallet.kakao_pay.connector_list = "adyen"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 6f0422e1862..37346fc3467 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -177,9 +177,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" }
card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal"
card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal"
pay_later.klarna.connector_list = "adyen"
-wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet"
+wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet"
wallet.samsung_pay.connector_list = "cybersource"
-wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet"
+wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet"
wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal"
wallet.momo.connector_list = "adyen"
wallet.kakao_pay.connector_list = "adyen"
diff --git a/config/development.toml b/config/development.toml
index f6e849af3d1..eab89187a46 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -784,9 +784,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" }
card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal"
card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal"
pay_later.klarna.connector_list = "adyen"
-wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet"
+wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet"
wallet.samsung_pay.connector_list = "cybersource"
-wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet"
+wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet"
wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal"
wallet.momo.connector_list = "adyen"
wallet.kakao_pay.connector_list = "adyen"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index b5eae287544..9a24adcd5e9 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -633,8 +633,8 @@ adyen = { banks = "aib,bank_of_scotland,danske_bank,first_direct,first_trust,hal
[mandates.supported_payment_methods]
pay_later.klarna = { connector_list = "adyen" }
-wallet.google_pay = { connector_list = "stripe,adyen,bankofamerica" }
-wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica" }
+wallet.google_pay = { connector_list = "stripe,adyen,bankofamerica,authorizedotnet" }
+wallet.apple_pay = { connector_list = "stripe,adyen,cybersource,noon,bankofamerica,authorizedotnet" }
wallet.samsung_pay = { connector_list = "cybersource" }
wallet.paypal = { connector_list = "adyen" }
card.credit = { connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,bamboraapac" }
diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs
index 29af20a9570..3bd39fd38b5 100644
--- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs
+++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs
@@ -117,7 +117,11 @@ impl ConnectorValidation for Authorizedotnet {
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
- let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]);
+ let mandate_supported_pmd = std::collections::HashSet::from([
+ PaymentMethodDataType::Card,
+ PaymentMethodDataType::GooglePay,
+ PaymentMethodDataType::ApplePay,
+ ]);
connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
index 626d6d76599..d7f50aa7405 100644
--- a/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
@@ -31,8 +31,8 @@ use serde_json::Value;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
- self, CardData, ForeignTryFrom, PaymentsSyncRequestData, RefundsRequestData,
- RouterData as OtherRouterData, WalletData as OtherWalletData,
+ self, CardData, ForeignTryFrom, PaymentsAuthorizeRequestData, PaymentsSyncRequestData,
+ RefundsRequestData, RouterData as OtherRouterData, WalletData as OtherWalletData,
},
};
@@ -376,8 +376,92 @@ impl TryFrom<&SetupMandateRouterData> for CreateCustomerProfileRequest {
},
})
}
+ PaymentMethodData::Wallet(wallet_data) => match wallet_data {
+ WalletData::GooglePay(_) => {
+ let merchant_authentication =
+ AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
+ let validation_mode = match item.test_mode {
+ Some(true) | None => ValidationMode::TestMode,
+ Some(false) => ValidationMode::LiveMode,
+ };
+ Ok(Self {
+ create_customer_profile_request: AuthorizedotnetZeroMandateRequest {
+ merchant_authentication,
+ profile: Profile {
+ // The payment ID is included in the description because the connector requires unique description when creating a mandate.
+ description: item.payment_id.clone(),
+ payment_profiles: PaymentProfiles {
+ customer_type: CustomerType::Individual,
+ payment: PaymentDetails::OpaqueData(WalletDetails {
+ data_descriptor: WalletMethod::Googlepay,
+ data_value: Secret::new(
+ wallet_data.get_encoded_wallet_token()?,
+ ),
+ }),
+ },
+ },
+ validation_mode,
+ },
+ })
+ }
+ WalletData::ApplePay(applepay_token) => {
+ let merchant_authentication =
+ AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
+ let validation_mode = match item.test_mode {
+ Some(true) | None => ValidationMode::TestMode,
+ Some(false) => ValidationMode::LiveMode,
+ };
+ Ok(Self {
+ create_customer_profile_request: AuthorizedotnetZeroMandateRequest {
+ merchant_authentication,
+ profile: Profile {
+ // The payment ID is included in the description because the connector requires unique description when creating a mandate.
+ description: item.payment_id.clone(),
+ payment_profiles: PaymentProfiles {
+ customer_type: CustomerType::Individual,
+ payment: PaymentDetails::OpaqueData(WalletDetails {
+ data_descriptor: WalletMethod::Applepay,
+ data_value: Secret::new(
+ applepay_token.payment_data.clone(),
+ ),
+ }),
+ },
+ },
+ validation_mode,
+ },
+ })
+ }
+ WalletData::AliPayQr(_)
+ | WalletData::AliPayRedirect(_)
+ | WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
+ | WalletData::MomoRedirect(_)
+ | WalletData::KakaoPayRedirect(_)
+ | WalletData::GoPayRedirect(_)
+ | WalletData::GcashRedirect(_)
+ | WalletData::ApplePayRedirect(_)
+ | WalletData::ApplePayThirdPartySdk(_)
+ | WalletData::DanaRedirect {}
+ | WalletData::GooglePayRedirect(_)
+ | WalletData::GooglePayThirdPartySdk(_)
+ | WalletData::MbWayRedirect(_)
+ | WalletData::MobilePayRedirect(_)
+ | WalletData::PaypalRedirect(_)
+ | WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
+ | WalletData::SamsungPay(_)
+ | WalletData::TwintRedirect {}
+ | WalletData::VippsRedirect {}
+ | WalletData::TouchNGoRedirect(_)
+ | WalletData::WeChatPayRedirect(_)
+ | WalletData::WeChatPayQr(_)
+ | WalletData::CashappQr(_)
+ | WalletData::SwishQr(_)
+ | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
+ ))?,
+ },
PaymentMethodData::CardRedirect(_)
- | PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
@@ -748,41 +832,24 @@ impl
&Card,
),
) -> Result<Self, Self::Error> {
- let (profile, customer) =
- if item
- .router_data
- .request
- .setup_future_usage
- .is_some_and(|future_usage| {
- matches!(future_usage, common_enums::FutureUsage::OffSession)
- })
- && (item.router_data.request.customer_acceptance.is_some()
- || item
- .router_data
- .request
- .setup_mandate_details
- .clone()
- .is_some_and(|mandate_details| {
- mandate_details.customer_acceptance.is_some()
- }))
- {
- (
- Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails {
- create_profile: true,
- })),
- Some(CustomerDetails {
- //The payment ID is included in the customer details because the connector requires unique customer information with a length of fewer than 20 characters when creating a mandate.
- //If the length exceeds 20 characters, a random alphanumeric string is used instead.
- id: if item.router_data.payment_id.len() <= 20 {
- item.router_data.payment_id.clone()
- } else {
- Alphanumeric.sample_string(&mut rand::thread_rng(), 20)
- },
- }),
- )
- } else {
- (None, None)
- };
+ let (profile, customer) = if item.router_data.request.is_mandate_payment() {
+ (
+ Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails {
+ create_profile: true,
+ })),
+ Some(CustomerDetails {
+ //The payment ID is included in the customer details because the connector requires unique customer information with a length of fewer than 20 characters when creating a mandate.
+ //If the length exceeds 20 characters, a random alphanumeric string is used instead.
+ id: if item.router_data.payment_id.len() <= 20 {
+ item.router_data.payment_id.clone()
+ } else {
+ Alphanumeric.sample_string(&mut rand::thread_rng(), 20)
+ },
+ }),
+ )
+ } else {
+ (None, None)
+ };
Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
@@ -841,6 +908,23 @@ impl
&WalletData,
),
) -> Result<Self, Self::Error> {
+ let (profile, customer) = if item.router_data.request.is_mandate_payment() {
+ (
+ Some(ProfileDetails::CreateProfileDetails(CreateProfileDetails {
+ create_profile: true,
+ })),
+ Some(CustomerDetails {
+ id: if item.router_data.payment_id.len() <= 20 {
+ item.router_data.payment_id.clone()
+ } else {
+ Alphanumeric.sample_string(&mut rand::thread_rng(), 20)
+ },
+ }),
+ )
+ } else {
+ (None, None)
+ };
+
Ok(Self {
transaction_type: TransactionType::try_from(item.router_data.request.capture_method)?,
amount: item.amount,
@@ -849,11 +933,11 @@ impl
wallet_data,
&item.router_data.request.complete_authorize_url,
)?),
- profile: None,
+ profile,
order: Order {
description: item.router_data.connector_request_reference_id.clone(),
},
- customer: None,
+ customer,
bill_to: item
.router_data
.get_optional_billing()
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index ff50c5f8cd9..bdf46a8ee40 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -279,8 +279,8 @@ cards = [
]
[pm_filters.dlocal]
-credit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
-debit = {country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW"}
+credit = { country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW" }
+debit = { country = "AR,BD,BO,BR,CM,CL,CN,CO,CR,DO,EC,SV,EG,GH,GT,HN,IN,ID,CI,JP,KE,MY,MX,MA,NI,NG,PK,PA,PY,PE,PH,RW,SA,SN,ZA,TZ,TH,TR,UG,UY,VN,ZM", currency = "ARS,BDT,BOB,BRL,XAF,CLP,CNY,COP,CRC,DOP,USD,EGP,GHS,GTQ,HNL,INR,IDR,XOF,JPY,KES,MYR,MXN,MAD,NIO,NGN,PKR,PYG,PEN,PHP,RWF,SAR,XOF,ZAR,TZS,THB,TRY,UGX,UYU,VND,ZMW" }
[pm_filters.mollie]
credit = { not_available_flows = { capture_method = "manual" } }
@@ -419,9 +419,9 @@ bank_debit.sepa = { connector_list = "gocardless,adyen,stripe,deutschebank" }
card.credit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal"
card.debit.connector_list = "stripe,adyen,authorizedotnet,cybersource,datatrans,globalpay,worldpay,multisafepay,nmi,nexinets,noon,bankofamerica,braintree,nuvei,payme,wellsfargo,bamboraapac,elavon,fiuu,nexixpay,novalnet,paybox,paypal"
pay_later.klarna.connector_list = "adyen"
-wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet"
+wallet.apple_pay.connector_list = "stripe,adyen,cybersource,noon,bankofamerica,nexinets,novalnet,authorizedotnet"
wallet.samsung_pay.connector_list = "cybersource"
-wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet"
+wallet.google_pay.connector_list = "stripe,adyen,cybersource,bankofamerica,noon,globalpay,multisafepay,novalnet,authorizedotnet"
wallet.paypal.connector_list = "adyen,globalpay,nexinets,novalnet,paypal"
wallet.momo.connector_list = "adyen"
wallet.kakao_pay.connector_list = "adyen"
|
feat
|
implement wallet mandates for authorizedotnet (#7412)
|
ef1914ec9b75240628ad0c6367499ec063d31e3d
|
2024-04-18 09:17:15
|
Gnanasundari24
|
test(cypress): Update ConnectorAuth Details (#4386)
| false
|
diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js
index ce743887a45..925ecc2a4b0 100644
--- a/cypress-tests/cypress/support/commands.js
+++ b/cypress-tests/cypress/support/commands.js
@@ -26,7 +26,7 @@
// commands.js or your custom support file
import * as RequestBodyUtils from "../utils/RequestBodyUtils";
-import ConnectorAuthDetails from "../../creds.json";
+import ConnectorAuthDetails from "../../../.github/secrets/creds.json";
|
test
|
Update ConnectorAuth Details (#4386)
|
f3224cc4dff3d35d6f77095239fdebc9ec3a32fc
|
2023-02-26 13:55:17
|
Arun Raj M
|
chore: merging back release v0.3.0 back to main (#636) (#655)
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8dce72ec6e8..2d0cf0ad964 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,64 @@
+# 0.3.0 (2023-02-25)
+
+## Build System / Dependencies
+
+* **docker-compose:** increase docker health check interval for hyperswitch-server (#534)
+
+## Chores
+
+* **release:** port release bug fixes to main branch (#612) (a8d6ce83)
+
+## Continuous Integration
+
+* run CI checks on merge queue events (#530) (c7b9e9c1)
+
+## Documentation Changes
+
+* **add_connector:** fix typo (#584) (a4f3abf3)
+
+## New Features
+
+* **router:**
+ * include eligible connectors list in list payment methods (#644) (92771b3b)
+ * API endpoints for managing API keys (#511) (1bdc8955)
+* **connector:**
+ * [Airwallex] add authorize, capture, void, psync, Webhooks support (#646) (6a67dd8b)
+ * [Bluesnap] add authorize, capture, void, refund, psync, rsync and Webhooks support (#649) (7efdc3c5)
+ * add authorize, capture, void, refund, psync support for Nuvei (#645) (03a9f5a9)
+* Added applepay feature (#636) (1e84c07c)
+* add `track_caller` to functions that perform `change_context` (#592) (8d2e573a)
+* Redis cache for MCA fetch and update (#515) (963cb528)
+* **api_models:** add error structs (#532) (d107b44f)
+
+## Bug Fixes
+
+* **connector:** update Bluesnap in routable connectors (#654) (64cb2ffc)
+* allow errors with status code 200 to pass (#601) (8a8767e9)
+* don't call connector if connector transaction id doesn't exist (#525) (326d6beb)
+* throw 500 error when redis goes down (#531) (aafb115a)
+* **router:**
+ * allow setup future usage to be updated in payment update and confirm requests (#610) (#638) (6c128f82)
+ * feature gate openssl deps for basilisk feature (#536) (e4956820)
+* **checkout:** Error Response when wrong api key is passed (#596) (55b6d88a)
+* **core:** use guard for access token result (#522) (903b4521)
+
+## Other Changes
+
+* **router:**
+ * webhooks enhancement (#637) (#641) (3bc9feb0)
+ * api keys path params (#609) (effa7a00)
+
+## Refactors
+
+* **router:**
+ * update payments api contract to accept a list of connectors (#643) (8f1f626c)
+ * api-key routes refactoring (#600) (e6408276)
+ * appstate as trait in authentication (#588) (eaf98e66)
+* **compatibility:** add additional fields to stripe payment and refund response types (#618) (2ea09e34)
+* Throw 500 error on database connection error instead of panic (#527) (f1e3bf48)
+* send full payment object for payment sync (#526) (6c2a1fea)
+* **middleware:** change visibility to `pub` (#587) (4884a24d)
+
# 0.2.1 (2023-02-17)
## Fixes
diff --git a/Cargo.lock b/Cargo.lock
index 5712e1d1cf2..8183ea5d40a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -317,6 +317,7 @@ dependencies = [
"serde_json",
"strum",
"time",
+ "url",
"utoipa",
]
@@ -1038,6 +1039,7 @@ dependencies = [
"futures",
"hex",
"masking",
+ "md5",
"nanoid",
"once_cell",
"proptest",
@@ -2222,6 +2224,12 @@ dependencies = [
"syn",
]
+[[package]]
+name = "md5"
+version = "0.7.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"
+
[[package]]
name = "memchr"
version = "2.5.0"
diff --git a/config/Development.toml b/config/Development.toml
index 68f4630aaef..95e341e72a2 100644
--- a/config/Development.toml
+++ b/config/Development.toml
@@ -43,8 +43,26 @@ locker_decryption_key1 = ""
locker_decryption_key2 = ""
[connectors.supported]
-wallets = ["klarna","braintree","applepay"]
-cards = ["stripe","adyen","authorizedotnet","checkout","braintree","aci","shift4","cybersource", "worldpay", "globalpay", "fiserv", "payu", "worldline", "dlocal"]
+wallets = ["klarna", "braintree", "applepay"]
+cards = [
+ "aci",
+ "adyen",
+ "airwallex",
+ "authorizedotnet",
+ "bluesnap",
+ "braintree",
+ "checkout",
+ "cybersource",
+ "dlocal",
+ "fiserv",
+ "globalpay",
+ "nuvei",
+ "payu",
+ "shift4",
+ "stripe",
+ "worldline",
+ "worldpay",
+]
[refund]
max_attempts = 10
@@ -104,6 +122,15 @@ base_url = "https://apis.sandbox.globalpay.com/ucp/"
[connectors.worldline]
base_url = "https://eu.sandbox.api-ingenico.com/"
+[connectors.bluesnap]
+base_url = "https://sandbox.bluesnap.com/"
+
+[connectors.nuvei]
+base_url = "https://ppp-test.nuvei.com/"
+
+[connectors.airwallex]
+base_url = "https://api-demo.airwallex.com/"
+
[connectors.dlocal]
base_url = "https://sandbox.dlocal.com/"
diff --git a/config/config.example.toml b/config/config.example.toml
index 9a9c22dc65d..b6bfd1dd1cf 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -153,10 +153,19 @@ base_url = "https://try.access.worldpay.com/"
[connectors.globalpay]
base_url = "https://apis.sandbox.globalpay.com/ucp/"
-# This data is used to call respective connectors for wallets and cards
+[connectors.bluesnap]
+base_url = "https://sandbox.bluesnap.com/"
+
+[connectors.nuvei]
+base_url = "https://ppp-test.nuvei.com/"
+
+[connectors.airwallex]
+base_url = "https://api-demo.airwallex.com/"
+
[connectors.dlocal]
base_url = "https://sandbox.dlocal.com/"
+# This data is used to call respective connectors for wallets and cards
[connectors.supported]
wallets = ["klarna", "braintree", "applepay"]
cards = [
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 9bbac7af768..06f3d3cfb76 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -105,12 +105,38 @@ base_url = "https://try.access.worldpay.com/"
[connectors.globalpay]
base_url = "https://apis.sandbox.globalpay.com/ucp/"
+[connectors.bluesnap]
+base_url = "https://sandbox.bluesnap.com/"
+
+[connectors.nuvei]
+base_url = "https://ppp-test.nuvei.com/"
+
+[connectors.airwallex]
+base_url = "https://api-demo.airwallex.com/"
+
[connectors.dlocal]
base_url = "https://sandbox.dlocal.com/"
[connectors.supported]
wallets = ["klarna", "braintree", "applepay"]
-cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "shift4", "cybersource", "worldpay", "globalpay", "fiserv", "dlocal"]
+cards = [
+ "adyen",
+ "airwallex",
+ "authorizedotnet",
+ "bluesnap",
+ "braintree",
+ "checkout",
+ "cybersource",
+ "dlocal",
+ "fiserv",
+ "globalpay",
+ "nuvei",
+ "payu",
+ "shift4",
+ "stripe",
+ "worldline",
+ "worldpay",
+]
[scheduler]
@@ -118,4 +144,4 @@ stream = "SCHEDULER_STREAM"
[scheduler.consumer]
disabled = false
-consumer_group = "SCHEDULER_GROUP"
\ No newline at end of file
+consumer_group = "SCHEDULER_GROUP"
diff --git a/connector-template/mod.rs b/connector-template/mod.rs
index ee78464f025..bbb2d4a6721 100644
--- a/connector-template/mod.rs
+++ b/connector-template/mod.rs
@@ -110,10 +110,14 @@ impl
fn get_url(&self, _req: &types::PaymentsAuthorizeRouterData, _connectors: &settings::Connectors,) -> CustomResult<String,errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
-
+
fn get_request_body(&self, req: &types::PaymentsAuthorizeRouterData) -> CustomResult<Option<String>,errors::ConnectorError> {
+ let req_obj = {{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest::try_from(req)?;
let {{project-name | downcase}}_req =
- utils::Encode::<{{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest>::convert_and_encode(req).change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ utils::Encode::<{{project-name | downcase}}::{{project-name | downcase | pascal_case}}PaymentsRequest>::encode_to_string_of_json(
+ &req_obj,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Some({{project-name | downcase}}_req))
}
diff --git a/connector-template/test.rs b/connector-template/test.rs
index c9c5fe0b5f0..df5dde5867a 100644
--- a/connector-template/test.rs
+++ b/connector-template/test.rs
@@ -106,6 +106,7 @@ async fn should_void_authorized_payment() {
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
}),
None,
)
diff --git a/crates/api_models/Cargo.toml b/crates/api_models/Cargo.toml
index 6575cf2a23d..c50967e7a92 100644
--- a/crates/api_models/Cargo.toml
+++ b/crates/api_models/Cargo.toml
@@ -16,6 +16,7 @@ serde = { version = "1.0.152", features = ["derive"] }
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"] }
# First party crates
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index e424af80863..6f02a8713ba 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -1,6 +1,7 @@
use common_utils::pii;
use masking::{Secret, StrongSecret};
use serde::{Deserialize, Serialize};
+use url;
use utoipa::ToSchema;
use super::payments::AddressDetails;
@@ -26,7 +27,7 @@ pub struct CreateMerchantAccount {
/// The URL to redirect after the completion of the operation
#[schema(max_length = 255, example = "https://www.example.com/success")]
- pub return_url: Option<String>,
+ pub return_url: Option<url::Url>,
/// Webhook related details
pub webhook_details: Option<WebhookDetails>,
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 08368491925..033a1ce39d8 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -11,6 +11,7 @@ use utoipa::ToSchema;
serde::Serialize,
strum::Display,
strum::EnumString,
+ frunk::LabelledGeneric,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
@@ -572,8 +573,10 @@ pub enum MandateStatus {
pub enum Connector {
Aci,
Adyen,
+ Airwallex,
Applepay,
Authorizedotnet,
+ Bluesnap,
Braintree,
Checkout,
Cybersource,
@@ -583,6 +586,7 @@ pub enum Connector {
Fiserv,
Globalpay,
Klarna,
+ Nuvei,
Payu,
Rapyd,
Shift4,
@@ -593,7 +597,7 @@ pub enum Connector {
impl Connector {
pub fn supports_access_token(&self) -> bool {
- matches!(self, Self::Globalpay | Self::Payu)
+ matches!(self, Self::Airwallex | Self::Globalpay | Self::Payu)
}
}
@@ -614,7 +618,9 @@ impl Connector {
pub enum RoutableConnectors {
Aci,
Adyen,
+ Airwallex,
Authorizedotnet,
+ Bluesnap,
Braintree,
Checkout,
Cybersource,
@@ -622,6 +628,7 @@ pub enum RoutableConnectors {
Fiserv,
Globalpay,
Klarna,
+ Nuvei,
Payu,
Rapyd,
Shift4,
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 2967f736e4e..4bbbf33a6d9 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -296,7 +296,7 @@ pub struct ListPaymentMethodResponse {
}
]
))]
- pub payment_methods: HashSet<ListPaymentMethod>,
+ pub payment_methods: Vec<ListPaymentMethod>,
}
#[derive(Eq, PartialEq, Hash, Debug, serde::Deserialize, ToSchema)]
@@ -362,9 +362,12 @@ pub struct ListPaymentMethod {
/// Type of payment experience enabled with the connector
#[schema(value_type = Option<Vec<PaymentExperience>>, example = json!(["redirect_to_url"]))]
pub payment_experience: Option<Vec<api_enums::PaymentExperience>>,
+
+ /// Eligible connectors for this payment method
+ #[schema(example = json!(["stripe", "adyen"]))]
+ pub eligible_connectors: Option<Vec<String>>,
}
-/// We need a custom serializer to only send relevant fields in ListPaymentMethodResponse
/// Currently if the payment method is Wallet or Paylater the relevant fields are `payment_method`
/// and `payment_method_issuers`. Otherwise only consider
/// `payment_method`,`payment_method_issuers`,`payment_method_types`,`payment_schemes` fields.
@@ -377,6 +380,7 @@ impl serde::Serialize for ListPaymentMethod {
let mut state = serializer.serialize_struct("ListPaymentMethod", 4)?;
state.serialize_field("payment_method", &self.payment_method)?;
state.serialize_field("payment_experience", &self.payment_experience)?;
+ state.serialize_field("eligible_connectors", &self.eligible_connectors)?;
match self.payment_method {
api_enums::PaymentMethodType::Wallet | api_enums::PaymentMethodType::PayLater => {
state.serialize_field("payment_method_issuers", &self.payment_method_issuers)?;
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 142bef10b42..3adcc5e315d 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1,6 +1,6 @@
use std::num::NonZeroI64;
-use common_utils::{errors, ext_traits::Encode, pii};
+use common_utils::pii;
use masking::{PeekInterface, Secret};
use router_derive::Setter;
use time::PrimitiveDateTime;
@@ -38,7 +38,7 @@ pub struct PaymentsRequest {
pub amount: Option<Amount>,
/// This allows the merchant to manually select a connector with which the payment can go through
#[schema(value_type = Option<Connector>, max_length = 255, example = "stripe")]
- pub connector: Option<api_enums::Connector>,
+ pub connector: Option<Vec<api_enums::Connector>>,
/// The currency of the payment request can be specified here
#[schema(value_type = Option<Currency>, example = "USD")]
pub currency: Option<api_enums::Currency>,
@@ -80,7 +80,7 @@ pub struct PaymentsRequest {
pub description: Option<String>,
/// The URL to redirect after the completion of the operation
#[schema(example = "https://hyperswitch.io")]
- pub return_url: Option<String>,
+ pub return_url: Option<url::Url>,
/// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete.
#[schema(value_type = Option<FutureUsage>, example = "off_session")]
pub setup_future_usage: Option<api_enums::FutureUsage>,
@@ -795,46 +795,6 @@ impl From<&VerifyRequest> for MandateValidationFields {
}
}
-impl TryFrom<PaymentsRequest> for PaymentsResponse {
- type Error = error_stack::Report<errors::ParsingError>;
- fn try_from(item: PaymentsRequest) -> Result<Self, Self::Error> {
- let payment_id = match item.payment_id {
- Some(PaymentIdType::PaymentIntentId(id)) => Some(id),
- _ => None,
- };
- let metadata = item
- .metadata
- .as_ref()
- .map(Encode::<Metadata>::encode_to_value)
- .transpose()?;
- Ok(Self {
- payment_id,
- merchant_id: item.merchant_id,
- setup_future_usage: item.setup_future_usage,
- off_session: item.off_session,
- shipping: item.shipping,
- billing: item.billing,
- metadata,
- capture_method: item.capture_method,
- payment_method: item.payment_method,
- capture_on: item.capture_on,
- payment_method_data: item
- .payment_method_data
- .map(PaymentMethodDataResponse::from),
- email: item.email,
- name: item.name,
- phone: item.phone,
- payment_token: item.payment_token,
- return_url: item.return_url,
- authentication_type: item.authentication_type,
- statement_descriptor_name: item.statement_descriptor_name,
- statement_descriptor_suffix: item.statement_descriptor_suffix,
- mandate_data: item.mandate_data,
- ..Default::default()
- })
- }
-}
-
impl From<VerifyRequest> for VerifyResponse {
fn from(item: VerifyRequest) -> Self {
Self {
@@ -853,25 +813,6 @@ impl From<VerifyRequest> for VerifyResponse {
}
}
-impl From<PaymentsStartRequest> for PaymentsResponse {
- fn from(item: PaymentsStartRequest) -> Self {
- Self {
- payment_id: Some(item.payment_id),
- merchant_id: Some(item.merchant_id),
- ..Default::default()
- }
- }
-}
-
-impl From<PaymentsSessionRequest> for PaymentsResponse {
- fn from(item: PaymentsSessionRequest) -> Self {
- Self {
- payment_id: Some(item.payment_id),
- ..Default::default()
- }
- }
-}
-
impl From<PaymentsSessionRequest> for PaymentsSessionResponse {
fn from(item: PaymentsSessionRequest) -> Self {
let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret);
@@ -893,43 +834,6 @@ impl From<PaymentsStartRequest> for PaymentsRequest {
}
}
-impl From<PaymentsRetrieveRequest> for PaymentsResponse {
- // After removing the request from the payments_to_payments_response this will no longer be needed
- fn from(item: PaymentsRetrieveRequest) -> Self {
- let payment_id = match item.resource_id {
- PaymentIdType::PaymentIntentId(id) => Some(id),
- _ => None,
- };
-
- Self {
- payment_id,
- merchant_id: item.merchant_id,
- ..Default::default()
- }
- }
-}
-
-impl From<PaymentsCancelRequest> for PaymentsResponse {
- fn from(item: PaymentsCancelRequest) -> Self {
- Self {
- payment_id: Some(item.payment_id),
- cancellation_reason: item.cancellation_reason,
- ..Default::default()
- }
- }
-}
-
-impl From<PaymentsCaptureRequest> for PaymentsResponse {
- // After removing the request from the payments_to_payments_response this will no longer be needed
- fn from(item: PaymentsCaptureRequest) -> Self {
- Self {
- payment_id: item.payment_id,
- amount_received: item.amount_to_capture,
- ..Self::default()
- }
- }
-}
-
impl From<Card> for CardResponse {
fn from(card: Card) -> Self {
let card_number_length = card.card_number.peek().clone().len();
@@ -1096,18 +1000,18 @@ pub struct GpaySessionTokenData {
#[serde(rename_all = "lowercase")]
pub enum SessionToken {
/// The session response structure for Google Pay
- Gpay(Box<GpayData>),
+ Gpay(Box<GpaySessionTokenResponse>),
/// The session response structure for Klarna
- Klarna(Box<KlarnaData>),
+ Klarna(Box<KlarnaSessionTokenResponse>),
/// The session response structure for PayPal
- Paypal(Box<PaypalData>),
+ Paypal(Box<PaypalSessionTokenResponse>),
/// The session response structure for Apple Pay
- Applepay(Box<ApplepayData>),
+ Applepay(Box<ApplepaySessionTokenResponse>),
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
#[serde(rename_all = "lowercase")]
-pub struct GpayData {
+pub struct GpaySessionTokenResponse {
/// The merchant info
pub merchant_info: GpayMerchantInfo,
/// List of the allowed payment meythods
@@ -1118,7 +1022,7 @@ pub struct GpayData {
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
#[serde(rename_all = "lowercase")]
-pub struct KlarnaData {
+pub struct KlarnaSessionTokenResponse {
/// The session token for Klarna
pub session_token: String,
/// The identifier for the session
@@ -1127,29 +1031,29 @@ pub struct KlarnaData {
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
#[serde(rename_all = "lowercase")]
-pub struct PaypalData {
+pub struct PaypalSessionTokenResponse {
/// The session token for PayPal
pub session_token: String,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
#[serde(rename_all = "lowercase")]
-pub struct ApplepayData {
+pub struct ApplepaySessionTokenResponse {
/// Session object for Apple Pay
- pub session_object: ApplePaySessionObject,
+ pub session_token_data: ApplePaySessionResponse,
/// Payment request object for Apple Pay
- pub payment_request_object: ApplePayRequest,
+ pub payment_request_data: ApplePayPaymentRequest,
}
#[derive(Debug, Clone, serde::Serialize, ToSchema, serde::Deserialize)]
-pub struct ApplePaySessionObject {
+pub struct ApplePaySessionResponse {
/// Timestamp at which session is requested
pub epoch_timestamp: u64,
/// Timestamp at which session expires
pub expires_at: u64,
/// The identifier for the merchant session
pub merchant_session_identifier: String,
- /// Applepay generates unique ID (UUID) value
+ /// Apple pay generated unique ID (UUID) value
pub nonce: String,
/// The identifier for the merchant
pub merchant_identifier: String,
@@ -1168,7 +1072,7 @@ pub struct ApplePaySessionObject {
}
#[derive(Debug, Clone, serde::Serialize, ToSchema, serde::Deserialize)]
-pub struct ApplePayRequest {
+pub struct ApplePayPaymentRequest {
/// The code for country
pub country_code: String,
/// The code for currency
@@ -1183,11 +1087,11 @@ pub struct ApplePayRequest {
#[derive(Debug, Clone, serde::Serialize, ToSchema, serde::Deserialize)]
pub struct AmountInfo {
- /// the label must be non-empty to pass validation.
+ /// The label must be the name of the merchant.
pub label: String,
- /// The type of label
+ /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending.
#[serde(rename = "type")]
- pub label_type: String,
+ pub total_type: String,
/// The total amount for the payment
pub amount: String,
}
diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml
index 5ab2eb69870..4d7982f8d0f 100644
--- a/crates/common_utils/Cargo.toml
+++ b/crates/common_utils/Cargo.toml
@@ -26,6 +26,7 @@ signal-hook = "0.3.14"
tokio = { version = "1.25.0", features = ["macros", "rt-multi-thread"] }
thiserror = "1.0.38"
time = { version = "0.3.17", features = ["serde", "serde-well-known", "std"] }
+md5 = "0.7.0"
# First party crates
masking = { version = "0.1.0", path = "../masking" }
diff --git a/crates/common_utils/src/crypto.rs b/crates/common_utils/src/crypto.rs
index d63aed438cf..87eb99ce15e 100644
--- a/crates/common_utils/src/crypto.rs
+++ b/crates/common_utils/src/crypto.rs
@@ -1,5 +1,6 @@
//! Utilities for cryptographic algorithms
use error_stack::{IntoReport, ResultExt};
+use md5;
use ring::{aead, hmac};
use crate::errors::{self, CustomResult};
@@ -219,6 +220,10 @@ impl DecodeMessage for GcmAes256 {
#[derive(Debug)]
pub struct Sha512;
+/// Secure Hash Algorithm 256
+#[derive(Debug)]
+pub struct Sha256;
+
/// Trait for generating a digest for SHA
pub trait GenerateDigest {
/// takes a message and creates a digest for it
@@ -231,6 +236,37 @@ impl GenerateDigest for Sha512 {
Ok(digest.as_ref().to_vec())
}
}
+/// MD5 hash function
+#[derive(Debug)]
+pub struct Md5;
+
+impl GenerateDigest for Md5 {
+ fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> {
+ let digest = md5::compute(message);
+ Ok(digest.as_ref().to_vec())
+ }
+}
+
+impl VerifySignature for Md5 {
+ fn verify_signature(
+ &self,
+ _secret: &[u8],
+ signature: &[u8],
+ msg: &[u8],
+ ) -> CustomResult<bool, errors::CryptoError> {
+ let hashed_digest = Self
+ .generate_digest(msg)
+ .change_context(errors::CryptoError::SignatureVerificationFailed)?;
+ Ok(hashed_digest == signature)
+ }
+}
+
+impl GenerateDigest for Sha256 {
+ fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> {
+ let digest = ring::digest::digest(&ring::digest::SHA256, message);
+ Ok(digest.as_ref().to_vec())
+ }
+}
/// Generate a random string using a cryptographically secure pseudo-random number generator
/// (CSPRNG). Typically used for generating (readable) keys and passwords.
@@ -256,6 +292,7 @@ pub fn generate_cryptographically_secure_random_bytes<const N: usize>() -> [u8;
mod crypto_tests {
#![allow(clippy::expect_used)]
use super::{DecodeMessage, EncodeMessage, SignMessage, VerifySignature};
+ use crate::crypto::GenerateDigest;
#[test]
fn test_hmac_sha256_sign_message() {
@@ -387,4 +424,39 @@ mod crypto_tests {
assert!(err_decoded.is_err());
}
+
+ #[test]
+ fn test_md5_digest() {
+ let message = "abcdefghijklmnopqrstuvwxyz".as_bytes();
+ assert_eq!(
+ format!(
+ "{}",
+ hex::encode(super::Md5.generate_digest(message).expect("Digest"))
+ ),
+ "c3fcd3d76192e4007dfb496cca67e13b"
+ );
+ }
+
+ #[test]
+ fn test_md5_verify_signature() {
+ let right_signature =
+ hex::decode("c3fcd3d76192e4007dfb496cca67e13b").expect("signature decoding");
+ let wrong_signature =
+ hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f")
+ .expect("Wrong signature decoding");
+ let secret = "".as_bytes();
+ let data = "abcdefghijklmnopqrstuvwxyz".as_bytes();
+
+ let right_verified = super::Md5
+ .verify_signature(secret, &right_signature, data)
+ .expect("Right signature verification result");
+
+ assert!(right_verified);
+
+ let wrong_verified = super::Md5
+ .verify_signature(secret, &wrong_signature, data)
+ .expect("Wrong signature verification result");
+
+ assert!(!wrong_verified);
+ }
}
diff --git a/crates/common_utils/src/lib.rs b/crates/common_utils/src/lib.rs
index b64ad922ef9..6ec1856e960 100644
--- a/crates/common_utils/src/lib.rs
+++ b/crates/common_utils/src/lib.rs
@@ -49,6 +49,28 @@ pub mod date_time {
(result, start.elapsed().as_seconds_f64() * 1000f64)
}
+ /// Prefix the date field with zero if it has single digit Eg: 1 -> 01
+ fn prefix_zero(input: u8) -> String {
+ if input < 10 {
+ return "0".to_owned() + input.to_string().as_str();
+ }
+ input.to_string()
+ }
+
+ /// Return the current date and time in UTC with the format YYYYMMDDHHmmss Eg: 20191105081132
+ pub fn date_as_yyyymmddhhmmss() -> String {
+ let now = OffsetDateTime::now_utc();
+ format!(
+ "{}{}{}{}{}{}",
+ now.year(),
+ prefix_zero(u8::from(now.month())),
+ prefix_zero(now.day()),
+ prefix_zero(now.hour()),
+ prefix_zero(now.minute()),
+ prefix_zero(now.second())
+ )
+ }
+
/// Return the current date and time in UTC with the format [year]-[month]-[day]T[hour]:[minute]:[second].mmmZ Eg: 2023-02-15T13:33:18.898Z
pub fn date_as_yyyymmddthhmmssmmmz() -> Result<String, time::error::Format> {
const ISO_CONFIG: EncodedConfig = Config::DEFAULT
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index f031f2e738f..cc6c5ba5e01 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -166,8 +166,20 @@ pub enum StripeErrorCode {
},
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The mandate information is invalid. {message}")]
PaymentIntentMandateInvalid { message: String },
+
#[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "The payment with the specified payment_id '{payment_id}' already exists in our records.")]
DuplicatePayment { payment_id: String },
+
+ #[error(error_type = StripeErrorType::ConnectorError, code = "", message = "{code}: {message}")]
+ ExternalConnectorError {
+ code: String,
+ message: String,
+ connector: String,
+ status_code: u16,
+ },
+
+ #[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "The connector provided in the request is incorrect or not available")]
+ IncorrectConnectorNameGiven,
// [#216]: https://github.com/juspay/hyperswitch/issues/216
// Implement the remaining stripe error codes
@@ -323,6 +335,8 @@ pub enum StripeErrorType {
ApiError,
CardError,
InvalidRequestError,
+ ConnectorError,
+ HyperswitchError,
}
impl From<errors::ApiErrorResponse> for StripeErrorCode {
@@ -369,8 +383,21 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
errors::ApiErrorResponse::RefundFailed { data } => Self::RefundFailed, // Nothing at stripe to map
errors::ApiErrorResponse::InternalServerError => Self::InternalServerError, // not a stripe code
- errors::ApiErrorResponse::ExternalConnectorError { .. } => Self::InternalServerError,
- errors::ApiErrorResponse::IncorrectConnectorNameGiven => Self::InternalServerError,
+ errors::ApiErrorResponse::ExternalConnectorError {
+ code,
+ message,
+ connector,
+ status_code,
+ ..
+ } => Self::ExternalConnectorError {
+ code,
+ message,
+ connector,
+ status_code,
+ },
+ errors::ApiErrorResponse::IncorrectConnectorNameGiven => {
+ Self::IncorrectConnectorNameGiven
+ }
errors::ApiErrorResponse::MandateActive => Self::MandateActive, //not a stripe code
errors::ApiErrorResponse::CustomerRedacted => Self::CustomerRedacted, //not a stripe code
errors::ApiErrorResponse::ConfigNotFound => Self::ConfigNotFound, // not a stripe code
@@ -474,12 +501,16 @@ impl actix_web::ResponseError for StripeErrorCode {
| Self::ResourceIdNotFound
| Self::PaymentIntentMandateInvalid { .. }
| Self::PaymentIntentUnexpectedState { .. }
- | Self::DuplicatePayment { .. } => StatusCode::BAD_REQUEST,
+ | Self::DuplicatePayment { .. }
+ | Self::IncorrectConnectorNameGiven => StatusCode::BAD_REQUEST,
Self::RefundFailed
| Self::InternalServerError
| Self::MandateActive
| Self::CustomerRedacted => StatusCode::INTERNAL_SERVER_ERROR,
Self::ReturnUrlUnavailable => StatusCode::SERVICE_UNAVAILABLE,
+ Self::ExternalConnectorError { status_code, .. } => {
+ StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
+ }
}
}
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index ee98ccc81be..f2e27ab3b95 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -116,7 +116,7 @@ impl From<Shipping> for payments::Address {
#[derive(PartialEq, Eq, Deserialize, Clone)]
pub struct StripePaymentIntentRequest {
pub amount: Option<i64>, //amount in cents, hence passed as integer
- pub connector: Option<api_enums::Connector>,
+ pub connector: Option<Vec<api_enums::Connector>>,
pub currency: Option<String>,
#[serde(rename = "amount_to_capture")]
pub amount_capturable: Option<i64>,
@@ -126,7 +126,7 @@ pub struct StripePaymentIntentRequest {
pub description: Option<String>,
pub payment_method_data: Option<StripePaymentMethodData>,
pub receipt_email: Option<pii::Secret<String, pii::Email>>,
- pub return_url: Option<String>,
+ pub return_url: Option<url::Url>,
pub setup_future_usage: Option<api_enums::FutureUsage>,
pub shipping: Option<Shipping>,
pub billing_details: Option<StripeBillingDetails>,
@@ -265,40 +265,110 @@ pub struct StripeCaptureRequest {
#[derive(Default, Eq, PartialEq, Serialize)]
pub struct StripePaymentIntentResponse {
pub id: Option<String>,
- pub object: String,
+ pub object: &'static str,
pub amount: i64,
pub amount_received: Option<i64>,
pub amount_capturable: Option<i64>,
pub currency: String,
pub status: StripePaymentStatus,
pub client_secret: Option<masking::Secret<String>>,
- #[serde(with = "common_utils::custom_serde::iso8601::option")]
- pub created: Option<time::PrimitiveDateTime>,
+ pub created: Option<i64>,
pub customer: Option<String>,
pub refunds: Option<Vec<refunds::RefundResponse>>,
pub mandate_id: Option<String>,
pub metadata: Option<Value>,
+ pub charges: Charges,
+ pub connector: Option<String>,
+ pub description: Option<String>,
+ pub mandate_data: Option<payments::MandateData>,
+ pub setup_future_usage: Option<api_models::enums::FutureUsage>,
+ pub off_session: Option<bool>,
+ pub return_url: Option<String>,
+ pub authentication_type: Option<api_models::enums::AuthenticationType>,
+ pub next_action: Option<payments::NextAction>,
+ pub cancellation_reason: Option<String>,
+ pub payment_method: Option<api_models::enums::PaymentMethodType>,
+ pub payment_method_data: Option<payments::PaymentMethodDataResponse>,
+ pub shipping: Option<payments::Address>,
+ pub billing: Option<payments::Address>,
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub capture_on: Option<time::PrimitiveDateTime>,
+ pub payment_token: Option<String>,
+ pub email: Option<masking::Secret<String, common_utils::pii::Email>>,
+ pub phone: Option<masking::Secret<String>>,
+ pub error_code: Option<String>,
+ pub error_message: Option<String>,
+ pub statement_descriptor_suffix: Option<String>,
+ pub statement_descriptor_name: Option<String>,
+ pub capture_method: Option<api_models::enums::CaptureMethod>,
+ pub name: Option<masking::Secret<String>>,
}
impl From<payments::PaymentsResponse> for StripePaymentIntentResponse {
fn from(resp: payments::PaymentsResponse) -> Self {
Self {
- object: "payment_intent".to_owned(),
+ object: "payment_intent",
+ id: resp.payment_id,
+ status: StripePaymentStatus::from(resp.status),
amount: resp.amount,
- amount_received: resp.amount_received,
amount_capturable: resp.amount_capturable,
- currency: resp.currency.to_lowercase(),
- status: StripePaymentStatus::from(resp.status),
+ amount_received: resp.amount_received,
+ connector: resp.connector,
client_secret: resp.client_secret,
- created: resp.created,
+ created: resp.created.map(|t| t.assume_utc().unix_timestamp()),
+ currency: resp.currency.to_lowercase(),
customer: resp.customer_id,
- id: resp.payment_id,
+ description: resp.description,
refunds: resp.refunds,
mandate_id: resp.mandate_id,
+ mandate_data: resp.mandate_data,
+ setup_future_usage: resp.setup_future_usage,
+ off_session: resp.off_session,
+ capture_on: resp.capture_on,
+ capture_method: resp.capture_method,
+ payment_method: resp.payment_method,
+ payment_method_data: resp.payment_method_data,
+ payment_token: resp.payment_token,
+ shipping: resp.shipping,
+ billing: resp.billing,
+ email: resp.email,
+ name: resp.name,
+ phone: resp.phone,
+ return_url: resp.return_url,
+ authentication_type: resp.authentication_type,
+ statement_descriptor_name: resp.statement_descriptor_name,
+ statement_descriptor_suffix: resp.statement_descriptor_suffix,
+ next_action: resp.next_action,
+ cancellation_reason: resp.cancellation_reason,
+ error_code: resp.error_code,
+ error_message: resp.error_message,
metadata: resp.metadata,
+ charges: Charges::new(),
}
}
}
+
+#[derive(Default, Eq, PartialEq, Serialize)]
+pub struct Charges {
+ object: &'static str,
+ data: Vec<String>,
+ has_more: bool,
+ total_count: i32,
+ url: String,
+}
+
+impl Charges {
+ fn new() -> Self {
+ Self {
+ object: "list",
+ data: vec![],
+ has_more: false,
+ total_count: 0,
+ url: "http://placeholder".to_string(),
+ }
+ }
+}
+
#[derive(Clone, Debug, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct StripePaymentListConstraints {
diff --git a/crates/router/src/compatibility/stripe/refunds/types.rs b/crates/router/src/compatibility/stripe/refunds/types.rs
index fe0cf423257..1b74795a1dd 100644
--- a/crates/router/src/compatibility/stripe/refunds/types.rs
+++ b/crates/router/src/compatibility/stripe/refunds/types.rs
@@ -2,7 +2,7 @@ use std::{convert::From, default::Default};
use serde::{Deserialize, Serialize};
-use crate::types::api::refunds;
+use crate::{core::errors, types::api::refunds};
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct StripeCreateRefundRequest {
@@ -23,6 +23,8 @@ pub struct StripeCreateRefundResponse {
pub currency: String,
pub payment_intent: String,
pub status: StripeRefundStatus,
+ pub created: Option<i64>,
+ pub metadata: serde_json::Value,
}
#[derive(Clone, Serialize, Deserialize, Eq, PartialEq)]
@@ -40,6 +42,7 @@ impl From<StripeCreateRefundRequest> for refunds::RefundRequest {
amount: req.amount,
payment_id: req.payment_intent,
reason: req.reason,
+ refund_type: Some(refunds::RefundType::Instant),
..Default::default()
}
}
@@ -65,14 +68,17 @@ impl From<refunds::RefundStatus> for StripeRefundStatus {
}
}
-impl From<refunds::RefundResponse> for StripeCreateRefundResponse {
- fn from(res: refunds::RefundResponse) -> Self {
- Self {
+impl TryFrom<refunds::RefundResponse> for StripeCreateRefundResponse {
+ type Error = error_stack::Report<errors::ApiErrorResponse>;
+ fn try_from(res: refunds::RefundResponse) -> Result<Self, Self::Error> {
+ Ok(Self {
id: res.refund_id,
amount: res.amount,
currency: res.currency.to_ascii_lowercase(),
payment_intent: res.payment_id,
status: res.status.into(),
- }
+ created: res.created_at.map(|t| t.assume_utc().unix_timestamp()),
+ metadata: res.metadata.unwrap_or(serde_json::json!({})),
+ })
}
}
diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs
index f296e06826b..7fe3110016c 100644
--- a/crates/router/src/compatibility/stripe/setup_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs
@@ -116,7 +116,7 @@ pub struct StripeSetupIntentRequest {
pub description: Option<String>,
pub payment_method_data: Option<StripePaymentMethodData>,
pub receipt_email: Option<pii::Secret<String, pii::Email>>,
- pub return_url: Option<String>,
+ pub return_url: Option<url::Url>,
pub setup_future_usage: Option<api_enums::FutureUsage>,
pub shipping: Option<Shipping>,
pub billing_details: Option<StripeBillingDetails>,
diff --git a/crates/router/src/compatibility/wrap.rs b/crates/router/src/compatibility/wrap.rs
index 5452ebdc6fe..69ca3c5272f 100644
--- a/crates/router/src/compatibility/wrap.rs
+++ b/crates/router/src/compatibility/wrap.rs
@@ -23,7 +23,7 @@ where
F: Fn(&'b A, U, T) -> Fut,
Fut: Future<Output = RouterResult<api::ApplicationResponse<Q>>>,
Q: Serialize + std::fmt::Debug + 'a,
- S: From<Q> + Serialize,
+ S: TryFrom<Q> + Serialize,
E: Serialize + error_stack::Context + actix_web::ResponseError + Clone,
errors::ApiErrorResponse: ErrorSwitch<E>,
T: std::fmt::Debug,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 6ca18641287..e6ba7a8c2fb 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -137,8 +137,10 @@ pub struct SupportedConnectors {
pub struct Connectors {
pub aci: ConnectorParams,
pub adyen: ConnectorParams,
+ pub airwallex: ConnectorParams,
pub applepay: ConnectorParams,
pub authorizedotnet: ConnectorParams,
+ pub bluesnap: ConnectorParams,
pub braintree: ConnectorParams,
pub checkout: ConnectorParams,
pub cybersource: ConnectorParams,
@@ -146,6 +148,7 @@ pub struct Connectors {
pub fiserv: ConnectorParams,
pub globalpay: ConnectorParams,
pub klarna: ConnectorParams,
+ pub nuvei: ConnectorParams,
pub payu: ConnectorParams,
pub rapyd: ConnectorParams,
pub shift4: ConnectorParams,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 9a4d99049bf..a95930a58e3 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -1,13 +1,16 @@
pub mod aci;
pub mod adyen;
+pub mod airwallex;
pub mod applepay;
pub mod authorizedotnet;
+pub mod bluesnap;
pub mod braintree;
pub mod checkout;
pub mod cybersource;
pub mod fiserv;
pub mod globalpay;
pub mod klarna;
+pub mod nuvei;
pub mod payu;
pub mod rapyd;
pub mod shift4;
@@ -19,8 +22,9 @@ pub mod worldpay;
pub mod dlocal;
pub use self::{
- aci::Aci, adyen::Adyen, applepay::Applepay, authorizedotnet::Authorizedotnet,
- braintree::Braintree, checkout::Checkout, cybersource::Cybersource, dlocal::Dlocal,
- fiserv::Fiserv, globalpay::Globalpay, klarna::Klarna, payu::Payu, rapyd::Rapyd, shift4::Shift4,
- stripe::Stripe, worldline::Worldline, worldpay::Worldpay,
+ aci::Aci, adyen::Adyen, airwallex::Airwallex, applepay::Applepay,
+ authorizedotnet::Authorizedotnet, bluesnap::Bluesnap, braintree::Braintree, checkout::Checkout,
+ cybersource::Cybersource, dlocal::Dlocal, fiserv::Fiserv, globalpay::Globalpay, klarna::Klarna,
+ nuvei::Nuvei, payu::Payu, rapyd::Rapyd, shift4::Shift4, stripe::Stripe, worldline::Worldline,
+ worldpay::Worldpay,
};
diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs
new file mode 100644
index 00000000000..fdd66013481
--- /dev/null
+++ b/crates/router/src/connector/airwallex.rs
@@ -0,0 +1,916 @@
+mod transformers;
+
+use std::fmt::Debug;
+
+use common_utils::ext_traits::ByteSliceExt;
+use error_stack::{IntoReport, ResultExt};
+use transformers as airwallex;
+
+use super::utils::{AccessTokenRequestInfo, RefundsRequestData};
+use crate::{
+ configs::settings,
+ core::{
+ errors::{self, CustomResult},
+ payments,
+ },
+ db::StorageInterface,
+ headers, logger, routes,
+ services::{self, ConnectorIntegration},
+ types::{
+ self,
+ api::{self, ConnectorCommon, ConnectorCommonExt},
+ ErrorResponse, Response, RouterData,
+ },
+ utils::{self, crypto, BytesExt},
+};
+
+#[derive(Debug, Clone)]
+pub struct Airwallex;
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Airwallex
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ let mut headers = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string(),
+ )];
+ let access_token = req
+ .access_token
+ .clone()
+ .ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
+
+ let auth_header = (
+ headers::AUTHORIZATION.to_string(),
+ format!("Bearer {}", access_token.token),
+ );
+
+ headers.push(auth_header);
+ Ok(headers)
+ }
+}
+
+impl ConnectorCommon for Airwallex {
+ fn id(&self) -> &'static str {
+ "airwallex"
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.airwallex.base_url.as_ref()
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ logger::debug!(payu_error_response=?res);
+ let response: airwallex::AirwallexErrorResponse = res
+ .response
+ .parse_struct("Airwallex ErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.code,
+ message: response.message,
+ reason: response.source,
+ })
+ }
+}
+
+impl api::Payment for Airwallex {}
+
+impl api::PreVerify for Airwallex {}
+impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>
+ for Airwallex
+{
+}
+
+impl api::ConnectorAccessToken for Airwallex {}
+
+impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+ for Airwallex
+{
+ fn get_url(
+ &self,
+ _req: &types::RefreshTokenRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}",
+ self.base_url(connectors),
+ "api/v1/authentication/login"
+ ))
+ }
+
+ fn get_headers(
+ &self,
+ req: &types::RefreshTokenRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ let headers = vec![
+ (headers::X_API_KEY.to_string(), req.request.app_id.clone()),
+ ("Content-Length".to_string(), "0".to_string()),
+ ("x-client-id".to_string(), req.get_request_id()?),
+ ];
+ Ok(headers)
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefreshTokenRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let req = Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .headers(types::RefreshTokenType::get_headers(self, req, connectors)?)
+ .url(&types::RefreshTokenType::get_url(self, req, connectors)?)
+ .body(types::RefreshTokenType::get_request_body(self, req)?)
+ .build(),
+ );
+ logger::debug!(payu_access_token_request=?req);
+ Ok(req)
+ }
+ fn handle_response(
+ &self,
+ data: &types::RefreshTokenRouterData,
+ res: Response,
+ ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> {
+ logger::debug!(access_token_response=?res);
+ let response: airwallex::AirwallexAuthUpdateResponse = res
+ .response
+ .parse_struct("airwallex AirwallexAuthUpdateResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ logger::debug!(access_token_error_response=?res);
+ self.build_error_response(res)
+ }
+}
+
+impl
+ ConnectorIntegration<
+ api::AuthorizeSessionToken,
+ types::AuthorizeSessionTokenData,
+ types::PaymentsResponseData,
+ > for Airwallex
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsAuthorizeSessionTokenRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsAuthorizeSessionTokenRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}",
+ self.base_url(connectors),
+ "api/v1/pa/payment_intents/create"
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsAuthorizeSessionTokenRouterData,
+ ) -> CustomResult<Option<String>, 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)?;
+ Ok(Some(req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsAuthorizeSessionTokenRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsPreAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .headers(types::PaymentsPreAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsPreAuthorizeType::get_request_body(
+ self, req,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RouterData<
+ api::AuthorizeSessionToken,
+ types::AuthorizeSessionTokenData,
+ types::PaymentsResponseData,
+ >,
+ res: Response,
+ ) -> CustomResult<
+ RouterData<
+ api::AuthorizeSessionToken,
+ types::AuthorizeSessionTokenData,
+ types::PaymentsResponseData,
+ >,
+ errors::ConnectorError,
+ >
+ where
+ api::AuthorizeSessionToken: Clone,
+ types::AuthorizeSessionTokenData: Clone,
+ types::PaymentsResponseData: Clone,
+ {
+ let response: airwallex::AirwallexPaymentsResponse = res
+ .response
+ .parse_struct("airwallex AirwallexPaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ logger::debug!(nuvei_session_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: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl api::PaymentAuthorize for Airwallex {}
+
+#[async_trait::async_trait]
+impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ for Airwallex
+{
+ async fn execute_pretasks(
+ &self,
+ router_data: &mut types::PaymentsAuthorizeRouterData,
+ app_state: &routes::AppState,
+ ) -> CustomResult<(), errors::ConnectorError> {
+ let integ: Box<
+ &(dyn ConnectorIntegration<
+ api::AuthorizeSessionToken,
+ types::AuthorizeSessionTokenData,
+ types::PaymentsResponseData,
+ > + Send
+ + Sync
+ + 'static),
+ > = Box::new(&Self);
+ let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::from(&router_data);
+ let resp = services::execute_connector_processing_step(
+ app_state,
+ integ,
+ authorize_data,
+ payments::CallConnectorAction::Trigger,
+ )
+ .await?;
+ router_data.reference_id = resp.reference_id;
+ Ok(())
+ }
+
+ fn get_headers(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}{}{}",
+ self.base_url(connectors),
+ "api/v1/pa/payment_intents/",
+ req.reference_id
+ .clone()
+ .ok_or(errors::ConnectorError::MissingConnectorTransactionID)?,
+ "/confirm"
+ ))
+ }
+
+ 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)?;
+ Ok(Some(airwallex_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsAuthorizeType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsAuthorizeRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: airwallex::AirwallexPaymentsResponse = res
+ .response
+ .parse_struct("AirwallexPaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ logger::debug!(airwallexpayments_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: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl api::PaymentSync for Airwallex {}
+impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+ for Airwallex
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let connector_payment_id = req
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
+ Ok(format!(
+ "{}{}{}",
+ self.base_url(connectors),
+ "api/v1/pa/payment_intents/",
+ connector_payment_id,
+ ))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Get)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsSyncRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ logger::debug!(payment_sync_response=?res);
+ let response: airwallex::AirwallexPaymentsResponse = res
+ .response
+ .parse_struct("airwallex PaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl api::PaymentCapture for Airwallex {}
+impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
+ for Airwallex
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}{}{}",
+ self.base_url(connectors),
+ "api/v1/pa/payment_intents/",
+ req.request.connector_transaction_id,
+ "/capture"
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ ) -> CustomResult<Option<String>, 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)?;
+ Ok(Some(airwallex_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsCaptureType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCaptureRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: airwallex::AirwallexPaymentsResponse = res
+ .response
+ .parse_struct("Airwallex PaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ logger::debug!(airwallexpayments_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: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl api::PaymentSession for Airwallex {}
+
+impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
+ for Airwallex
+{
+ //TODO: implement sessions flow
+}
+
+impl api::PaymentVoid for Airwallex {}
+
+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
+ for Airwallex
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}{}{}",
+ self.base_url(connectors),
+ "api/v1/pa/payment_intents/",
+ req.request.connector_transaction_id,
+ "/cancel"
+ ))
+ }
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ ) -> CustomResult<Option<String>, 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)?;
+ Ok(Some(airwallex_req))
+ }
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCancelRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ let response: airwallex::AirwallexPaymentsResponse = res
+ .response
+ .parse_struct("Airwallex PaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ logger::debug!(airwallexpayments_create_response=?response);
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
+ .body(types::PaymentsVoidType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl api::Refund for Airwallex {}
+impl api::RefundExecute for Airwallex {}
+impl api::RefundSync for Airwallex {}
+
+impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
+ for Airwallex
+{
+ fn get_headers(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}",
+ self.base_url(connectors),
+ "api/v1/pa/refunds/create"
+ ))
+ }
+
+ 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)?;
+ Ok(Some(airwallex_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::RefundExecuteType::get_request_body(self, req)?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundsRouterData<api::Execute>,
+ res: Response,
+ ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ logger::debug!(target: "router::connector::airwallex", response=?res);
+ let response: airwallex::RefundResponse = res
+ .response
+ .parse_struct("airwallex RefundResponse")
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
+ for Airwallex
+{
+ fn get_headers(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}{}",
+ self.base_url(connectors),
+ "/api/v1/pa/refunds/",
+ req.request.get_connector_refund_id()?
+ ))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Get)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .body(types::RefundSyncType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundSyncRouterData,
+ res: Response,
+ ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ logger::debug!(target: "router::connector::airwallex", response=?res);
+ let response: airwallex::RefundResponse = res
+ .response
+ .parse_struct("airwallex RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+#[async_trait::async_trait]
+impl api::IncomingWebhook for Airwallex {
+ fn get_webhook_source_verification_algorithm(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
+ Ok(Box::new(crypto::HmacSha256))
+ }
+
+ fn get_webhook_source_verification_signature(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let security_header = request
+ .headers
+ .get("x-signature")
+ .map(|header_value| {
+ header_value
+ .to_str()
+ .map(String::from)
+ .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)
+ .into_report()
+ })
+ .ok_or(errors::ConnectorError::WebhookSignatureNotFound)
+ .into_report()??;
+
+ hex::decode(security_header)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSignatureNotFound)
+ }
+
+ fn get_webhook_source_verification_message(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ _merchant_id: &str,
+ _secret: &[u8],
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let timestamp = request
+ .headers
+ .get("x-timestamp")
+ .map(|header_value| {
+ header_value
+ .to_str()
+ .map(String::from)
+ .map_err(|_| errors::ConnectorError::WebhookSignatureNotFound)
+ .into_report()
+ })
+ .ok_or(errors::ConnectorError::WebhookSignatureNotFound)
+ .into_report()??;
+
+ Ok(format!("{}{}", timestamp, String::from_utf8_lossy(request.body)).into_bytes())
+ }
+
+ async fn get_webhook_source_verification_merchant_secret(
+ &self,
+ db: &dyn StorageInterface,
+ merchant_id: &str,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let key = format!("whsec_verification_{}_{}", self.id(), merchant_id);
+ let secret = db
+ .find_config_by_key(&key)
+ .await
+ .change_context(errors::ConnectorError::WebhookVerificationSecretNotFound)?;
+ Ok(secret.config.into_bytes())
+ }
+
+ fn get_webhook_object_reference_id(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let details: airwallex::AirwallexWebhookData = request
+ .body
+ .parse_struct("airwallexWebhookData")
+ .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+
+ Ok(details.source_id)
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ let details: airwallex::AirwallexWebhookData = request
+ .body
+ .parse_struct("airwallexWebhookData")
+ .change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
+
+ Ok(match details.name.as_str() {
+ "payment_attempt.failed_to_process" => api::IncomingWebhookEvent::PaymentIntentFailure,
+ "payment_attempt.authorized" => api::IncomingWebhookEvent::PaymentIntentSuccess,
+ _ => Err(errors::ConnectorError::WebhookEventTypeNotFound).into_report()?,
+ })
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<serde_json::Value, errors::ConnectorError> {
+ let details: airwallex::AirwallexWebhookObjectResource = request
+ .body
+ .parse_struct("AirwallexWebhookObjectResource")
+ .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
+
+ Ok(details.data.object)
+ }
+}
+
+impl services::ConnectorRedirectResponse for Airwallex {
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ Ok(payments::CallConnectorAction::Trigger)
+ }
+}
diff --git a/crates/router/src/connector/airwallex/transformers.rs b/crates/router/src/connector/airwallex/transformers.rs
new file mode 100644
index 00000000000..97e876bd091
--- /dev/null
+++ b/crates/router/src/connector/airwallex/transformers.rs
@@ -0,0 +1,386 @@
+use serde::{Deserialize, Serialize};
+use time::PrimitiveDateTime;
+use url::Url;
+use uuid::Uuid;
+
+use crate::{
+ core::errors,
+ pii::{self, Secret},
+ services,
+ types::{self, api, storage::enums},
+};
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct AirwallexIntentRequest {
+ // Unique ID to be sent for each transaction/operation request to the connector
+ request_id: String,
+ amount: i64,
+ currency: enums::Currency,
+ //ID created in merchant's order system that corresponds to this PaymentIntent.
+ merchant_order_id: String,
+}
+impl TryFrom<&types::PaymentsAuthorizeSessionTokenRouterData> for AirwallexIntentRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &types::PaymentsAuthorizeSessionTokenRouterData,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ request_id: Uuid::new_v4().to_string(),
+ amount: item.request.amount,
+ currency: item.request.currency,
+ merchant_order_id: item.payment_id.clone(),
+ })
+ }
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct AirwallexPaymentsRequest {
+ // Unique ID to be sent for each transaction/operation request to the connector
+ request_id: String,
+ payment_method: AirwallexPaymentMethod,
+ payment_method_options: Option<AirwallexPaymentOptions>,
+ return_url: Option<String>,
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+#[serde(untagged)]
+pub enum AirwallexPaymentMethod {
+ Card(AirwallexCard),
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct AirwallexCard {
+ card: AirwallexCardDetails,
+ #[serde(rename = "type")]
+ payment_method_type: AirwallexPaymentType,
+}
+#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct AirwallexCardDetails {
+ expiry_month: Secret<String>,
+ expiry_year: Secret<String>,
+ number: Secret<String, pii::CardNumber>,
+ cvc: Secret<String>,
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum AirwallexPaymentType {
+ Card,
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum AirwallexPaymentOptions {
+ Card(AirwallexCardPaymentOptions),
+}
+#[derive(Debug, Serialize, Eq, PartialEq)]
+pub struct AirwallexCardPaymentOptions {
+ auto_capture: bool,
+}
+
+impl TryFrom<&types::PaymentsAuthorizeRouterData> for AirwallexPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ let mut payment_method_options = None;
+ let payment_method = match item.request.payment_method_data.clone() {
+ api::PaymentMethod::Card(ccard) => {
+ payment_method_options =
+ Some(AirwallexPaymentOptions::Card(AirwallexCardPaymentOptions {
+ auto_capture: matches!(
+ item.request.capture_method,
+ Some(enums::CaptureMethod::Automatic) | None
+ ),
+ }));
+ Ok(AirwallexPaymentMethod::Card(AirwallexCard {
+ card: AirwallexCardDetails {
+ number: ccard.card_number,
+ expiry_month: ccard.card_exp_month.clone(),
+ expiry_year: ccard.card_exp_year.clone(),
+ cvc: ccard.card_cvc,
+ },
+ payment_method_type: AirwallexPaymentType::Card,
+ }))
+ }
+ _ => Err(errors::ConnectorError::NotImplemented(
+ "Unknown payment method".to_string(),
+ )),
+ }?;
+ Ok(Self {
+ request_id: Uuid::new_v4().to_string(),
+ payment_method,
+ payment_method_options,
+ return_url: item.router_return_url.clone(),
+ })
+ }
+}
+
+#[derive(Deserialize)]
+pub struct AirwallexAuthUpdateResponse {
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ expires_at: PrimitiveDateTime,
+ token: String,
+}
+
+impl<F, T> TryFrom<types::ResponseRouterData<F, AirwallexAuthUpdateResponse, T, types::AccessToken>>
+ for types::RouterData<F, T, types::AccessToken>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, AirwallexAuthUpdateResponse, T, types::AccessToken>,
+ ) -> Result<Self, Self::Error> {
+ let expires = (item.response.expires_at - common_utils::date_time::now()).whole_seconds();
+ Ok(Self {
+ response: Ok(types::AccessToken {
+ token: item.response.token,
+ expires,
+ }),
+ ..item.data
+ })
+ }
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct AirwallexPaymentsCaptureRequest {
+ // Unique ID to be sent for each transaction/operation request to the connector
+ request_id: String,
+ amount: Option<i64>,
+}
+
+impl TryFrom<&types::PaymentsCaptureRouterData> for AirwallexPaymentsCaptureRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ request_id: Uuid::new_v4().to_string(),
+ amount: item.request.amount_to_capture,
+ })
+ }
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct AirwallexPaymentsCancelRequest {
+ // Unique ID to be sent for each transaction/operation request to the connector
+ request_id: String,
+ cancellation_reason: Option<String>,
+}
+
+impl TryFrom<&types::PaymentsCancelRouterData> for AirwallexPaymentsCancelRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ request_id: Uuid::new_v4().to_string(),
+ cancellation_reason: item.request.cancellation_reason.clone(),
+ })
+ }
+}
+
+// PaymentsResponse
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum AirwallexPaymentStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Pending,
+ RequiresPaymentMethod,
+ RequiresCustomerAction,
+ RequiresCapture,
+ Cancelled,
+}
+
+impl From<AirwallexPaymentStatus> for enums::AttemptStatus {
+ fn from(item: AirwallexPaymentStatus) -> Self {
+ match item {
+ AirwallexPaymentStatus::Succeeded => Self::Charged,
+ AirwallexPaymentStatus::Failed => Self::Failure,
+ AirwallexPaymentStatus::Pending => Self::Pending,
+ AirwallexPaymentStatus::RequiresPaymentMethod => Self::PaymentMethodAwaited,
+ AirwallexPaymentStatus::RequiresCustomerAction => Self::AuthenticationPending,
+ AirwallexPaymentStatus::RequiresCapture => Self::Authorized,
+ AirwallexPaymentStatus::Cancelled => Self::Voided,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct AirwallexRedirectFormData {
+ #[serde(rename = "JWT")]
+ jwt: String,
+ #[serde(rename = "threeDSMethodData")]
+ three_ds_method_data: String,
+ token: String,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct AirwallexPaymentsNextAction {
+ url: Url,
+ method: services::Method,
+ data: AirwallexRedirectFormData,
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct AirwallexPaymentsResponse {
+ status: AirwallexPaymentStatus,
+ //Unique identifier for the PaymentIntent
+ id: String,
+ amount: Option<i64>,
+ //ID of the PaymentConsent related to this PaymentIntent
+ payment_consent_id: Option<String>,
+ next_action: Option<AirwallexPaymentsNextAction>,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, AirwallexPaymentsResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ AirwallexPaymentsResponse,
+ T,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ let redirection_data =
+ item.response
+ .next_action
+ .map(|response_url_data| services::RedirectForm {
+ endpoint: response_url_data.url.to_string(),
+ method: response_url_data.method,
+ form_fields: std::collections::HashMap::from([
+ ("JWT".to_string(), response_url_data.data.jwt),
+ (
+ "threeDSMethodData".to_string(),
+ response_url_data.data.three_ds_method_data,
+ ),
+ ("token".to_string(), response_url_data.data.token),
+ ]),
+ });
+ Ok(Self {
+ status: enums::AttemptStatus::from(item.response.status),
+ reference_id: Some(item.response.id.clone()),
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ redirection_data,
+ mandate_reference: None,
+ connector_metadata: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct AirwallexRefundRequest {
+ // Unique ID to be sent for each transaction/operation request to the connector
+ request_id: String,
+ amount: Option<i64>,
+ reason: Option<String>,
+ //Identifier for the PaymentIntent for which Refund is requested
+ payment_intent_id: String,
+}
+
+impl<F> TryFrom<&types::RefundsRouterData<F>> for AirwallexRefundRequest {
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ request_id: Uuid::new_v4().to_string(),
+ amount: Some(item.request.refund_amount),
+ reason: item.request.reason.clone(),
+ payment_intent_id: item.request.connector_transaction_id.clone(),
+ })
+ }
+}
+
+// Type definition for Refund Response
+#[allow(dead_code)]
+#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+pub enum RefundStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Received,
+ Accepted,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Received | RefundStatus::Accepted => Self::Pending,
+ }
+ }
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct RefundResponse {
+ //A unique number that tags a credit or debit card transaction when it goes from the merchant's bank through to the cardholder's bank.
+ acquirer_reference_number: String,
+ amount: i64,
+ //Unique identifier for the Refund
+ id: String,
+ status: RefundStatus,
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
+ for types::RefundsRouterData<api::Execute>
+{
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ let refund_status = enums::RefundStatus::from(item.response.status);
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.id,
+ refund_status,
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
+ for types::RefundsRouterData<api::RSync>
+{
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ let refund_status = enums::RefundStatus::from(item.response.status);
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.id,
+ refund_status,
+ }),
+ ..item.data
+ })
+ }
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AirwallexWebhookData {
+ pub source_id: String,
+ pub name: String,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct AirwallexWebhookDataResource {
+ pub object: serde_json::Value,
+}
+
+#[derive(Debug, Deserialize)]
+pub struct AirwallexWebhookObjectResource {
+ pub data: AirwallexWebhookDataResource,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct AirwallexErrorResponse {
+ pub code: String,
+ pub message: String,
+ pub details: Option<Vec<String>>,
+ pub source: Option<String>,
+}
diff --git a/crates/router/src/connector/applepay.rs b/crates/router/src/connector/applepay.rs
index 791507fb576..a4570c5d13d 100644
--- a/crates/router/src/connector/applepay.rs
+++ b/crates/router/src/connector/applepay.rs
@@ -158,7 +158,7 @@ impl
data: &types::PaymentsSessionRouterData,
res: types::Response,
) -> CustomResult<types::PaymentsSessionRouterData, errors::ConnectorError> {
- let response: applepay::ApplepaySessionResponse = res
+ let response: applepay::ApplepaySessionTokenResponse = res
.response
.parse_struct("ApplepaySessionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -197,11 +197,11 @@ impl
.get_required_value("connector_meta_data")
.change_context(errors::ConnectorError::NoConnectorMetaData)?;
- let metadata: transformers::ApplePayMetaData = metadata
+ let metadata: transformers::ApplePayMetadata = metadata
.parse_value("ApplePayMetaData")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
- Ok(Some(metadata.session_object.certificate))
+ Ok(Some(metadata.session_token_data.certificate))
}
fn get_certificate_key(
@@ -214,11 +214,11 @@ impl
.get_required_value("connector_meta_data")
.change_context(errors::ConnectorError::NoConnectorMetaData)?;
- let metadata: transformers::ApplePayMetaData = metadata
+ let metadata: transformers::ApplePayMetadata = metadata
.parse_value("ApplePayMetaData")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
- Ok(Some(metadata.session_object.certificate_keys))
+ Ok(Some(metadata.session_token_data.certificate_keys))
}
}
diff --git a/crates/router/src/connector/applepay/transformers.rs b/crates/router/src/connector/applepay/transformers.rs
index 3488c2126eb..c3a756daf72 100644
--- a/crates/router/src/connector/applepay/transformers.rs
+++ b/crates/router/src/connector/applepay/transformers.rs
@@ -16,7 +16,7 @@ pub struct ApplepaySessionRequest {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
-pub struct ApplepaySessionResponse {
+pub struct ApplepaySessionTokenResponse {
pub epoch_timestamp: u64,
pub expires_at: u64,
pub merchant_session_identifier: String,
@@ -38,20 +38,20 @@ pub struct ErrorResponse {
}
#[derive(Debug, Default, Serialize, Deserialize)]
-pub struct ApplePayMetaData {
- pub payment_object: PaymentObjectMetaData,
- pub session_object: SessionObject,
+pub struct ApplePayMetadata {
+ pub payment_request_data: PaymentRequestMetadata,
+ pub session_token_data: SessionRequest,
}
#[derive(Debug, Default, Serialize, Deserialize)]
-pub struct PaymentObjectMetaData {
+pub struct PaymentRequestMetadata {
pub supported_networks: Vec<String>,
pub merchant_capabilities: Vec<String>,
pub label: String,
}
#[derive(Debug, Default, Serialize, Deserialize)]
-pub struct SessionObject {
+pub struct SessionRequest {
pub certificate: String,
pub certificate_keys: String,
pub merchant_identifier: String,
@@ -88,15 +88,15 @@ impl TryFrom<&types::PaymentsSessionRouterData> for ApplepaySessionRequest {
.get_required_value("connector_meta_data")
.change_context(errors::ConnectorError::NoConnectorMetaData)?;
- let metadata: ApplePayMetaData = metadata
- .parse_value("ApplePayMetaData")
+ let metadata: ApplePayMetadata = metadata
+ .parse_value("ApplePayMetadata")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(Self {
- merchant_identifier: metadata.session_object.merchant_identifier,
- display_name: metadata.session_object.display_name,
- initiative: metadata.session_object.initiative,
- initiative_context: metadata.session_object.initiative_context,
+ 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,
})
}
}
@@ -105,7 +105,7 @@ impl<F>
TryFrom<
types::ResponseRouterData<
F,
- ApplepaySessionResponse,
+ ApplepaySessionTokenResponse,
types::PaymentsSessionData,
types::PaymentsResponseData,
>,
@@ -115,7 +115,7 @@ impl<F>
fn try_from(
item: types::ResponseRouterData<
F,
- ApplepaySessionResponse,
+ ApplepaySessionTokenResponse,
types::PaymentsSessionData,
types::PaymentsResponseData,
>,
@@ -127,12 +127,12 @@ impl<F>
.get_required_value("connector_meta_data")
.change_context(errors::ConnectorError::NoConnectorMetaData)?;
- let metadata: ApplePayMetaData = metadata
- .parse_value("ApplePayMetaData")
+ let metadata: ApplePayMetadata = metadata
+ .parse_value("ApplePayMetadata")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let amount_info = AmountInfo {
- label: metadata.payment_object.label,
+ label: metadata.payment_request_data.label,
label_type: "final".to_string(),
amount: (item.data.request.amount / 100).to_string(),
};
@@ -149,12 +149,12 @@ impl<F>
})?,
currency_code: item.data.request.currency.to_string(),
total: amount_info,
- merchant_capabilities: metadata.payment_object.merchant_capabilities,
- supported_networks: metadata.payment_object.supported_networks,
- apple_pay_merchant_id: metadata.session_object.merchant_identifier,
+ 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_object = ApplepaySessionResponse {
+ let applepay_session = ApplepaySessionTokenResponse {
epoch_timestamp: item.response.epoch_timestamp,
expires_at: item.response.expires_at,
merchant_session_identifier: item.response.merchant_session_identifier,
@@ -171,10 +171,12 @@ impl<F>
Ok(Self {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: {
- api_models::payments::SessionToken::Applepay(Box::new(payments::ApplepayData {
- session_object: applepay_session_object.into(),
- payment_request_object: payment_request.into(),
- }))
+ api_models::payments::SessionToken::Applepay(Box::new(
+ payments::ApplepaySessionTokenResponse {
+ session_token_data: applepay_session.into(),
+ payment_request_data: payment_request.into(),
+ },
+ ))
},
}),
..item.data
@@ -182,7 +184,7 @@ impl<F>
}
}
-impl From<PaymentRequest> for payments::ApplePayRequest {
+impl From<PaymentRequest> for payments::ApplePayPaymentRequest {
fn from(value: PaymentRequest) -> Self {
Self {
country_code: value.country_code,
@@ -198,14 +200,14 @@ impl From<AmountInfo> for payments::AmountInfo {
fn from(value: AmountInfo) -> Self {
Self {
label: value.label,
- label_type: value.label_type,
+ total_type: value.label_type,
amount: value.amount,
}
}
}
-impl From<ApplepaySessionResponse> for payments::ApplePaySessionObject {
- fn from(value: ApplepaySessionResponse) -> Self {
+impl From<ApplepaySessionTokenResponse> for payments::ApplePaySessionResponse {
+ fn from(value: ApplepaySessionTokenResponse) -> Self {
Self {
epoch_timestamp: value.epoch_timestamp,
expires_at: value.expires_at,
diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs
new file mode 100644
index 00000000000..1f81aff9f79
--- /dev/null
+++ b/crates/router/src/connector/bluesnap.rs
@@ -0,0 +1,744 @@
+mod transformers;
+
+use std::fmt::Debug;
+
+use base64::Engine;
+use common_utils::crypto;
+use error_stack::{IntoReport, ResultExt};
+use transformers as bluesnap;
+
+use super::utils::RefundsRequestData;
+use crate::{
+ configs::settings,
+ consts,
+ core::{
+ errors::{self, CustomResult},
+ payments,
+ },
+ db::StorageInterface,
+ headers, logger,
+ services::{self, ConnectorIntegration},
+ types::{
+ self,
+ api::{self, ConnectorCommon, ConnectorCommonExt},
+ ErrorResponse, Response,
+ },
+ utils::{self, BytesExt},
+};
+
+#[derive(Debug, Clone)]
+pub struct Bluesnap;
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Bluesnap
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &types::RouterData<Flow, Request, Response>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ let mut header = self.get_auth_header(&req.connector_auth_type)?;
+ header.push((
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string(),
+ ));
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Bluesnap {
+ fn id(&self) -> &'static str {
+ "bluesnap"
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.bluesnap.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &types::ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ let auth: bluesnap::BluesnapAuthType = auth_type
+ .try_into()
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ let encoded_api_key =
+ consts::BASE64_ENGINE.encode(format!("{}:{}", auth.key1, auth.api_key));
+ Ok(vec![(
+ headers::AUTHORIZATION.to_string(),
+ format!("Basic {encoded_api_key}"),
+ )])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ logger::debug!(bluesnap_error_response=?res);
+ let response: bluesnap::BluesnapErrorResponse = res
+ .response
+ .parse_struct("BluesnapErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ let response_error_message = response.message.first().map_or(
+ ErrorResponse {
+ status_code: res.status_code,
+ code: consts::NO_ERROR_CODE.to_string(),
+ message: consts::NO_ERROR_MESSAGE.to_string(),
+ reason: None,
+ },
+ |error_response| ErrorResponse {
+ status_code: res.status_code,
+ code: error_response.code.clone(),
+ message: error_response.description.clone(),
+ reason: None,
+ },
+ );
+ Ok(response_error_message)
+ }
+}
+
+impl api::Payment for Bluesnap {}
+
+impl api::PreVerify for Bluesnap {}
+impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>
+ for Bluesnap
+{
+}
+
+impl api::PaymentVoid for Bluesnap {}
+
+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
+ for Bluesnap
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}",
+ self.base_url(connectors),
+ "services/2/transactions"
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let connector_req = bluesnap::BluesnapVoidRequest::try_from(req)?;
+ let bluesnap_req =
+ utils::Encode::<bluesnap::BluesnapVoidRequest>::encode_to_string_of_json(
+ &connector_req,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(bluesnap_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Put)
+ .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
+ .body(types::PaymentsVoidType::get_request_body(self, req)?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCancelRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ let response: bluesnap::BluesnapPaymentsResponse = res
+ .response
+ .parse_struct("BluesnapPaymentsResponse")
+ .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: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl api::ConnectorAccessToken for Bluesnap {}
+
+impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+ for Bluesnap
+{
+}
+
+impl api::PaymentSync for Bluesnap {}
+impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+ for Bluesnap
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let connector_payment_id = req
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
+ Ok(format!(
+ "{}{}{}",
+ self.base_url(connectors),
+ "services/2/transactions/",
+ connector_payment_id
+ ))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Get)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsSyncRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: bluesnap::BluesnapPaymentsResponse = res
+ .response
+ .parse_struct("BluesnapPaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+}
+
+impl api::PaymentCapture for Bluesnap {}
+impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
+ for Bluesnap
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}",
+ self.base_url(connectors),
+ "services/2/transactions"
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let connector_req = bluesnap::BluesnapCaptureRequest::try_from(req)?;
+ let bluesnap_req =
+ utils::Encode::<bluesnap::BluesnapCaptureRequest>::encode_to_string_of_json(
+ &connector_req,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(bluesnap_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Put)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsCaptureType::get_request_body(self, req)?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCaptureRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: bluesnap::BluesnapPaymentsResponse = res
+ .response
+ .parse_struct("Bluesnap BluesnapPaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: String = res
+ .response
+ .parse_struct("ErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ logger::debug!(bluesnap_error_response=?res);
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: consts::NO_ERROR_CODE.to_string(),
+ message: response,
+ reason: None,
+ })
+ }
+}
+
+impl api::PaymentSession for Bluesnap {}
+
+impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
+ for Bluesnap
+{
+ //TODO: implement sessions flow
+}
+
+impl api::PaymentAuthorize for Bluesnap {}
+
+impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ for Bluesnap
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}",
+ self.base_url(connectors),
+ "services/2/transactions"
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let connector_req = bluesnap::BluesnapPaymentsRequest::try_from(req)?;
+ let bluesnap_req =
+ utils::Encode::<bluesnap::BluesnapPaymentsRequest>::encode_to_string_of_json(
+ &connector_req,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(bluesnap_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsAuthorizeType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsAuthorizeRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: bluesnap::BluesnapPaymentsResponse = res
+ .response
+ .parse_struct("BluesnapPaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl api::Refund for Bluesnap {}
+impl api::RefundExecute for Bluesnap {}
+impl api::RefundSync for Bluesnap {}
+
+impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
+ for Bluesnap
+{
+ fn get_headers(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}{}",
+ self.base_url(connectors),
+ "services/2/transactions/refund/",
+ req.request.connector_transaction_id
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let connector_req = bluesnap::BluesnapRefundRequest::try_from(req)?;
+ let bluesnap_req =
+ utils::Encode::<bluesnap::BluesnapRefundRequest>::encode_to_string_of_json(
+ &connector_req,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(bluesnap_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::RefundExecuteType::get_request_body(self, req)?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundsRouterData<api::Execute>,
+ res: Response,
+ ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ let response: bluesnap::RefundResponse = res
+ .response
+ .parse_struct("bluesnap RefundResponse")
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Bluesnap {
+ fn get_headers(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}{}{}",
+ self.base_url(connectors),
+ "services/2/transactions/",
+ req.request.get_connector_refund_id()?
+ ))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundsRouterData<api::RSync>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Get)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundSyncRouterData,
+ res: Response,
+ ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ let response: bluesnap::BluesnapPaymentsResponse = res
+ .response
+ .parse_struct("bluesnap BluesnapPaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+#[async_trait::async_trait]
+impl api::IncomingWebhook for Bluesnap {
+ fn get_webhook_source_verification_algorithm(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
+ Ok(Box::new(crypto::Md5))
+ }
+
+ fn get_webhook_source_verification_signature(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let webhook_body: bluesnap::BluesnapWebhookBody =
+ serde_urlencoded::from_bytes(request.body)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
+ let signature = webhook_body.auth_key;
+ hex::decode(signature)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSignatureNotFound)
+ }
+ fn get_webhook_source_verification_message(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ _merchant_id: &str,
+ _secret: &[u8],
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let webhook_body: bluesnap::BluesnapWebhookBody =
+ serde_urlencoded::from_bytes(request.body)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
+ let msg = webhook_body.reference_number + &webhook_body.contract_id;
+ Ok(msg.into_bytes())
+ }
+
+ async fn get_webhook_source_verification_merchant_secret(
+ &self,
+ db: &dyn StorageInterface,
+ merchant_id: &str,
+ ) -> CustomResult<Vec<u8>, errors::ConnectorError> {
+ let key = format!("whsec_verification_{}_{}", self.id(), merchant_id);
+ let secret = db
+ .find_config_by_key(&key)
+ .await
+ .change_context(errors::ConnectorError::WebhookVerificationSecretNotFound)?;
+
+ Ok(secret.config.into_bytes())
+ }
+
+ async fn verify_webhook_source(
+ &self,
+ db: &dyn StorageInterface,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ merchant_id: &str,
+ ) -> CustomResult<bool, errors::ConnectorError> {
+ let algorithm = self
+ .get_webhook_source_verification_algorithm(request)
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
+
+ let signature = self
+ .get_webhook_source_verification_signature(request)
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
+ let mut secret = self
+ .get_webhook_source_verification_merchant_secret(db, merchant_id)
+ .await
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
+ let mut message = self
+ .get_webhook_source_verification_message(request, merchant_id, &secret)
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
+ message.append(&mut secret);
+ algorithm
+ .verify_signature(&secret, &signature, &message)
+ .change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
+ }
+
+ fn get_webhook_object_reference_id(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ let webhook_body: bluesnap::BluesnapWebhookBody =
+ serde_urlencoded::from_bytes(request.body)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
+ Ok(webhook_body.reference_number)
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ let details: bluesnap::BluesnapWebhookObjectEventType =
+ serde_urlencoded::from_bytes(request.body)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
+
+ Ok(match details.transaction_type.as_str() {
+ "DECLINE" | "CC_CHARGE_FAILED" => api::IncomingWebhookEvent::PaymentIntentFailure,
+ "CHARGE" => api::IncomingWebhookEvent::PaymentIntentSuccess,
+ _ => Err(errors::ConnectorError::WebhookEventTypeNotFound).into_report()?,
+ })
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<serde_json::Value, errors::ConnectorError> {
+ let details: bluesnap::BluesnapWebhookObjectResource =
+ serde_urlencoded::from_bytes(request.body)
+ .into_report()
+ .change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
+ let res_json =
+ utils::Encode::<transformers::BluesnapWebhookObjectResource>::encode_to_value(&details)
+ .change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
+
+ Ok(res_json)
+ }
+}
+
+impl services::ConnectorRedirectResponse for Bluesnap {
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ Ok(payments::CallConnectorAction::Trigger)
+ }
+}
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
new file mode 100644
index 00000000000..89c088e1c7f
--- /dev/null
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -0,0 +1,332 @@
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ core::errors,
+ pii::{self, Secret},
+ types::{
+ self, api,
+ storage::enums,
+ transformers::{self, ForeignTryFrom},
+ },
+};
+
+#[derive(Debug, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct BluesnapPaymentsRequest {
+ amount: i64,
+ #[serde(flatten)]
+ payment_method: PaymentMethodDetails,
+ currency: enums::Currency,
+ soft_descriptor: Option<String>,
+ card_transaction_type: BluesnapTxnType,
+}
+
+#[derive(Debug, Serialize, Eq, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub enum PaymentMethodDetails {
+ CreditCard(Card),
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct Card {
+ card_number: Secret<String, pii::CardNumber>,
+ expiration_month: Secret<String>,
+ expiration_year: Secret<String>,
+ security_code: Secret<String>,
+}
+
+impl TryFrom<&types::PaymentsAuthorizeRouterData> for BluesnapPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ let auth_mode = match item.request.capture_method {
+ Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly,
+ _ => BluesnapTxnType::AuthCapture,
+ };
+ let payment_method = match item.request.payment_method_data.clone() {
+ api::PaymentMethod::Card(ccard) => Ok(PaymentMethodDetails::CreditCard(Card {
+ card_number: ccard.card_number,
+ expiration_month: ccard.card_exp_month.clone(),
+ expiration_year: ccard.card_exp_year.clone(),
+ security_code: ccard.card_cvc,
+ })),
+ _ => Err(errors::ConnectorError::NotImplemented(
+ "payment method".to_string(),
+ )),
+ }?;
+ Ok(Self {
+ amount: item.request.amount,
+ payment_method,
+ currency: item.request.currency,
+ soft_descriptor: item.description.clone(),
+ card_transaction_type: auth_mode,
+ })
+ }
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct BluesnapVoidRequest {
+ card_transaction_type: BluesnapTxnType,
+ transaction_id: String,
+}
+
+impl TryFrom<&types::PaymentsCancelRouterData> for BluesnapVoidRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ let card_transaction_type = BluesnapTxnType::AuthReversal;
+ let transaction_id = item.request.connector_transaction_id.to_string();
+ Ok(Self {
+ card_transaction_type,
+ transaction_id,
+ })
+ }
+}
+
+#[derive(Debug, Serialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct BluesnapCaptureRequest {
+ card_transaction_type: BluesnapTxnType,
+ transaction_id: String,
+ amount: Option<i64>,
+}
+
+impl TryFrom<&types::PaymentsCaptureRouterData> for BluesnapCaptureRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ let card_transaction_type = BluesnapTxnType::Capture;
+ let transaction_id = item.request.connector_transaction_id.to_string();
+ Ok(Self {
+ card_transaction_type,
+ transaction_id,
+ amount: item.request.amount_to_capture,
+ })
+ }
+}
+
+// Auth Struct
+pub struct BluesnapAuthType {
+ pub(super) api_key: String,
+ pub(super) key1: String,
+}
+
+impl TryFrom<&types::ConnectorAuthType> for BluesnapAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
+ Ok(Self {
+ api_key: api_key.to_string(),
+ key1: key1.to_string(),
+ })
+ } else {
+ Err(errors::ConnectorError::FailedToObtainAuthType.into())
+ }
+ }
+}
+// PaymentsResponse
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum BluesnapTxnType {
+ AuthOnly,
+ AuthCapture,
+ AuthReversal,
+ Capture,
+ Refund,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "UPPERCASE")]
+pub enum BluesnapProcessingStatus {
+ #[serde(alias = "success")]
+ Success,
+ #[default]
+ #[serde(alias = "pending")]
+ Pending,
+ #[serde(alias = "fail")]
+ Fail,
+ #[serde(alias = "pending_merchant_review")]
+ PendingMerchantReview,
+}
+
+impl TryFrom<transformers::Foreign<(BluesnapTxnType, BluesnapProcessingStatus)>>
+ for transformers::Foreign<enums::AttemptStatus>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: transformers::Foreign<(BluesnapTxnType, BluesnapProcessingStatus)>,
+ ) -> Result<Self, Self::Error> {
+ let item = item.0;
+ let (item_txn_status, item_processing_status) = item;
+ Ok(match item_processing_status {
+ BluesnapProcessingStatus::Success => match item_txn_status {
+ BluesnapTxnType::AuthOnly => enums::AttemptStatus::Authorized,
+ BluesnapTxnType::AuthReversal => enums::AttemptStatus::Voided,
+ BluesnapTxnType::AuthCapture | BluesnapTxnType::Capture => {
+ enums::AttemptStatus::Charged
+ }
+ BluesnapTxnType::Refund => enums::AttemptStatus::Charged,
+ },
+ BluesnapProcessingStatus::Pending | BluesnapProcessingStatus::PendingMerchantReview => {
+ enums::AttemptStatus::Pending
+ }
+ BluesnapProcessingStatus::Fail => enums::AttemptStatus::Failure,
+ }
+ .into())
+ }
+}
+
+impl From<BluesnapProcessingStatus> for enums::RefundStatus {
+ fn from(item: BluesnapProcessingStatus) -> Self {
+ match item {
+ BluesnapProcessingStatus::Success => Self::Success,
+ BluesnapProcessingStatus::Pending => Self::Pending,
+ BluesnapProcessingStatus::PendingMerchantReview => Self::ManualReview,
+ BluesnapProcessingStatus::Fail => Self::Failure,
+ }
+ }
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct BluesnapPaymentsResponse {
+ processing_info: ProcessingInfoResponse,
+ transaction_id: String,
+ card_transaction_type: BluesnapTxnType,
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct Refund {
+ refund_transaction_id: String,
+ amount: String,
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct ProcessingInfoResponse {
+ processing_status: BluesnapProcessingStatus,
+ authorization_code: Option<String>,
+ network_transaction_id: Option<String>,
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, BluesnapPaymentsResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ BluesnapPaymentsResponse,
+ T,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: enums::AttemptStatus::foreign_try_from((
+ item.response.card_transaction_type,
+ item.response.processing_info.processing_status,
+ ))?,
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.transaction_id,
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+#[derive(Default, Debug, Eq, PartialEq, Serialize)]
+pub struct BluesnapRefundRequest {
+ amount: Option<i64>,
+ reason: Option<String>,
+}
+
+impl<F> TryFrom<&types::RefundsRouterData<F>> for BluesnapRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ reason: item.request.reason.clone(),
+ amount: Some(item.request.refund_amount),
+ })
+ }
+}
+
+#[derive(Default, Debug, Clone, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RefundResponse {
+ refund_transaction_id: i32,
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, BluesnapPaymentsResponse>>
+ for types::RefundsRouterData<api::RSync>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::RSync, BluesnapPaymentsResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.transaction_id.clone(),
+ refund_status: enums::RefundStatus::from(
+ item.response.processing_info.processing_status,
+ ),
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
+ for types::RefundsRouterData<api::Execute>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.refund_transaction_id.to_string(),
+ refund_status: enums::RefundStatus::Pending,
+ }),
+ ..item.data
+ })
+ }
+}
+#[derive(Debug, Clone, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct BluesnapWebhookBody {
+ pub auth_key: String,
+ pub contract_id: String,
+ pub reference_number: String,
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BluesnapWebhookObjectEventType {
+ pub transaction_type: String,
+}
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct BluesnapWebhookObjectResource {
+ pub auth_key: String,
+ pub contract_id: String,
+ pub reference_number: String,
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct ErrorDetails {
+ pub code: String,
+ pub description: String,
+}
+
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct BluesnapErrorResponse {
+ pub message: Vec<ErrorDetails>,
+}
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index cd116779de3..59e854f46d2 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -244,9 +244,11 @@ impl<F, T>
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::PaymentsResponseData::SessionResponse {
- session_token: types::api::SessionToken::Paypal(Box::new(payments::PaypalData {
- session_token: item.response.client_token.value,
- })),
+ session_token: types::api::SessionToken::Paypal(Box::new(
+ payments::PaypalSessionTokenResponse {
+ session_token: item.response.client_token.value,
+ },
+ )),
}),
..item.data
})
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 6dfe630ccfe..59ba3a28314 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -4,7 +4,7 @@ use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{self, AddressDetailsData, PaymentsRequestData, PhoneDetailsData},
+ connector::utils::{self, AddressDetailsData, PhoneDetailsData, RouterData},
consts,
core::errors,
pii::PeekInterface,
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs
index b494d98f259..3ec3e50e2bd 100644
--- a/crates/router/src/connector/dlocal/transformers.rs
+++ b/crates/router/src/connector/dlocal/transformers.rs
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
- connector::utils::{AddressDetailsData, PaymentsRequestData},
+ connector::utils::{AddressDetailsData, RouterData},
core::errors,
services,
types::{self, api, storage::enums},
diff --git a/crates/router/src/connector/globalpay/transformers.rs b/crates/router/src/connector/globalpay/transformers.rs
index 258d066629e..6973906f9e6 100644
--- a/crates/router/src/connector/globalpay/transformers.rs
+++ b/crates/router/src/connector/globalpay/transformers.rs
@@ -8,28 +8,25 @@ use super::{
response::{GlobalpayPaymentStatus, GlobalpayPaymentsResponse, GlobalpayRefreshTokenResponse},
};
use crate::{
- connector::utils::{self, CardData, PaymentsRequestData},
+ connector::utils::{CardData, PaymentsRequestData, RouterData},
consts,
core::errors,
types::{self, api, storage::enums, ErrorResponse},
};
+#[derive(Debug, Serialize, Deserialize)]
+pub struct GlobalPayMeta {
+ account_name: String,
+}
+
impl TryFrom<&types::PaymentsAuthorizeRouterData> for GlobalpayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
- let metadata = item
- .connector_meta_data
- .to_owned()
- .ok_or_else(utils::missing_field_err("connector_meta"))?;
- let account_name = metadata
- .as_object()
- .and_then(|o| o.get("account_name"))
- .map(|o| o.to_string())
- .ok_or_else(utils::missing_field_err("connector_meta.account_name"))?;
+ let metadata: GlobalPayMeta = item.to_connector_meta()?;
let card = item.get_card()?;
let expiry_year = card.get_card_expiry_year_2_digit();
Ok(Self {
- account_name,
+ account_name: metadata.account_name,
amount: Some(item.request.amount.to_string()),
currency: item.request.currency.to_string(),
reference: item.attempt_id.to_string(),
diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs
index 2d4a02289b7..e065014efb0 100644
--- a/crates/router/src/connector/klarna/transformers.rs
+++ b/crates/router/src/connector/klarna/transformers.rs
@@ -72,10 +72,12 @@ impl TryFrom<types::PaymentsSessionResponseRouterData<KlarnaSessionResponse>>
let response = &item.response;
Ok(Self {
response: Ok(types::PaymentsResponseData::SessionResponse {
- session_token: types::api::SessionToken::Klarna(Box::new(payments::KlarnaData {
- session_token: response.client_token.clone(),
- session_id: response.session_id.clone(),
- })),
+ session_token: types::api::SessionToken::Klarna(Box::new(
+ payments::KlarnaSessionTokenResponse {
+ session_token: response.client_token.clone(),
+ session_id: response.session_id.clone(),
+ },
+ )),
}),
..item.data
})
diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs
new file mode 100644
index 00000000000..9aff6524cf5
--- /dev/null
+++ b/crates/router/src/connector/nuvei.rs
@@ -0,0 +1,670 @@
+mod transformers;
+
+use std::fmt::Debug;
+
+use error_stack::{IntoReport, ResultExt};
+use transformers as nuvei;
+
+use crate::{
+ configs::settings,
+ core::{
+ errors::{self, CustomResult},
+ payments,
+ },
+ headers, logger,
+ services::{self, ConnectorIntegration},
+ types::{
+ self,
+ api::{self, ConnectorCommon, ConnectorCommonExt},
+ ErrorResponse, Response, RouterData,
+ },
+ utils::{self, BytesExt},
+};
+
+#[derive(Debug, Clone)]
+pub struct Nuvei;
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nuvei
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ _req: &RouterData<Flow, Request, Response>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ let headers = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ self.get_content_type().to_string(),
+ )];
+ Ok(headers)
+ }
+}
+
+impl ConnectorCommon for Nuvei {
+ fn id(&self) -> &'static str {
+ "nuvei"
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.nuvei.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ _auth_type: &types::ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ Ok(vec![])
+ }
+}
+
+impl api::Payment for Nuvei {}
+
+impl api::PreVerify for Nuvei {}
+impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>
+ for Nuvei
+{
+}
+
+impl api::PaymentVoid for Nuvei {}
+
+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
+ for Nuvei
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}ppp/api/v1/voidTransaction.do",
+ api::ConnectorCommon::base_url(self, connectors)
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let req_obj = nuvei::NuveiPaymentFlowRequest::try_from(req)?;
+ let req =
+ utils::Encode::<nuvei::NuveiPaymentFlowRequest>::encode_to_string_of_json(&req_obj)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCancelRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ .headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
+ .body(types::PaymentsVoidType::get_request_body(self, req)?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCancelRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ logger::debug!(target: "router::connector::nuvei", response=?res);
+ let response: nuvei::NuveiPaymentsResponse = res
+ .response
+ .parse_struct("nuvei NuveiPaymentsResponse")
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ types::PaymentsCancelRouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl api::ConnectorAccessToken for Nuvei {}
+
+impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+ for Nuvei
+{
+}
+
+impl api::PaymentSync for Nuvei {}
+impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+ for Nuvei
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}ppp/api/v1/getPaymentStatus.do",
+ api::ConnectorCommon::base_url(self, connectors)
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let req_obj = nuvei::NuveiPaymentSyncRequest::try_from(req)?;
+ let req =
+ utils::Encode::<nuvei::NuveiPaymentSyncRequest>::encode_to_string_of_json(&req_obj)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(req))
+ }
+ fn build_request(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .body(types::PaymentsSyncType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsSyncRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ logger::debug!(payment_sync_response=?res);
+ let response: nuvei::NuveiPaymentsResponse = res
+ .response
+ .parse_struct("nuvei PaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+}
+
+impl api::PaymentCapture for Nuvei {}
+impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
+ for Nuvei
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}ppp/api/v1/settleTransaction.do",
+ api::ConnectorCommon::base_url(self, connectors)
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let req_obj = nuvei::NuveiPaymentFlowRequest::try_from(req)?;
+ let req =
+ utils::Encode::<nuvei::NuveiPaymentFlowRequest>::encode_to_string_of_json(&req_obj)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsCaptureType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCaptureRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: nuvei::NuveiPaymentsResponse = res
+ .response
+ .parse_struct("Nuvei PaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ logger::debug!(nuveipayments_create_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl api::PaymentSession for Nuvei {}
+
+impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
+ for Nuvei
+{
+}
+
+impl api::PaymentAuthorize for Nuvei {}
+
+#[async_trait::async_trait]
+impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ for Nuvei
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}ppp/api/v1/payment.do",
+ api::ConnectorCommon::base_url(self, connectors)
+ ))
+ }
+
+ async fn execute_pretasks(
+ &self,
+ router_data: &mut types::PaymentsAuthorizeRouterData,
+ app_state: &crate::routes::AppState,
+ ) -> CustomResult<(), errors::ConnectorError> {
+ let integ: Box<
+ &(dyn ConnectorIntegration<
+ api::AuthorizeSessionToken,
+ types::AuthorizeSessionTokenData,
+ types::PaymentsResponseData,
+ > + Send
+ + Sync
+ + 'static),
+ > = Box::new(&Self);
+ let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::from(&router_data);
+ let resp = services::execute_connector_processing_step(
+ app_state,
+ integ,
+ authorize_data,
+ payments::CallConnectorAction::Trigger,
+ )
+ .await?;
+ router_data.session_token = resp.session_token;
+ Ok(())
+ }
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let req_obj = nuvei::NuveiPaymentsRequest::try_from(req)?;
+ let req = utils::Encode::<nuvei::NuveiPaymentsRequest>::encode_to_string_of_json(&req_obj)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsAuthorizeType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsAuthorizeRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: nuvei::NuveiPaymentsResponse = res
+ .response
+ .parse_struct("nuvei NuveiPaymentsResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ logger::debug!(nuveipayments_create_response=?response);
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl
+ ConnectorIntegration<
+ api::AuthorizeSessionToken,
+ types::AuthorizeSessionTokenData,
+ types::PaymentsResponseData,
+ > for Nuvei
+{
+ fn get_headers(
+ &self,
+ req: &RouterData<
+ types::api::payments::AuthorizeSessionToken,
+ types::AuthorizeSessionTokenData,
+ types::PaymentsResponseData,
+ >,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &RouterData<
+ types::api::payments::AuthorizeSessionToken,
+ types::AuthorizeSessionTokenData,
+ types::PaymentsResponseData,
+ >,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}ppp/api/v1/getSessionToken.do",
+ api::ConnectorCommon::base_url(self, connectors)
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &RouterData<
+ types::api::payments::AuthorizeSessionToken,
+ types::AuthorizeSessionTokenData,
+ types::PaymentsResponseData,
+ >,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let req_obj = nuvei::NuveiSessionRequest::try_from(req)?;
+ let req = utils::Encode::<nuvei::NuveiSessionRequest>::encode_to_string_of_json(&req_obj)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(req))
+ }
+
+ fn build_request(
+ &self,
+ req: &RouterData<
+ types::api::payments::AuthorizeSessionToken,
+ types::AuthorizeSessionTokenData,
+ types::PaymentsResponseData,
+ >,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsPreAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .headers(types::PaymentsPreAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsPreAuthorizeType::get_request_body(
+ self, req,
+ )?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &RouterData<
+ api::AuthorizeSessionToken,
+ types::AuthorizeSessionTokenData,
+ types::PaymentsResponseData,
+ >,
+ res: Response,
+ ) -> CustomResult<
+ RouterData<
+ api::AuthorizeSessionToken,
+ types::AuthorizeSessionTokenData,
+ types::PaymentsResponseData,
+ >,
+ errors::ConnectorError,
+ >
+ where
+ api::AuthorizeSessionToken: Clone,
+ types::AuthorizeSessionTokenData: Clone,
+ types::PaymentsResponseData: Clone,
+ {
+ let response: nuvei::NuveiSessionResponse = res
+ .response
+ .parse_struct("nuvei NuveiSessionResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ logger::debug!(nuvei_session_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: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl api::Refund for Nuvei {}
+impl api::RefundExecute for Nuvei {}
+impl api::RefundSync for Nuvei {}
+
+impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Nuvei {
+ fn get_headers(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, String)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!(
+ "{}ppp/api/v1/refundTransaction.do",
+ api::ConnectorCommon::base_url(self, connectors)
+ ))
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ ) -> CustomResult<Option<String>, errors::ConnectorError> {
+ let req_obj = nuvei::NuveiPaymentFlowRequest::try_from(req)?;
+ let req =
+ utils::Encode::<nuvei::NuveiPaymentFlowRequest>::encode_to_string_of_json(&req_obj)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::RefundExecuteType::get_request_body(self, req)?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundsRouterData<api::Execute>,
+ res: Response,
+ ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ logger::debug!(target: "router::connector::nuvei", response=?res);
+ let response: nuvei::NuveiPaymentsResponse = res
+ .response
+ .parse_struct("nuvei NuveiPaymentsResponse")
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ }
+ .try_into()
+ .change_context(errors::ConnectorError::ResponseHandlingFailed)
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Nuvei {}
+
+#[async_trait::async_trait]
+impl api::IncomingWebhook for Nuvei {
+ fn get_webhook_object_reference_id(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<serde_json::Value, errors::ConnectorError> {
+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ }
+}
+
+impl services::ConnectorRedirectResponse for Nuvei {
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ Ok(payments::CallConnectorAction::Trigger)
+ }
+}
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
new file mode 100644
index 00000000000..6fa32954a90
--- /dev/null
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -0,0 +1,615 @@
+use common_utils::{
+ crypto::{self, GenerateDigest},
+ date_time,
+};
+use error_stack::{IntoReport, ResultExt};
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ connector::utils::{PaymentsCancelRequestData, RouterData},
+ core::errors,
+ types::{self, api, storage::enums},
+};
+
+#[derive(Debug, Serialize, Default, Deserialize)]
+pub struct NuveiMeta {
+ pub session_token: String,
+}
+
+#[derive(Debug, Serialize, Default, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NuveiSessionRequest {
+ pub merchant_id: String,
+ pub merchant_site_id: String,
+ pub client_request_id: String,
+ pub time_stamp: String,
+ pub checksum: String,
+}
+
+#[derive(Debug, Serialize, Default, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NuveiSessionResponse {
+ pub session_token: String,
+ pub internal_request_id: i64,
+ pub status: String,
+ pub err_code: i64,
+ pub reason: String,
+ pub merchant_id: String,
+ pub merchant_site_id: String,
+ pub version: String,
+ pub client_request_id: String,
+}
+
+#[derive(Debug, Serialize, Default, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NuveiPaymentsRequest {
+ pub time_stamp: String,
+ pub session_token: String,
+ pub merchant_id: String,
+ pub merchant_site_id: String,
+ pub client_request_id: String,
+ pub amount: String,
+ pub currency: String,
+ pub user_token_id: String,
+ pub client_unique_id: String,
+ pub transaction_type: TransactionType,
+ pub payment_option: PaymentOption,
+ pub checksum: String,
+}
+
+#[derive(Debug, Serialize, Default, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NuveiPaymentFlowRequest {
+ pub time_stamp: String,
+ pub merchant_id: String,
+ pub merchant_site_id: String,
+ pub client_request_id: String,
+ pub amount: String,
+ pub currency: String,
+ pub related_transaction_id: Option<String>,
+ pub checksum: String,
+}
+
+#[derive(Debug, Serialize, Default, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NuveiPaymentSyncRequest {
+ pub session_token: String,
+}
+
+#[derive(Debug, Default, Serialize, Deserialize)]
+pub enum TransactionType {
+ Auth,
+ #[default]
+ Sale,
+}
+
+#[derive(Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct PaymentOption {
+ pub card: Card,
+ pub user_payment_option_id: Option<String>,
+ pub device_details: Option<DeviceDetails>,
+ pub billing_address: Option<BillingAddress>,
+}
+
+#[derive(Debug, Default, Serialize, Deserialize)]
+pub struct BillingAddress {
+ pub email: String,
+ pub country: String,
+}
+
+#[derive(Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct Card {
+ pub card_number: Option<Secret<String, common_utils::pii::CardNumber>>,
+ pub card_holder_name: Option<Secret<String>>,
+ pub expiration_month: Option<Secret<String>>,
+ pub expiration_year: Option<Secret<String>>,
+ #[serde(rename = "CVV")]
+ pub cvv: Option<Secret<String>>,
+ pub three_d: Option<ThreeD>,
+ pub cc_card_number: Option<String>,
+ pub bin: Option<String>,
+ pub last4_digits: Option<String>,
+ pub cc_exp_month: Option<String>,
+ pub cc_exp_year: Option<String>,
+ pub acquirer_id: Option<String>,
+ pub cvv2_reply: Option<String>,
+ pub avs_code: Option<String>,
+ pub card_type: Option<String>,
+ pub card_brand: Option<String>,
+ pub issuer_bank_name: Option<String>,
+ pub issuer_country: Option<String>,
+ pub is_prepaid: Option<String>,
+}
+
+#[derive(Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct ThreeD {
+ pub browser_details: Option<BrowserDetails>,
+ pub version: Option<String>,
+ pub notification_url: Option<String>,
+ pub merchant_url: Option<String>,
+ pub platform_type: Option<String>,
+ pub v2_additional_params: Option<V2AdditionalParams>,
+}
+
+#[derive(Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct BrowserDetails {
+ pub accept_header: String,
+ pub ip: String,
+ pub java_enabled: String,
+ pub java_script_enabled: String,
+ pub language: String,
+ pub color_depth: String,
+ pub screen_height: String,
+ pub screen_width: String,
+ pub time_zone: String,
+ pub user_agent: String,
+}
+
+#[derive(Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct V2AdditionalParams {
+ pub challenge_window_size: String,
+}
+
+#[derive(Debug, Default, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct DeviceDetails {
+ pub ip_address: String,
+}
+
+impl From<enums::CaptureMethod> for TransactionType {
+ fn from(value: enums::CaptureMethod) -> Self {
+ match value {
+ enums::CaptureMethod::Manual => Self::Auth,
+ _ => Self::Sale,
+ }
+ }
+}
+
+fn encode_payload(
+ payload: Vec<String>,
+) -> Result<String, error_stack::Report<errors::ConnectorError>> {
+ let data = payload.join("");
+ let digest = crypto::Sha256
+ .generate_digest(data.as_bytes())
+ .change_context(errors::ConnectorError::RequestEncodingFailed)
+ .attach_printable("error encoding the payload")?;
+ Ok(hex::encode(digest))
+}
+
+impl TryFrom<&types::PaymentsAuthorizeSessionTokenRouterData> for NuveiSessionRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &types::PaymentsAuthorizeSessionTokenRouterData,
+ ) -> Result<Self, Self::Error> {
+ let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?;
+ let merchant_id = connector_meta.merchant_id;
+ let merchant_site_id = connector_meta.merchant_site_id;
+ let client_request_id = item.attempt_id.clone();
+ let time_stamp = date_time::date_as_yyyymmddhhmmss();
+ let merchant_secret = connector_meta.merchant_secret;
+ Ok(Self {
+ merchant_id: merchant_id.clone(),
+ merchant_site_id: merchant_site_id.clone(),
+ client_request_id: client_request_id.clone(),
+ time_stamp: time_stamp.clone(),
+ checksum: encode_payload(vec![
+ merchant_id,
+ merchant_site_id,
+ client_request_id,
+ time_stamp,
+ merchant_secret,
+ ])?,
+ })
+ }
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, NuveiSessionResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, NuveiSessionResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: enums::AttemptStatus::Pending,
+ session_token: Some(item.response.session_token.clone()),
+ response: Ok(types::PaymentsResponseData::SessionTokenResponse {
+ session_token: item.response.session_token,
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<&types::PaymentsAuthorizeRouterData> for NuveiPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?;
+ let merchant_id = connector_meta.merchant_id;
+ let merchant_site_id = connector_meta.merchant_site_id;
+ let client_request_id = item.attempt_id.clone();
+ let time_stamp = date_time::date_as_yyyymmddhhmmss();
+ let merchant_secret = connector_meta.merchant_secret;
+ match item.request.payment_method_data.clone() {
+ api::PaymentMethod::Card(card) => Ok(Self {
+ merchant_id: merchant_id.clone(),
+ merchant_site_id: merchant_site_id.clone(),
+ client_request_id: client_request_id.clone(),
+ amount: item.request.amount.clone().to_string(),
+ currency: item.request.currency.clone().to_string(),
+ transaction_type: item
+ .request
+ .capture_method
+ .map(TransactionType::from)
+ .unwrap_or_default(),
+ payment_option: PaymentOption {
+ card: Card {
+ card_number: Some(card.card_number),
+ card_holder_name: Some(card.card_holder_name),
+ expiration_month: Some(card.card_exp_month),
+ expiration_year: Some(card.card_exp_year),
+ cvv: Some(card.card_cvc),
+ ..Default::default()
+ },
+ ..Default::default()
+ },
+ time_stamp: time_stamp.clone(),
+ session_token: item.get_session_token()?,
+ checksum: encode_payload(vec![
+ merchant_id,
+ merchant_site_id,
+ client_request_id,
+ item.request.amount.to_string(),
+ item.request.currency.to_string(),
+ time_stamp,
+ merchant_secret,
+ ])?,
+ ..Default::default()
+ }),
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
+ }
+}
+
+impl TryFrom<&types::PaymentsCaptureRouterData> for NuveiPaymentFlowRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?;
+ let merchant_id = connector_meta.merchant_id;
+ let merchant_site_id = connector_meta.merchant_site_id;
+ let client_request_id = item.attempt_id.clone();
+ let time_stamp = date_time::date_as_yyyymmddhhmmss();
+ let merchant_secret = connector_meta.merchant_secret;
+ Ok(Self {
+ merchant_id: merchant_id.clone(),
+ merchant_site_id: merchant_site_id.clone(),
+ client_request_id: client_request_id.clone(),
+ amount: item.request.amount.clone().to_string(),
+ currency: item.request.currency.clone().to_string(),
+ related_transaction_id: Some(item.request.connector_transaction_id.clone()),
+ time_stamp: time_stamp.clone(),
+ checksum: encode_payload(vec![
+ merchant_id,
+ merchant_site_id,
+ client_request_id,
+ item.request.amount.to_string(),
+ item.request.currency.to_string(),
+ item.request.connector_transaction_id.clone(),
+ time_stamp,
+ merchant_secret,
+ ])?,
+ })
+ }
+}
+
+impl TryFrom<&types::RefundExecuteRouterData> for NuveiPaymentFlowRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::RefundExecuteRouterData) -> Result<Self, Self::Error> {
+ let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?;
+ let merchant_id = connector_meta.merchant_id;
+ let merchant_site_id = connector_meta.merchant_site_id;
+ let client_request_id = item.attempt_id.clone();
+ let time_stamp = date_time::date_as_yyyymmddhhmmss();
+ let merchant_secret = connector_meta.merchant_secret;
+ Ok(Self {
+ merchant_id: merchant_id.clone(),
+ merchant_site_id: merchant_site_id.clone(),
+ client_request_id: client_request_id.clone(),
+ amount: item.request.amount.clone().to_string(),
+ currency: item.request.currency.clone().to_string(),
+ related_transaction_id: Some(item.request.connector_transaction_id.clone()),
+ time_stamp: time_stamp.clone(),
+ checksum: encode_payload(vec![
+ merchant_id,
+ merchant_site_id,
+ client_request_id,
+ item.request.amount.to_string(),
+ item.request.currency.to_string(),
+ item.request.connector_transaction_id.clone(),
+ time_stamp,
+ merchant_secret,
+ ])?,
+ })
+ }
+}
+
+impl TryFrom<&types::PaymentsSyncRouterData> for NuveiPaymentSyncRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(value: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
+ let meta: NuveiMeta = value.to_connector_meta()?;
+ Ok(Self {
+ session_token: meta.session_token,
+ })
+ }
+}
+
+impl TryFrom<&types::PaymentsCancelRouterData> for NuveiPaymentFlowRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ let connector_meta: NuveiAuthType = NuveiAuthType::try_from(&item.connector_auth_type)?;
+ let merchant_id = connector_meta.merchant_id;
+ let merchant_site_id = connector_meta.merchant_site_id;
+ let client_request_id = item.attempt_id.clone();
+ let time_stamp = date_time::date_as_yyyymmddhhmmss();
+ let merchant_secret = connector_meta.merchant_secret;
+ let amount = item.request.get_amount()?.to_string();
+ let currency = item.request.get_currency()?.to_string();
+ Ok(Self {
+ merchant_id: merchant_id.clone(),
+ merchant_site_id: merchant_site_id.clone(),
+ client_request_id: client_request_id.clone(),
+ amount: amount.clone(),
+ currency: currency.clone(),
+ related_transaction_id: Some(item.request.connector_transaction_id.clone()),
+ time_stamp: time_stamp.clone(),
+ checksum: encode_payload(vec![
+ merchant_id,
+ merchant_site_id,
+ client_request_id,
+ amount,
+ currency,
+ item.request.connector_transaction_id.clone(),
+ time_stamp,
+ merchant_secret,
+ ])?,
+ })
+ }
+}
+
+// Auth Struct
+pub struct NuveiAuthType {
+ pub(super) merchant_id: String,
+ pub(super) merchant_site_id: String,
+ pub(super) merchant_secret: String,
+}
+
+impl TryFrom<&types::ConnectorAuthType> for NuveiAuthType {
+ 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 {
+ merchant_id: api_key.to_string(),
+ merchant_site_id: key1.to_string(),
+ merchant_secret: api_secret.to_string(),
+ })
+ } else {
+ Err(errors::ConnectorError::FailedToObtainAuthType)?
+ }
+ }
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "UPPERCASE")]
+pub enum NuveiPaymentStatus {
+ Success,
+ Failed,
+ Error,
+ #[default]
+ Processing,
+}
+
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "UPPERCASE")]
+pub enum NuveiTransactionStatus {
+ Approved,
+ Declined,
+ Error,
+ #[default]
+ Processing,
+}
+
+impl From<NuveiTransactionStatus> for enums::AttemptStatus {
+ fn from(item: NuveiTransactionStatus) -> Self {
+ match item {
+ NuveiTransactionStatus::Approved => Self::Charged,
+ NuveiTransactionStatus::Declined | NuveiTransactionStatus::Error => Self::Failure,
+ _ => Self::Pending,
+ }
+ }
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NuveiPaymentsResponse {
+ pub order_id: Option<String>,
+ pub user_token_id: Option<String>,
+ pub payment_option: Option<PaymentOption>,
+ pub transaction_status: Option<NuveiTransactionStatus>,
+ pub gw_error_code: Option<i64>,
+ pub gw_extended_error_code: Option<i64>,
+ pub issuer_decline_code: Option<String>,
+ pub issuer_decline_reason: Option<String>,
+ pub transaction_type: Option<NuveiTransactionType>,
+ pub transaction_id: Option<String>,
+ pub external_transaction_id: Option<String>,
+ pub auth_code: Option<String>,
+ pub custom_data: Option<String>,
+ pub fraud_details: Option<FraudDetails>,
+ pub external_scheme_transaction_id: Option<String>,
+ pub session_token: Option<String>,
+ pub client_unique_id: Option<String>,
+ pub internal_request_id: Option<i64>,
+ pub status: NuveiPaymentStatus,
+ pub err_code: Option<i64>,
+ pub reason: Option<String>,
+ pub merchant_id: Option<String>,
+ pub merchant_site_id: Option<String>,
+ pub version: Option<String>,
+ pub client_request_id: Option<String>,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+pub enum NuveiTransactionType {
+ Auth,
+ Sale,
+ Credit,
+ Settle,
+ Void,
+}
+
+#[derive(Debug, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct FraudDetails {
+ pub final_decision: String,
+}
+
+fn get_payment_status(response: &NuveiPaymentsResponse) -> enums::AttemptStatus {
+ match response.transaction_status.clone() {
+ Some(status) => match status {
+ NuveiTransactionStatus::Approved => match response.transaction_type {
+ Some(NuveiTransactionType::Auth) => enums::AttemptStatus::Authorized,
+ Some(NuveiTransactionType::Sale) | Some(NuveiTransactionType::Settle) => {
+ enums::AttemptStatus::Charged
+ }
+ Some(NuveiTransactionType::Void) => enums::AttemptStatus::Voided,
+ _ => enums::AttemptStatus::Pending,
+ },
+ NuveiTransactionStatus::Declined | NuveiTransactionStatus::Error => {
+ match response.transaction_type {
+ Some(NuveiTransactionType::Auth) => enums::AttemptStatus::AuthorizationFailed,
+ Some(NuveiTransactionType::Sale) | Some(NuveiTransactionType::Settle) => {
+ enums::AttemptStatus::Failure
+ }
+ Some(NuveiTransactionType::Void) => enums::AttemptStatus::VoidFailed,
+ _ => enums::AttemptStatus::Pending,
+ }
+ }
+ NuveiTransactionStatus::Processing => enums::AttemptStatus::Pending,
+ },
+ None => match response.status {
+ NuveiPaymentStatus::Failed | NuveiPaymentStatus::Error => enums::AttemptStatus::Failure,
+ _ => enums::AttemptStatus::Pending,
+ },
+ }
+}
+
+impl<F, T>
+ TryFrom<types::ResponseRouterData<F, NuveiPaymentsResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, NuveiPaymentsResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: get_payment_status(&item.response),
+ response: match item.response.status {
+ NuveiPaymentStatus::Error => Err(types::ErrorResponse {
+ code: item
+ .response
+ .err_code
+ .ok_or(errors::ParsingError)?
+ .to_string(),
+ message: item.response.reason.clone().ok_or(errors::ParsingError)?,
+ reason: None,
+ status_code: item.http_code,
+ }),
+ _ => Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.transaction_id.ok_or(errors::ParsingError)?,
+ ),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: Some(
+ serde_json::to_value(NuveiMeta {
+ session_token: item.response.session_token.unwrap_or_default(),
+ })
+ .into_report()
+ .change_context(errors::ParsingError)?,
+ ),
+ }),
+ },
+ ..item.data
+ })
+ }
+}
+
+impl From<NuveiTransactionStatus> for enums::RefundStatus {
+ fn from(item: NuveiTransactionStatus) -> Self {
+ match item {
+ NuveiTransactionStatus::Approved => Self::Success,
+ NuveiTransactionStatus::Declined | NuveiTransactionStatus::Error => Self::Failure,
+ NuveiTransactionStatus::Processing => Self::Pending,
+ }
+ }
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::Execute, NuveiPaymentsResponse>>
+ for types::RefundsRouterData<api::Execute>
+{
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::Execute, NuveiPaymentsResponse>,
+ ) -> Result<Self, Self::Error> {
+ let refund_status = item
+ .response
+ .transaction_status
+ .map(|a| a.into())
+ .unwrap_or(enums::RefundStatus::Failure);
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.transaction_id.ok_or(errors::ParsingError)?,
+ refund_status,
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, NuveiPaymentsResponse>>
+ for types::RefundsRouterData<api::RSync>
+{
+ type Error = error_stack::Report<errors::ParsingError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::RSync, NuveiPaymentsResponse>,
+ ) -> Result<Self, Self::Error> {
+ let refund_status = item
+ .response
+ .transaction_status
+ .map(|a| a.into())
+ .unwrap_or(enums::RefundStatus::Failure);
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.transaction_id.ok_or(errors::ParsingError)?,
+ refund_status,
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct NuveiErrorResponse {}
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 6428ceb55ae..4b3ff44906f 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -4,7 +4,7 @@ use masking::Secret;
use crate::{
core::errors::{self, CustomResult},
pii::PeekInterface,
- types::{self, api},
+ types::{self, api, PaymentsCancelData},
utils::OptionExt,
};
@@ -34,15 +34,37 @@ impl AccessTokenRequestInfo for types::RefreshTokenRouterData {
}
}
-pub trait PaymentsRequestData {
+pub trait RouterData {
fn get_billing(&self) -> Result<&api::Address, Error>;
fn get_billing_country(&self) -> Result<String, Error>;
fn get_billing_phone(&self) -> Result<&api::PhoneDetails, Error>;
+ fn get_connector_meta(&self) -> Result<serde_json::Value, Error>;
+ fn get_session_token(&self) -> Result<String, Error>;
fn get_billing_address(&self) -> Result<&api::AddressDetails, Error>;
+ fn to_connector_meta<T>(&self) -> Result<T, Error>
+ where
+ T: serde::de::DeserializeOwned;
+}
+
+pub trait PaymentsRequestData {
fn get_card(&self) -> Result<api::Card, Error>;
fn get_return_url(&self) -> Result<String, Error>;
}
+pub trait PaymentsCancelRequestData {
+ fn get_amount(&self) -> Result<i64, Error>;
+ fn get_currency(&self) -> Result<storage_models::enums::Currency, Error>;
+}
+
+impl PaymentsCancelRequestData for PaymentsCancelData {
+ fn get_amount(&self) -> Result<i64, Error> {
+ self.amount.ok_or_else(missing_field_err("amount"))
+ }
+ fn get_currency(&self) -> Result<storage_models::enums::Currency, Error> {
+ self.currency.ok_or_else(missing_field_err("currency"))
+ }
+}
+
pub trait RefundsRequestData {
fn get_connector_refund_id(&self) -> Result<String, Error>;
}
@@ -56,7 +78,7 @@ impl RefundsRequestData for types::RefundsData {
}
}
-impl PaymentsRequestData for types::PaymentsAuthorizeRouterData {
+impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Response> {
fn get_billing_country(&self) -> Result<String, Error> {
self.address
.billing
@@ -66,13 +88,6 @@ impl PaymentsRequestData for types::PaymentsAuthorizeRouterData {
.ok_or_else(missing_field_err("billing.address.country"))
}
- fn get_card(&self) -> Result<api::Card, Error> {
- match self.request.payment_method_data.clone() {
- api::PaymentMethod::Card(card) => Ok(card),
- _ => Err(missing_field_err("card")()),
- }
- }
-
fn get_billing_phone(&self) -> Result<&api::PhoneDetails, Error> {
self.address
.billing
@@ -94,11 +109,40 @@ impl PaymentsRequestData for types::PaymentsAuthorizeRouterData {
.ok_or_else(missing_field_err("billing"))
}
+ fn get_connector_meta(&self) -> Result<serde_json::Value, Error> {
+ self.connector_meta_data
+ .clone()
+ .ok_or_else(missing_field_err("connector_meta_data"))
+ }
+
+ fn get_session_token(&self) -> Result<String, Error> {
+ self.session_token
+ .clone()
+ .ok_or_else(missing_field_err("session_token"))
+ }
+
+ fn to_connector_meta<T>(&self) -> Result<T, Error>
+ where
+ T: serde::de::DeserializeOwned,
+ {
+ serde_json::from_value::<T>(self.get_connector_meta()?)
+ .into_report()
+ .change_context(errors::ConnectorError::NoConnectorMetaData)
+ }
+}
+
+impl PaymentsRequestData for types::PaymentsAuthorizeRouterData {
fn get_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("router_return_url"))
}
+ fn get_card(&self) -> Result<api::Card, Error> {
+ match self.request.payment_method_data.clone() {
+ api::PaymentMethod::Card(card) => Ok(card),
+ _ => Err(missing_field_err("card")()),
+ }
+ }
}
pub trait CardData {
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index c1b59800f02..3e00620664d 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -63,7 +63,7 @@ pub async fn create_merchant_account(
merchant_name: req.merchant_name,
api_key,
merchant_details,
- return_url: req.return_url,
+ return_url: req.return_url.map(|a| a.to_string()),
webhook_details,
routing_algorithm: req.routing_algorithm,
sub_merchants_enabled: req.sub_merchants_enabled,
@@ -146,7 +146,7 @@ pub async fn merchant_account_update(
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)?,
- return_url: req.return_url,
+ return_url: req.return_url.map(|a| a.to_string()),
webhook_details: req
.webhook_details
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index f56d44552ec..57869ef9c06 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1,4 +1,4 @@
-use std::collections::HashSet;
+use std::collections::{HashMap, HashSet};
use api_models::{admin, enums as api_enums};
use common_utils::{consts, ext_traits::AsyncExt, generate_id};
@@ -382,7 +382,7 @@ pub async fn list_payment_methods(
error.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
})?;
- let mut response: HashSet<api::ListPaymentMethod> = HashSet::new();
+ let mut response: HashMap<api::ListPaymentMethod, Vec<String>> = HashMap::new();
for mca in all_mcas {
let payment_methods = match mca.payment_methods_enabled {
Some(pm) => pm,
@@ -396,6 +396,7 @@ pub async fn list_payment_methods(
payment_intent.as_ref(),
payment_attempt.as_ref(),
address.as_ref(),
+ mca.connector_name,
)
.await?;
}
@@ -406,7 +407,13 @@ pub async fn list_payment_methods(
.unwrap_or(Ok(services::ApplicationResponse::Json(
api::ListPaymentMethodResponse {
redirect_url: merchant_account.return_url,
- payment_methods: response,
+ payment_methods: response
+ .into_iter()
+ .map(|(mut key, val)| {
+ key.eligible_connectors = Some(val);
+ key
+ })
+ .collect(),
},
)))
}
@@ -414,10 +421,11 @@ pub async fn list_payment_methods(
async fn filter_payment_methods(
payment_methods: Vec<serde_json::Value>,
req: &mut api::ListPaymentMethodRequest,
- resp: &mut HashSet<api::ListPaymentMethod>,
+ resp: &mut HashMap<api::ListPaymentMethod, Vec<String>>,
payment_intent: Option<&storage::PaymentIntent>,
payment_attempt: Option<&storage::PaymentAttempt>,
address: Option<&storage::Address>,
+ connector_name: String,
) -> errors::CustomResult<(), errors::ApiErrorResponse> {
for payment_method in payment_methods.into_iter() {
if let Ok(payment_method_object) =
@@ -458,7 +466,9 @@ async fn filter_payment_methods(
};
if filter && filter2 && filter3 {
- resp.insert(payment_method_object);
+ resp.entry(payment_method_object)
+ .or_insert_with(Vec::new)
+ .push(connector_name.clone());
}
}
}
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 5c65854ad8d..b7b0e982042 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -212,7 +212,7 @@ where
FData: Send,
Op: Operation<F, Req> + Send + Sync + Clone,
Req: Debug,
- Res: transformers::ToResponse<Req, PaymentData<F>, Op> + TryFrom<Req>,
+ Res: transformers::ToResponse<Req, PaymentData<F>, Op>,
// To create connector flow specific interface data
PaymentData<F>: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs
index a43a23bedd6..10487b2cf94 100644
--- a/crates/router/src/core/payments/access_token.rs
+++ b/crates/router/src/core/payments/access_token.rs
@@ -45,6 +45,8 @@ pub fn router_data_type_conversion<F1, F2, Req1, Req2, Res1, Res2>(
status: router_data.status,
attempt_id: router_data.attempt_id,
access_token: router_data.access_token,
+ session_token: router_data.session_token,
+ reference_id: None,
}
}
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 909feb27d51..c60d1b734b6 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -46,7 +46,7 @@ impl
#[async_trait]
impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuthorizeRouterData {
async fn decide_flows<'a>(
- self,
+ mut self,
state: &AppState,
connector: &api::ConnectorData,
customer: &Option<storage::Customer>,
@@ -81,7 +81,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
impl types::PaymentsAuthorizeRouterData {
pub async fn decide_flow<'a, 'b>(
- &'b self,
+ &'b mut self,
state: &'a AppState,
connector: &api::ConnectorData,
maybe_customer: &Option<storage::Customer>,
@@ -97,6 +97,10 @@ impl types::PaymentsAuthorizeRouterData {
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
+ connector_integration
+ .execute_pretasks(self, state)
+ .await
+ .map_err(|error| error.to_payment_failed_response())?;
let resp = services::execute_connector_processing_step(
state,
connector_integration,
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index b2950004dbc..785e5d08c33 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -91,11 +91,13 @@ fn create_gpay_session_token(
let response_router_data = types::PaymentsSessionRouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
- session_token: payment_types::SessionToken::Gpay(Box::new(payment_types::GpayData {
- merchant_info: gpay_data.data.merchant_info,
- allowed_payment_methods: gpay_data.data.allowed_payment_methods,
- transaction_info,
- })),
+ session_token: payment_types::SessionToken::Gpay(Box::new(
+ payment_types::GpaySessionTokenResponse {
+ merchant_info: gpay_data.data.merchant_info,
+ allowed_payment_methods: gpay_data.data.allowed_payment_methods,
+ transaction_info,
+ },
+ )),
}),
..router_data.clone()
};
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index cca49294759..9ff2f81b783 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -161,7 +161,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id);
- payment_intent.return_url = request.return_url.clone();
+ payment_intent.return_url = request.return_url.as_ref().map(|a| a.to_string());
Ok((
Box::new(self),
@@ -262,7 +262,10 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentConfirm {
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
// Use a new connector in the confirm call or use the same one which was passed when
// creating the payment or if none is passed then use the routing algorithm
- let request_connector = request.connector.map(|connector| connector.to_string());
+ let request_connector = request
+ .connector
+ .as_ref()
+ .and_then(|connector| connector.first().map(|c| c.to_string()));
helpers::get_connector_default(
state,
request_connector.as_ref().or(previously_used_connector),
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index a297cdaeda7..973f3921075 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -259,7 +259,10 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest> for PaymentCreate {
request: &api::PaymentsRequest,
_previously_used_connector: Option<&String>,
) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {
- let request_connector = request.connector.map(|connector| connector.to_string());
+ let request_connector = request
+ .connector
+ .as_ref()
+ .and_then(|connector| connector.first().map(|c| c.to_string()));
helpers::get_connector_default(state, request_connector.as_ref()).await
}
}
@@ -474,7 +477,7 @@ impl PaymentCreate {
client_secret: Some(client_secret),
setup_future_usage: request.setup_future_usage.map(ForeignInto::foreign_into),
off_session: request.off_session,
- return_url: request.return_url.clone(),
+ return_url: request.return_url.as_ref().map(|a| a.to_string()),
shipping_address_id,
billing_address_id,
statement_descriptor_name: request.statement_descriptor_name.clone(),
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 5dc58a076d3..1236b71e245 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -330,6 +330,7 @@ async fn payment_response_update_tracker<F: Clone, T>(
}
types::PaymentsResponseData::SessionResponse { .. } => (None, None),
+ types::PaymentsResponseData::SessionTokenResponse { .. } => (None, None),
},
};
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index e013c91a3fd..5447e721719 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -140,7 +140,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
payment_intent.shipping_address_id = shipping_address.clone().map(|x| x.address_id);
payment_intent.billing_address_id = billing_address.clone().map(|x| x.address_id);
- payment_intent.return_url = request.return_url.clone();
+ payment_intent.return_url = request.return_url.as_ref().map(|a| a.to_string());
let token = token.or_else(|| payment_attempt.payment_token.clone());
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index a5a35ffeb1b..81dd61d55ff 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -98,6 +98,8 @@ where
response: response.map_or_else(|| Err(types::ErrorResponse::default()), Ok),
amount_captured: payment_data.payment_intent.amount_captured,
access_token: None,
+ session_token: None,
+ reference_id: None,
};
Ok(router_data)
@@ -105,7 +107,7 @@ where
pub trait ToResponse<Req, D, Op>
where
- Self: TryFrom<Req>,
+ Self: Sized,
Op: Debug,
{
fn generate_response(
@@ -120,7 +122,6 @@ where
impl<F, Req, Op> ToResponse<Req, PaymentData<F>, Op> for api::PaymentsResponse
where
- Self: TryFrom<Req>,
F: Clone,
Op: Debug,
{
@@ -235,7 +236,6 @@ pub fn payments_to_payments_response<R, Op>(
operation: Op,
) -> RouterResponse<api::PaymentsResponse>
where
- api::PaymentsResponse: TryFrom<R>,
Op: Debug,
{
let currency = payment_attempt
@@ -251,16 +251,13 @@ where
};
Ok(match payment_request {
- Some(request) => {
+ Some(_request) => {
if payments::is_start_pay(&operation) && redirection_data.is_some() {
let redirection_data = redirection_data.get_required_value("redirection_data")?;
let form: RedirectForm = serde_json::from_value(redirection_data)
.map_err(|_| errors::ApiErrorResponse::InternalServerError)?;
services::ApplicationResponse::Form(form)
} else {
- let mut response: api::PaymentsResponse = request
- .try_into()
- .map_err(|_| errors::ApiErrorResponse::InternalServerError)?;
let mut next_action_response = None;
if payment_intent.status == enums::IntentStatus::RequiresCustomerAction {
next_action_response = Some(api::NextAction {
@@ -272,7 +269,7 @@ where
)),
})
}
-
+ let mut response: api::PaymentsResponse = Default::default();
services::ApplicationResponse::Json(
response
.set_payment_id(Some(payment_attempt.payment_id))
@@ -319,7 +316,6 @@ where
.set_error_code(payment_attempt.error_code)
.set_shipping(address.shipping)
.set_billing(address.billing)
- .to_owned()
.set_next_action(next_action_response)
.set_return_url(payment_intent.return_url)
.set_cancellation_reason(payment_attempt.cancellation_reason)
@@ -340,6 +336,7 @@ where
.capture_method
.map(ForeignInto::foreign_into),
)
+ .set_metadata(payment_intent.metadata)
.to_owned(),
)
}
@@ -380,6 +377,7 @@ where
billing: address.billing,
cancellation_reason: payment_attempt.cancellation_reason,
payment_token: payment_attempt.payment_token,
+ metadata: payment_intent.metadata,
..Default::default()
}),
})
@@ -474,6 +472,8 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsCancelData {
fn try_from(payment_data: PaymentData<F>) -> Result<Self, Self::Error> {
Ok(Self {
+ amount: Some(payment_data.amount.into()),
+ currency: Some(payment_data.currency),
connector_transaction_id: payment_data
.payment_attempt
.connector_transaction_id
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index fccd7284589..fb072c80bfb 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -82,6 +82,8 @@ pub async fn construct_refund_router_data<'a, F>(
refund_status: refund.refund_status,
}),
access_token: None,
+ session_token: None,
+ reference_id: None,
};
Ok(router_data)
diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs
index 9be89d49bfd..b38997e3465 100644
--- a/crates/router/src/openapi.rs
+++ b/crates/router/src/openapi.rs
@@ -173,8 +173,8 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentsSessionRequest,
api_models::payments::PaymentsSessionResponse,
api_models::payments::SessionToken,
- api_models::payments::ApplePaySessionObject,
- api_models::payments::ApplePayRequest,
+ api_models::payments::ApplePaySessionResponse,
+ api_models::payments::ApplePayPaymentRequest,
api_models::payments::AmountInfo,
api_models::payments::GpayMerchantInfo,
api_models::payments::GpayAllowedPaymentMethods,
@@ -182,10 +182,10 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::GpayTokenizationSpecification,
api_models::payments::GpayTokenParameters,
api_models::payments::GpayTransactionInfo,
- api_models::payments::GpayData,
- api_models::payments::KlarnaData,
- api_models::payments::PaypalData,
- api_models::payments::ApplepayData,
+ api_models::payments::GpaySessionTokenResponse,
+ api_models::payments::KlarnaSessionTokenResponse,
+ api_models::payments::PaypalSessionTokenResponse,
+ api_models::payments::ApplepaySessionTokenResponse,
api_models::payments::PaymentsCancelRequest,
api_models::payments::PaymentListConstraints,
api_models::payments::PaymentListResponse,
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 1a92a6f6cfd..9962d0237d1 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -29,7 +29,8 @@ use crate::{
routes::{app::AppStateInfo, AppState},
services::authentication as auth,
types::{
- self, api,
+ self,
+ api::{self},
storage::{self},
ErrorResponse,
},
@@ -51,7 +52,8 @@ where
}
}
-pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> {
+#[async_trait::async_trait]
+pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Resp> + Sync {
fn get_headers(
&self,
_req: &types::RouterData<T, Req, Resp>,
@@ -84,6 +86,26 @@ pub trait ConnectorIntegration<T, Req, Resp>: ConnectorIntegrationAny<T, Req, Re
Ok(None)
}
+ /// This module can be called before executing a payment flow where a pre-task is needed
+ /// Eg: Some connectors requires one-time session token before making a payment, we can add the session token creation logic in this block
+ async fn execute_pretasks(
+ &self,
+ _router_data: &mut types::RouterData<T, Req, Resp>,
+ _app_state: &AppState,
+ ) -> CustomResult<(), errors::ConnectorError> {
+ Ok(())
+ }
+
+ /// This module can be called after executing a payment flow where a post-task needed
+ /// Eg: Some connectors require payment sync to happen immediately after the authorize call to complete the transaction, we can add that logic in this block
+ async fn execute_posttasks(
+ &self,
+ _router_data: &mut types::RouterData<T, Req, Resp>,
+ _app_state: &AppState,
+ ) -> CustomResult<(), errors::ConnectorError> {
+ Ok(())
+ }
+
fn build_request(
&self,
_req: &types::RouterData<T, Req, Resp>,
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index ef52823d9cd..93c68a4ff37 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -22,6 +22,8 @@ use crate::{core::errors, services};
pub type PaymentsAuthorizeRouterData =
RouterData<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
+pub type PaymentsAuthorizeSessionTokenRouterData =
+ RouterData<api::AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>;
pub type PaymentsSyncRouterData = RouterData<api::PSync, PaymentsSyncData, PaymentsResponseData>;
pub type PaymentsCaptureRouterData =
RouterData<api::Capture, PaymentsCaptureData, PaymentsResponseData>;
@@ -51,6 +53,11 @@ pub type RefundsResponseRouterData<F, R> =
pub type PaymentsAuthorizeType =
dyn services::ConnectorIntegration<api::Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
+pub type PaymentsPreAuthorizeType = dyn services::ConnectorIntegration<
+ api::AuthorizeSessionToken,
+ AuthorizeSessionTokenData,
+ PaymentsResponseData,
+>;
pub type PaymentsSyncType =
dyn services::ConnectorIntegration<api::PSync, PaymentsSyncData, PaymentsResponseData>;
pub type PaymentsCaptureType =
@@ -88,6 +95,8 @@ pub struct RouterData<Flow, Request, Response> {
pub connector_meta_data: Option<serde_json::Value>,
pub amount_captured: Option<i64>,
pub access_token: Option<AccessToken>,
+ pub session_token: Option<String>,
+ pub reference_id: Option<String>,
/// Contains flow-specific data required to construct a request and send it to the connector.
pub request: Request,
@@ -127,6 +136,14 @@ pub struct PaymentsCaptureData {
pub amount: i64,
}
+#[derive(Debug, Clone)]
+pub struct AuthorizeSessionTokenData {
+ pub amount_to_capture: Option<i64>,
+ pub currency: storage_enums::Currency,
+ pub connector_transaction_id: String,
+ pub amount: i64,
+}
+
#[derive(Debug, Clone)]
pub struct PaymentsSyncData {
//TODO : add fields based on the connector requirements
@@ -135,8 +152,10 @@ pub struct PaymentsSyncData {
pub capture_method: Option<storage_enums::CaptureMethod>,
}
-#[derive(Debug, Clone)]
+#[derive(Debug, Default, Clone)]
pub struct PaymentsCancelData {
+ pub amount: Option<i64>,
+ pub currency: Option<storage_enums::Currency>,
pub connector_transaction_id: String,
pub cancellation_reason: Option<String>,
}
@@ -190,6 +209,9 @@ pub enum PaymentsResponseData {
SessionResponse {
session_token: api::SessionToken,
},
+ SessionTokenResponse {
+ session_token: String,
+ },
}
#[derive(Debug, Clone, Default)]
@@ -372,3 +394,36 @@ impl Default for ErrorResponse {
Self::from(errors::ApiErrorResponse::InternalServerError)
}
}
+
+impl From<&&mut PaymentsAuthorizeRouterData> for PaymentsAuthorizeSessionTokenRouterData {
+ fn from(data: &&mut PaymentsAuthorizeRouterData) -> Self {
+ Self {
+ flow: PhantomData,
+ request: AuthorizeSessionTokenData {
+ amount_to_capture: data.amount_captured,
+ currency: data.request.currency,
+ connector_transaction_id: data.payment_id.clone(),
+ amount: data.request.amount,
+ },
+ merchant_id: data.merchant_id.clone(),
+ connector: data.connector.clone(),
+ attempt_id: data.attempt_id.clone(),
+ status: data.status,
+ payment_method: data.payment_method,
+ connector_auth_type: data.connector_auth_type.clone(),
+ description: data.description.clone(),
+ return_url: data.return_url.clone(),
+ router_return_url: data.router_return_url.clone(),
+ address: data.address.clone(),
+ auth_type: data.auth_type,
+ connector_meta_data: data.connector_meta_data.clone(),
+ amount_captured: data.amount_captured,
+ access_token: data.access_token.clone(),
+ response: data.response.clone(),
+ payment_method_id: data.payment_method_id.clone(),
+ payment_id: data.payment_id.clone(),
+ session_token: data.session_token.clone(),
+ reference_id: data.reference_id.clone(),
+ }
+ }
+}
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index a69f3df64e6..98229ab864a 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -162,8 +162,10 @@ impl ConnectorData {
match connector_name {
"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)),
+ "bluesnap" => Ok(Box::new(&connector::Bluesnap)),
"braintree" => Ok(Box::new(&connector::Braintree)),
"checkout" => Ok(Box::new(&connector::Checkout)),
"cybersource" => Ok(Box::new(&connector::Cybersource)),
@@ -171,6 +173,7 @@ impl ConnectorData {
"fiserv" => Ok(Box::new(&connector::Fiserv)),
"globalpay" => Ok(Box::new(&connector::Globalpay)),
"klarna" => Ok(Box::new(&connector::Klarna)),
+ "nuvei" => Ok(Box::new(&connector::Nuvei)),
"payu" => Ok(Box::new(&connector::Payu)),
"rapyd" => Ok(Box::new(&connector::Rapyd)),
"shift4" => Ok(Box::new(&connector::Shift4)),
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 7e808c2e52e..e9320b71030 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -64,6 +64,9 @@ impl super::Router for PaymentsRequest {}
// Core related api layer.
#[derive(Debug, Clone)]
pub struct Authorize;
+
+#[derive(Debug, Clone)]
+pub struct AuthorizeSessionToken;
#[derive(Debug, Clone)]
pub struct Capture;
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index b900c630f94..b80ed75eb6b 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -463,3 +463,9 @@ impl From<F<api_models::api_keys::UpdateApiKeyRequest>>
.into()
}
}
+
+impl From<F<storage_enums::AttemptStatus>> for F<api_enums::AttemptStatus> {
+ fn from(status: F<storage_enums::AttemptStatus>) -> Self {
+ Self(frunk::labelled_convert_from(status.0))
+ }
+}
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index 2aec793239c..9ba5f195009 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -59,6 +59,8 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {
connector_meta_data: None,
amount_captured: None,
access_token: None,
+ session_token: None,
+ reference_id: None,
}
}
@@ -97,6 +99,8 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> {
connector_meta_data: None,
amount_captured: None,
access_token: None,
+ session_token: None,
+ reference_id: None,
}
}
diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs
index 632d8faf718..1d2fc73dec1 100644
--- a/crates/router/tests/connectors/adyen.rs
+++ b/crates/router/tests/connectors/adyen.rs
@@ -162,6 +162,8 @@ async fn should_void_authorized_payment() {
enums::CaptureMethod::Manual,
),
Some(types::PaymentsCancelData {
+ amount: None,
+ currency: None,
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
}),
diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs
new file mode 100644
index 00000000000..e9d40b62fe3
--- /dev/null
+++ b/crates/router/tests/connectors/airwallex.rs
@@ -0,0 +1,519 @@
+use masking::Secret;
+use router::types::{self, api, storage::enums, AccessToken};
+
+use crate::{
+ connector_auth,
+ utils::{self, Connector, ConnectorActions},
+};
+
+#[derive(Clone, Copy)]
+struct AirwallexTest;
+impl ConnectorActions for AirwallexTest {}
+
+static CONNECTOR: AirwallexTest = AirwallexTest {};
+
+impl Connector for AirwallexTest {
+ fn get_data(&self) -> types::api::ConnectorData {
+ use router::connector::Airwallex;
+ types::api::ConnectorData {
+ connector: Box::new(&Airwallex),
+ connector_name: types::Connector::Airwallex,
+ get_token: types::api::GetToken::Connector,
+ }
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ types::ConnectorAuthType::from(
+ connector_auth::ConnectorAuthentication::new()
+ .airwallex
+ .expect("Missing connector authentication configuration"),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "airwallex".to_string()
+ }
+}
+
+fn get_access_token() -> Option<AccessToken> {
+ match CONNECTOR.get_auth_token() {
+ types::ConnectorAuthType::BodyKey { api_key, key1 } => Some(AccessToken {
+ token: api_key,
+ expires: key1.parse::<i64>().unwrap(),
+ }),
+ _ => None,
+ }
+}
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ Some(utils::PaymentInfo {
+ access_token: get_access_token(),
+ router_return_url: Some("https://google.com".to_string()),
+ ..Default::default()
+ })
+}
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_number: Secret::new("4035501000000008".to_string()),
+ card_exp_month: Secret::new("02".to_string()),
+ card_exp_year: Secret::new("2035".to_string()),
+ card_holder_name: Secret::new("John Doe".to_string()),
+ card_cvc: Secret::new("123".to_string()),
+ }),
+ capture_method: Some(storage_models::enums::CaptureMethod::Manual),
+ ..utils::PaymentAuthorizeType::default().0
+ })
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+#[serial_test::serial]
+#[actix_web::test]
+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).
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ payment_method_details(),
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: Some(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).
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ encoded_data: None,
+ capture_method: None,
+ }),
+ 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).
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_void_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_void_payment(
+ payment_method_details(),
+ Some(types::PaymentsCancelData {
+ amount: None,
+ currency: None,
+ connector_transaction_id: String::from(""),
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ }),
+ 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).
+// #[serial_test::serial]
+#[actix_web::test]
+#[ignore]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the manual capture flow (Non 3DS).
+// #[serial_test::serial]
+#[actix_web::test]
+#[ignore]
+async fn 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).
+// #[serial_test::serial]
+#[actix_web::test]
+#[ignore]
+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).
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ encoded_data: None,
+ capture_method: None,
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+// #[serial_test::serial]
+#[actix_web::test]
+#[ignore]
+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).
+// #[serial_test::serial]
+#[actix_web::test]
+#[ignore]
+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).
+// #[serial_test::serial]
+#[actix_web::test]
+#[ignore]
+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).
+// #[serial_test::serial]
+#[actix_web::test]
+#[ignore]
+async fn should_sync_refund() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Cards Negative scenerios
+// Creates a payment with incorrect card number.
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_card_number() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_number: Secret::new("1234567891011".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Invalid card number".to_string(),
+ );
+}
+
+// Creates a payment with empty card number.
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_payment_for_empty_card_number() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_number: Secret::new(String::from("")),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ let x = response.response.unwrap_err();
+ assert_eq!(x.message, "Invalid card number",);
+}
+
+// Creates a payment with incorrect CVC.
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Invalid card cvc".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::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,
+ "Invalid expiry month".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::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,
+ "payment_method.card should not be expired".to_string(),
+ );
+}
+
+// Voids a payment using automatic capture flow (Non 3DS).
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_void_payment_for_auto_capture() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(txn_id.unwrap(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ void_response.response.unwrap_err().message,
+ "The PaymentIntent status SUCCEEDED is invalid for operation cancel."
+ );
+}
+
+// Captures a payment using invalid connector payment id.
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ capture_response.response.unwrap_err().message,
+ String::from(
+ "The requested endpoint does not exist [/api/v1/pa/payment_intents/123456789/capture]"
+ )
+ );
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+// #[serial_test::serial]
+#[actix_web::test]
+#[ignore]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
+ );
+}
+
+// Connector dependent test cases goes here
+
+// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs
index cc3d36df9db..cadc748be6f 100644
--- a/crates/router/tests/connectors/authorizedotnet.rs
+++ b/crates/router/tests/connectors/authorizedotnet.rs
@@ -59,6 +59,8 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {
connector_meta_data: None,
amount_captured: None,
access_token: None,
+ session_token: None,
+ reference_id: None,
}
}
@@ -96,6 +98,8 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> {
address: PaymentAddress::default(),
amount_captured: None,
access_token: None,
+ session_token: None,
+ reference_id: None,
}
}
diff --git a/crates/router/tests/connectors/bluesnap.rs b/crates/router/tests/connectors/bluesnap.rs
new file mode 100644
index 00000000000..f3d82fee687
--- /dev/null
+++ b/crates/router/tests/connectors/bluesnap.rs
@@ -0,0 +1,540 @@
+use masking::Secret;
+use router::types::{self, api, storage::enums, ConnectorAuthType};
+
+use crate::{
+ connector_auth,
+ utils::{self, ConnectorActions},
+};
+
+#[derive(Clone, Copy)]
+struct BluesnapTest;
+impl ConnectorActions for BluesnapTest {}
+static CONNECTOR: BluesnapTest = BluesnapTest {};
+impl utils::Connector for BluesnapTest {
+ fn get_data(&self) -> types::api::ConnectorData {
+ use router::connector::Bluesnap;
+ types::api::ConnectorData {
+ connector: Box::new(&Bluesnap),
+ connector_name: types::Connector::Bluesnap,
+ get_token: types::api::GetToken::Connector,
+ }
+ }
+
+ fn get_auth_token(&self) -> ConnectorAuthType {
+ types::ConnectorAuthType::from(
+ connector_auth::ConnectorAuthentication::new()
+ .bluesnap
+ .expect("Missing connector authentication configuration"),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "bluesnap".to_string()
+ }
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(None, None)
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(None, None, None)
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Partially captures a payment using the manual capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ None,
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: Some(50),
+ ..utils::PaymentCaptureType::default().0
+ }),
+ None,
+ )
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the manual capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(None, None)
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ encoded_data: None,
+ capture_method: None,
+ }),
+ None,
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+}
+
+// Voids a payment using the manual capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_void_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_void_payment(
+ None,
+ Some(types::PaymentsCancelData {
+ connector_transaction_id: String::from(""),
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
+ }),
+ None,
+ )
+ .await
+ .expect("Void payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
+}
+
+// Refunds a payment using the manual capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(None, None, None, None)
+ .await
+ .unwrap();
+ let rsync_response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ response.response.unwrap().connector_refund_id,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ rsync_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the manual capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_partially_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ None,
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ let rsync_response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ response.response.unwrap().connector_refund_id,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ rsync_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Synchronizes a refund using the manual capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_sync_manually_captured_refund() {
+ let refund_response = CONNECTOR
+ .capture_payment_and_refund(None, None, None, None)
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates a payment using the automatic capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR.make_payment(None, None).await.unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR.make_payment(None, None).await.unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ encoded_data: None,
+ capture_method: None,
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_refund_auto_captured_payment() {
+ let response = CONNECTOR
+ .make_payment_and_refund(None, None, None)
+ .await
+ .unwrap();
+ let rsync_response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ response.response.unwrap().connector_refund_id,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ rsync_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the automatic capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_partially_refund_succeeded_payment() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ let rsync_response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ rsync_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_refund_succeeded_payment_multiple_times() {
+ let authorize_response = CONNECTOR.make_payment(None, None).await.unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let transaction_id = utils::get_connector_transaction_id(authorize_response.response).unwrap();
+ for _x in 0..2 {
+ tokio::time::sleep(std::time::Duration::from_secs(5)).await; // to avoid 404 error
+ let refund_response = CONNECTOR
+ .refund_payment(
+ transaction_id.clone(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ let rsync_response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ rsync_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+ }
+}
+
+// Synchronizes a refund using the automatic capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_sync_refund() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(None, None, None)
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Cards Negative scenerios
+// Creates a payment with incorrect card number.
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_card_number() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_number: Secret::new("1234567891011".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Order creation failure due to problematic input.".to_string(),
+ );
+}
+
+// Creates a payment with empty card number.
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_payment_for_empty_card_number() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_number: Secret::new(String::from("")),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ let x = response.response.unwrap_err();
+ assert_eq!(
+ x.message,
+ "Order creation failure due to problematic input.",
+ );
+}
+
+// Creates a payment with incorrect CVC.
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Order creation failure due to problematic input.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Order creation failure due to problematic input.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Order creation failure due to problematic input.".to_string(),
+ );
+}
+
+// Voids a payment using automatic capture flow (Non 3DS).
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_void_payment_for_auto_capture() {
+ let authorize_response = CONNECTOR.make_payment(None, None).await.unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(txn_id.unwrap(), None, None)
+ .await
+ .unwrap();
+ assert_eq!(
+ void_response.response.unwrap_err().message,
+ "Transaction AUTH_REVERSAL failed. Transaction has already been captured."
+ );
+}
+
+// Captures a payment using invalid connector payment id.
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, None)
+ .await
+ .unwrap();
+
+ capture_response
+ .response
+ .unwrap_err()
+ .message
+ .contains("is not authorized to view transaction");
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+
+#[serial_test::serial]
+#[actix_web::test]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .make_payment_and_refund(
+ None,
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Refund amount cannot be more than the refundable order amount.",
+ );
+}
+
+// Connector dependent test cases goes here
+
+// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs
index ac9bc1196c4..113e78b8471 100644
--- a/crates/router/tests/connectors/checkout.rs
+++ b/crates/router/tests/connectors/checkout.rs
@@ -56,6 +56,8 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {
connector_meta_data: None,
amount_captured: None,
access_token: None,
+ session_token: None,
+ reference_id: None,
}
}
@@ -93,6 +95,8 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> {
address: PaymentAddress::default(),
amount_captured: None,
access_token: None,
+ session_token: None,
+ reference_id: None,
}
}
diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs
index 21c0245fde5..63d14f0497f 100644
--- a/crates/router/tests/connectors/connector_auth.rs
+++ b/crates/router/tests/connectors/connector_auth.rs
@@ -6,11 +6,14 @@ pub(crate) struct ConnectorAuthentication {
pub dlocal: Option<SignatureKey>,
pub aci: Option<BodyKey>,
pub adyen: Option<BodyKey>,
+ pub airwallex: Option<BodyKey>,
pub authorizedotnet: Option<BodyKey>,
+ pub bluesnap: Option<BodyKey>,
pub checkout: Option<BodyKey>,
pub cybersource: Option<SignatureKey>,
pub fiserv: Option<SignatureKey>,
pub globalpay: Option<HeaderKey>,
+ pub nuvei: Option<SignatureKey>,
pub payu: Option<BodyKey>,
pub rapyd: Option<BodyKey>,
pub shift4: Option<HeaderKey>,
diff --git a/crates/router/tests/connectors/cybersource.rs b/crates/router/tests/connectors/cybersource.rs
index f960e3ea2da..3174cb43cf4 100644
--- a/crates/router/tests/connectors/cybersource.rs
+++ b/crates/router/tests/connectors/cybersource.rs
@@ -140,6 +140,7 @@ async fn should_void_already_authorized_payment() {
Some(types::PaymentsCancelData {
connector_transaction_id: "".to_string(),
cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
}),
get_default_payment_info(),
)
diff --git a/crates/router/tests/connectors/dlocal.rs b/crates/router/tests/connectors/dlocal.rs
index 26631f2e4fb..5e82a791fd8 100644
--- a/crates/router/tests/connectors/dlocal.rs
+++ b/crates/router/tests/connectors/dlocal.rs
@@ -108,6 +108,7 @@ async fn should_void_authorized_payment() {
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
}),
Some(get_payment_info()),
)
@@ -458,6 +459,7 @@ pub fn get_payment_info() -> PaymentInfo {
auth_type: None,
access_token: None,
router_return_url: None,
+ connector_meta_data: None,
}
}
// Connector dependent test cases goes here
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index 35b3a0a0e9f..05e23fced4e 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -2,13 +2,16 @@
mod aci;
mod adyen;
+mod airwallex;
mod authorizedotnet;
+mod bluesnap;
mod checkout;
mod connector_auth;
mod cybersource;
mod dlocal;
mod fiserv;
mod globalpay;
+mod nuvei;
mod payu;
mod rapyd;
mod shift4;
diff --git a/crates/router/tests/connectors/nuvei.rs b/crates/router/tests/connectors/nuvei.rs
new file mode 100644
index 00000000000..cf4c3c0aef9
--- /dev/null
+++ b/crates/router/tests/connectors/nuvei.rs
@@ -0,0 +1,414 @@
+use masking::Secret;
+use router::types::{
+ self, api,
+ storage::{self, enums},
+};
+use serde_json::json;
+
+use crate::{
+ connector_auth,
+ utils::{self, ConnectorActions, PaymentInfo},
+};
+
+#[derive(Clone, Copy)]
+struct NuveiTest;
+impl ConnectorActions for NuveiTest {}
+impl utils::Connector for NuveiTest {
+ fn get_data(&self) -> types::api::ConnectorData {
+ use router::connector::Nuvei;
+ types::api::ConnectorData {
+ connector: Box::new(&Nuvei),
+ connector_name: types::Connector::Nuvei,
+ get_token: types::api::GetToken::Connector,
+ }
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ types::ConnectorAuthType::from(
+ connector_auth::ConnectorAuthentication::new()
+ .nuvei
+ .expect("Missing connector authentication configuration"),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "nuvei".to_string()
+ }
+}
+
+static CONNECTOR: NuveiTest = NuveiTest {};
+
+fn get_payment_data() -> Option<types::PaymentsAuthorizeData> {
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_number: Secret::new(String::from("4000027891380961")),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ })
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(get_payment_data(), None)
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(get_payment_data(), None, None)
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Partially captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ get_payment_data(),
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: Some(50),
+ ..utils::PaymentCaptureType::default().0
+ }),
+ None,
+ )
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(get_payment_data(), None)
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ encoded_data: None,
+ capture_method: None,
+ }),
+ Some(PaymentInfo {
+ connector_meta_data: Some(json!({
+ "session_token": authorize_response.session_token.unwrap()
+ })),
+ ..Default::default()
+ }),
+ )
+ .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(
+ get_payment_data(),
+ Some(types::PaymentsCancelData {
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ amount: Some(100),
+ currency: Some(storage::enums::Currency::USD),
+ ..Default::default()
+ }),
+ None,
+ )
+ .await
+ .expect("Void payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
+}
+
+// Refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(get_payment_data(), None, None, None)
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Failure, //Nuvei fails refund always
+ );
+}
+
+// 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(
+ get_payment_data(),
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Failure, //Nuvei fails refund always
+ );
+}
+
+// Creates a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(get_payment_data(), None)
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(get_payment_data(), None)
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ encoded_data: None,
+ capture_method: None,
+ }),
+ Some(PaymentInfo {
+ connector_meta_data: Some(json!({
+ "session_token": authorize_response.session_token.unwrap()
+ })),
+ ..Default::default()
+ }),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_auto_captured_payment() {
+ let response = CONNECTOR
+ .make_payment_and_refund(get_payment_data(), None, None)
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Failure,
+ );
+}
+
+// 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(
+ get_payment_data(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap().refund_status,
+ enums::RefundStatus::Failure,
+ );
+}
+
+// Cards Negative scenerios
+// Creates a payment with incorrect card number.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_card_number() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_number: Secret::new("1234567891011".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Missing or invalid CardData data. Invalid credit card number.".to_string(),
+ );
+}
+
+// Creates a payment with empty card number.
+#[actix_web::test]
+async fn should_fail_payment_for_empty_card_number() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_number: Secret::new(String::from("")),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ let x = response.response.unwrap_err();
+ assert_eq!(
+ x.message,
+ "Missing or invalid CardData data. Missing card number.",
+ );
+}
+
+// Creates a payment with incorrect CVC.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "cardData.CVV is invalid".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Invalid expired date".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+#[actix_web::test]
+async fn should_succeed_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethod::Card(api::Card {
+ card_number: Secret::new(String::from("4000027891380961")),
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..get_payment_data().unwrap()
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// 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(get_payment_data(), None)
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(
+ txn_id.unwrap(),
+ Some(types::PaymentsCancelData {
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ amount: Some(100),
+ currency: Some(storage::enums::Currency::USD),
+ ..Default::default()
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(void_response.status, enums::AttemptStatus::Voided);
+}
+
+// Captures a payment using invalid connector payment id.
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, None)
+ .await
+ .unwrap();
+ assert_eq!(
+ capture_response.response.unwrap_err().message,
+ String::from("Invalid relatedTransactionId")
+ );
+}
+
+// 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(
+ get_payment_data(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ None,
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Failure,
+ );
+}
diff --git a/crates/router/tests/connectors/shift4.rs b/crates/router/tests/connectors/shift4.rs
index 66f24aaf2f4..3d78855b63f 100644
--- a/crates/router/tests/connectors/shift4.rs
+++ b/crates/router/tests/connectors/shift4.rs
@@ -134,6 +134,7 @@ async fn should_void_authorized_payment() {
Some(types::PaymentsCancelData {
connector_transaction_id: "".to_string(),
cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
}),
None,
)
diff --git a/crates/router/tests/connectors/stripe.rs b/crates/router/tests/connectors/stripe.rs
index 04fa9166ad3..ed256218566 100644
--- a/crates/router/tests/connectors/stripe.rs
+++ b/crates/router/tests/connectors/stripe.rs
@@ -143,6 +143,7 @@ async fn should_void_already_authorized_payment() {
Some(types::PaymentsCancelData {
connector_transaction_id: "".to_string(), // this connector_transaction_id will be ignored and the transaction_id from payment authorize data will be used for void
cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
}),
None,
)
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index 94b930534cb..d469eebb383 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -4,10 +4,11 @@ use async_trait::async_trait;
use error_stack::Report;
use masking::Secret;
use router::{
+ configs::settings::Settings,
core::{errors, errors::ConnectorError, payments},
db::StorageImpl,
routes, services,
- types::{self, api, storage::enums, AccessToken, PaymentAddress},
+ types::{self, api, storage::enums, AccessToken, PaymentAddress, RouterData},
};
use wiremock::{Mock, MockServer};
@@ -30,6 +31,7 @@ pub struct PaymentInfo {
pub auth_type: Option<enums::AuthenticationType>,
pub access_token: Option<AccessToken>,
pub router_return_url: Option<String>,
+ pub connector_meta_data: Option<serde_json::Value>,
}
#[async_trait]
@@ -40,7 +42,7 @@ pub trait ConnectorActions: Connector {
payment_info: Option<PaymentInfo>,
) -> Result<types::PaymentsAuthorizeRouterData, Report<ConnectorError>> {
let integration = self.get_data().connector.get_connector_integration();
- let request = self.generate_data(
+ let mut request = self.generate_data(
types::PaymentsAuthorizeData {
confirm: true,
capture_method: Some(storage_models::enums::CaptureMethod::Manual),
@@ -48,6 +50,10 @@ pub trait ConnectorActions: Connector {
},
payment_info,
);
+ let state =
+ routes::AppState::with_storage(Settings::new().unwrap(), StorageImpl::PostgresqlTest)
+ .await;
+ integration.execute_pretasks(&mut request, &state).await?;
call_connector(request, integration).await
}
@@ -57,7 +63,7 @@ pub trait ConnectorActions: Connector {
payment_info: Option<PaymentInfo>,
) -> Result<types::PaymentsAuthorizeRouterData, Report<ConnectorError>> {
let integration = self.get_data().connector.get_connector_integration();
- let request = self.generate_data(
+ let mut request = self.generate_data(
types::PaymentsAuthorizeData {
confirm: true,
capture_method: Some(storage_models::enums::CaptureMethod::Automatic),
@@ -65,6 +71,10 @@ pub trait ConnectorActions: Connector {
},
payment_info,
);
+ let state =
+ routes::AppState::with_storage(Settings::new().unwrap(), StorageImpl::PostgresqlTest)
+ .await;
+ integration.execute_pretasks(&mut request, &state).await?;
call_connector(request, integration).await
}
@@ -342,8 +352,8 @@ pub trait ConnectorActions: Connector {
&self,
req: Req,
info: Option<PaymentInfo>,
- ) -> types::RouterData<Flow, Req, Res> {
- types::RouterData {
+ ) -> RouterData<Flow, Req, Res> {
+ RouterData {
flow: PhantomData,
merchant_id: self.get_name(),
connector: self.get_name(),
@@ -369,9 +379,11 @@ pub trait ConnectorActions: Connector {
.and_then(|a| a.address)
.or_else(|| Some(PaymentAddress::default()))
.unwrap(),
- connector_meta_data: self.get_connector_meta(),
+ connector_meta_data: info.clone().and_then(|a| a.connector_meta_data),
amount_captured: None,
access_token: info.and_then(|a| a.access_token),
+ session_token: None,
+ reference_id: None,
}
}
@@ -384,6 +396,7 @@ pub trait ConnectorActions: Connector {
resource_id.get_connector_transaction_id().ok()
}
Ok(types::PaymentsResponseData::SessionResponse { .. }) => None,
+ Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None,
Err(_) => None,
}
}
@@ -394,10 +407,9 @@ async fn call_connector<
Req: Debug + Clone + 'static,
Resp: Debug + Clone + 'static,
>(
- request: types::RouterData<T, Req, Resp>,
+ request: RouterData<T, Req, Resp>,
integration: services::BoxedConnectorIntegration<'_, T, Req, Resp>,
-) -> Result<types::RouterData<T, Req, Resp>, Report<ConnectorError>> {
- use router::configs::settings::Settings;
+) -> Result<RouterData<T, Req, Resp>, Report<ConnectorError>> {
let conf = Settings::new().unwrap();
let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await;
services::api::execute_connector_processing_step(
@@ -492,6 +504,7 @@ impl Default for PaymentCancelType {
Self(types::PaymentsCancelData {
cancellation_reason: Some("requested_by_customer".to_string()),
connector_transaction_id: "".to_string(),
+ ..Default::default()
})
}
}
@@ -551,6 +564,7 @@ pub fn get_connector_transaction_id(
resource_id.get_connector_transaction_id().ok()
}
Ok(types::PaymentsResponseData::SessionResponse { .. }) => None,
+ Ok(types::PaymentsResponseData::SessionTokenResponse { .. }) => None,
Err(_) => None,
}
}
diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs
index 7452ecda85d..6768003f210 100644
--- a/crates/router/tests/payments.rs
+++ b/crates/router/tests/payments.rs
@@ -296,7 +296,7 @@ async fn payments_create_core() {
email: None,
name: None,
description: Some("Its my first payment request".to_string()),
- return_url: Some("http://example.com/payments".to_string()),
+ return_url: Some(url::Url::parse("http://example.com/payments").unwrap()),
setup_future_usage: Some(api_enums::FutureUsage::OnSession),
authentication_type: Some(api_enums::AuthenticationType::NoThreeDs),
payment_method_data: Some(api::PaymentMethod::Card(api::Card {
@@ -451,7 +451,7 @@ async fn payments_create_core_adyen_no_redirect() {
confirm: Some(true),
customer_id: Some(customer_id),
description: Some("Its my first payment request".to_string()),
- return_url: Some("http://example.com/payments".to_string()),
+ return_url: Some(url::Url::parse("http://example.com/payments").unwrap()),
setup_future_usage: Some(api_enums::FutureUsage::OnSession),
authentication_type: Some(api_enums::AuthenticationType::NoThreeDs),
payment_method_data: Some(api::PaymentMethod::Card(api::Card {
diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs
index d7c80f560af..fea5b65d796 100644
--- a/crates/router/tests/payments2.rs
+++ b/crates/router/tests/payments2.rs
@@ -56,7 +56,7 @@ async fn payments_create_core() {
email: None,
name: None,
description: Some("Its my first payment request".to_string()),
- return_url: Some("http://example.com/payments".to_string()),
+ return_url: Some(url::Url::parse("http://example.com/payments").unwrap()),
setup_future_usage: None,
authentication_type: Some(api_enums::AuthenticationType::NoThreeDs),
payment_method_data: Some(api::PaymentMethod::Card(api::Card {
@@ -206,7 +206,7 @@ async fn payments_create_core_adyen_no_redirect() {
confirm: Some(true),
customer_id: Some(customer_id),
description: Some("Its my first payment request".to_string()),
- return_url: Some("http://example.com/payments".to_string()),
+ return_url: Some(url::Url::parse("http://example.com/payments").unwrap()),
setup_future_usage: Some(api_enums::FutureUsage::OffSession),
authentication_type: Some(api_enums::AuthenticationType::NoThreeDs),
payment_method_data: Some(api::PaymentMethod::Card(api::Card {
diff --git a/crates/storage_models/src/enums.rs b/crates/storage_models/src/enums.rs
index 89e37f74996..1c9328bba98 100644
--- a/crates/storage_models/src/enums.rs
+++ b/crates/storage_models/src/enums.rs
@@ -25,6 +25,7 @@ pub mod diesel_exports {
serde::Serialize,
strum::Display,
strum::EnumString,
+ frunk::LabelledGeneric,
)]
#[router_derive::diesel_enum(storage_type = "pg_enum")]
#[serde(rename_all = "snake_case")]
diff --git a/loadtest/config/Development.toml b/loadtest/config/Development.toml
index 2887ec39221..9de76944e07 100644
--- a/loadtest/config/Development.toml
+++ b/loadtest/config/Development.toml
@@ -85,9 +85,36 @@ base_url = "https://apple-pay-gateway.apple.com/"
[connectors.klarna]
base_url = "https://api-na.playground.klarna.com/"
+[connectors.bluesnap]
+base_url = "https://sandbox.bluesnap.com/"
+
+[connectors.nuvei]
+base_url = "https://ppp-test.nuvei.com/"
+
+[connectors.airwallex]
+base_url = "https://api-demo.airwallex.com/"
+
[connectors.dlocal]
base_url = "https://sandbox.dlocal.com/"
[connectors.supported]
wallets = ["klarna", "braintree", "applepay"]
-cards = ["stripe", "adyen", "authorizedotnet", "checkout", "braintree", "cybersource", "shift4", "worldpay", "globalpay", "dlocal"]
+cards = [
+ "aci",
+ "adyen",
+ "airwallex",
+ "authorizedotnet",
+ "bluesnap",
+ "braintree",
+ "checkout",
+ "cybersource",
+ "dlocal",
+ "fiserv",
+ "globalpay",
+ "nuvei",
+ "payu",
+ "shift4",
+ "stripe",
+ "worldline",
+ "worldpay",
+]
diff --git a/openapi/generated.json b/openapi/generated.json
index e94630c1e4c..0d3fc6023a3 100644
--- a/openapi/generated.json
+++ b/openapi/generated.json
@@ -1916,11 +1916,11 @@
"properties": {
"label": {
"type": "string",
- "description": "the label must be non-empty to pass validation."
+ "description": "The label must be the name of the merchant."
},
"type": {
"type": "string",
- "description": "The type of label"
+ "description": "A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending."
},
"amount": {
"type": "string",
@@ -1942,7 +1942,7 @@
}
]
},
- "ApplePayRequest": {
+ "ApplePayPaymentRequest": {
"type": "object",
"required": [
"country_code",
@@ -1979,7 +1979,7 @@
}
}
},
- "ApplePaySessionObject": {
+ "ApplePaySessionResponse": {
"type": "object",
"required": [
"epoch_timestamp",
@@ -2011,7 +2011,7 @@
},
"nonce": {
"type": "string",
- "description": "Applepay generates unique ID (UUID) value"
+ "description": "Apple pay generated unique ID (UUID) value"
},
"merchant_identifier": {
"type": "string",
@@ -2044,18 +2044,18 @@
}
}
},
- "ApplepayData": {
+ "ApplepaySessionTokenResponse": {
"type": "object",
"required": [
- "session_object",
- "payment_request_object"
+ "session_token_data",
+ "payment_request_data"
],
"properties": {
- "session_object": {
- "$ref": "#/components/schemas/ApplePaySessionObject"
+ "session_token_data": {
+ "$ref": "#/components/schemas/ApplePaySessionResponse"
},
- "payment_request_object": {
- "$ref": "#/components/schemas/ApplePayRequest"
+ "payment_request_data": {
+ "$ref": "#/components/schemas/ApplePayPaymentRequest"
}
}
},
@@ -2843,7 +2843,19 @@
}
}
},
- "GpayData": {
+ "GpayMerchantInfo": {
+ "type": "object",
+ "required": [
+ "merchant_name"
+ ],
+ "properties": {
+ "merchant_name": {
+ "type": "string",
+ "description": "The name of the merchant"
+ }
+ }
+ },
+ "GpaySessionTokenResponse": {
"type": "object",
"required": [
"merchant_info",
@@ -2865,18 +2877,6 @@
}
}
},
- "GpayMerchantInfo": {
- "type": "object",
- "required": [
- "merchant_name"
- ],
- "properties": {
- "merchant_name": {
- "type": "string",
- "description": "The name of the merchant"
- }
- }
- },
"GpayTokenParameters": {
"type": "object",
"required": [
@@ -2951,7 +2951,13 @@
"requires_capture"
]
},
- "KlarnaData": {
+ "KlarnaIssuer": {
+ "type": "string",
+ "enum": [
+ "klarna"
+ ]
+ },
+ "KlarnaSessionTokenResponse": {
"type": "object",
"required": [
"session_token",
@@ -2968,12 +2974,6 @@
}
}
},
- "KlarnaIssuer": {
- "type": "string",
- "enum": [
- "klarna"
- ]
- },
"ListCustomerPaymentMethodsResponse": {
"type": "object",
"required": [
@@ -3057,26 +3057,10 @@
]
},
"accepted_countries": {
- "type": "array",
- "items": {
- "type": "string",
- "description": "List of Countries accepted or has the processing capabilities of the processor"
- },
- "example": [
- "US",
- "UK",
- "IN"
- ]
+ "$ref": "#/components/schemas/admin.AcceptedCountries"
},
"accepted_currencies": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/Currency"
- },
- "example": [
- "USD",
- "EUR"
- ]
+ "$ref": "#/components/schemas/admin.AcceptedCurrencies"
},
"minimum_amount": {
"type": "integer",
@@ -3108,6 +3092,17 @@
"example": [
"redirect_to_url"
]
+ },
+ "eligible_connectors": {
+ "type": "array",
+ "items": {
+ "type": "string",
+ "description": "Eligible connectors for this payment method"
+ },
+ "example": [
+ "stripe",
+ "adyen"
+ ]
}
}
},
@@ -3659,14 +3654,31 @@
},
"example": [
{
- "accepted_countries": [
- "in",
- "us"
- ],
- "accepted_currencies": [
- "AED",
- "AED"
- ],
+ "accepted_countries": {
+ "disable_only": [
+ "FR",
+ "DE",
+ "IN"
+ ],
+ "enable_all": false,
+ "enable_only": [
+ "UK",
+ "AU"
+ ]
+ },
+ "accepted_currencies": {
+ "disable_only": [
+ "INR",
+ "CAD",
+ "AED",
+ "JPY"
+ ],
+ "enable_all": false,
+ "enable_only": [
+ "EUR",
+ "USD"
+ ]
+ },
"installment_payment_enabled": true,
"maximum_amount": 68607706,
"minimum_amount": 1,
@@ -4036,26 +4048,10 @@
]
},
"accepted_currencies": {
- "type": "array",
- "items": {
- "$ref": "#/components/schemas/Currency"
- },
- "example": [
- "USD",
- "EUR",
- "AED"
- ]
+ "$ref": "#/components/schemas/AcceptedCurrencies"
},
"accepted_countries": {
- "type": "array",
- "items": {
- "type": "string",
- "description": "List of Countries accepted or has the processing capabilities of the processor"
- },
- "example": [
- "US",
- "IN"
- ]
+ "$ref": "#/components/schemas/AcceptedCountries"
},
"minimum_amount": {
"type": "integer",
@@ -4587,7 +4583,7 @@
}
}
},
- "PaypalData": {
+ "PaypalSessionTokenResponse": {
"type": "object",
"required": [
"session_token"
@@ -4891,7 +4887,7 @@
{
"allOf": [
{
- "$ref": "#/components/schemas/GpayData"
+ "$ref": "#/components/schemas/GpaySessionTokenResponse"
},
{
"type": "object",
@@ -4912,7 +4908,7 @@
{
"allOf": [
{
- "$ref": "#/components/schemas/KlarnaData"
+ "$ref": "#/components/schemas/KlarnaSessionTokenResponse"
},
{
"type": "object",
@@ -4933,7 +4929,7 @@
{
"allOf": [
{
- "$ref": "#/components/schemas/PaypalData"
+ "$ref": "#/components/schemas/PaypalSessionTokenResponse"
},
{
"type": "object",
@@ -4954,7 +4950,7 @@
{
"allOf": [
{
- "$ref": "#/components/schemas/ApplepayData"
+ "$ref": "#/components/schemas/ApplepaySessionTokenResponse"
},
{
"type": "object",
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index e387e192c54..be5f201656e 100644
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -18,13 +18,13 @@ sed -i'' -e "s/};/${pg}::${pgc},\n};/" $conn.rs
sed -i'' -e "s/_ => Err/\"${pg}\" => Ok(Box::new(\&connector::${pgc})),\n\t\t\t_ => Err/" $src/types/api.rs
sed -i'' -e "s/pub supported: SupportedConnectors,/pub supported: SupportedConnectors,\n\tpub ${pg}: ConnectorParams,/" $src/configs/settings.rs
sed -i'' -e "s/\[scheduler\]/[connectors.${pg}]\nbase_url = \"\"\n\n[scheduler]/" config/Development.toml
-sed -r -i'' -e "s/cards = \[(.*)\]/cards = [\1, \"${pg}\"]/" config/Development.toml
+sed -r -i'' -e "s/cards = \[/cards = [\n\t\"${pg}\",/" config/Development.toml
sed -i'' -e "s/\[connectors.supported\]/[connectors.${pg}]\nbase_url = ""\n\n[connectors.supported]/" config/docker_compose.toml
-sed -r -i'' -e "s/cards = \[(.*)\]/cards = [\1, \"${pg}\"]/" config/docker_compose.toml
+sed -r -i'' -e "s/cards = \[/cards = [\n\t\"${pg}\",/" config/docker_compose.toml
sed -i'' -e "s/\[connectors.supported\]/[connectors.${pg}]\nbase_url = ""\n\n[connectors.supported]/" config/config.example.toml
-sed -r -i'' -e "s/cards = \[(.*)\]/cards = [\1, \"${pg}\"]/" config/config.example.toml
+sed -r -i'' -e "s/cards = \[/cards = [\n\t\"${pg}\",/" config/config.example.toml
sed -i'' -e "s/\[connectors.supported\]/[connectors.${pg}]\nbase_url = ""\n\n[connectors.supported]/" loadtest/config/Development.toml
-sed -r -i'' -e "s/cards = \[(.*)\]/cards = [\1, \"${pg}\"]/" loadtest/config/Development.toml
+sed -r -i'' -e "s/cards = \[/cards = [\n\t\"${pg}\",/" loadtest/config/Development.toml
sed -i'' -e "s/Dummy,/Dummy,\n\t${pgc},/" crates/api_models/src/enums.rs
sed -i'' -e "s/pub enum RoutableConnectors {/pub enum RoutableConnectors {\n\t${pgc},/" crates/api_models/src/enums.rs
# remove temporary files created in above step
|
chore
|
merging back release v0.3.0 back to main (#636) (#655)
|
b7d557367a3a5aca478ffd2087af8077bc4e7e2b
|
2023-10-19 19:44:26
|
Joel Tony
|
feat(connector): [Klarna] Add order id as the reference id to merchant (#2614)
| false
|
diff --git a/crates/router/src/connector/klarna/transformers.rs b/crates/router/src/connector/klarna/transformers.rs
index 31e356d4765..563410ee99d 100644
--- a/crates/router/src/connector/klarna/transformers.rs
+++ b/crates/router/src/connector/klarna/transformers.rs
@@ -159,12 +159,14 @@ impl TryFrom<types::PaymentsResponseRouterData<KlarnaPaymentsResponse>>
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.order_id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.order_id.clone(),
+ ),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.order_id.clone()),
}),
status: item.response.fraud_status.into(),
..item.data
|
feat
|
[Klarna] Add order id as the reference id to merchant (#2614)
|
d30b58abb5e716b70c2dadec9e6f13c9e3403b6f
|
2023-11-30 15:31:01
|
DEEPANSHU BANSAL
|
feat(connector): [BANKOFAMERICA] Add Required Fields for GPAY (#3014)
| false
|
diff --git a/crates/router/src/configs/defaults.rs b/crates/router/src/configs/defaults.rs
index f5c3b46b27f..f9bfcae1ca1 100644
--- a/crates/router/src/configs/defaults.rs
+++ b/crates/router/src/configs/defaults.rs
@@ -503,15 +503,6 @@ impl Default for super::settings::RequiredFields {
value: None,
}
),
- (
- "payment_method_data.card.card_holder_name".to_string(),
- RequiredFieldInfo {
- required_field: "payment_method_data.card.card_holder_name".to_string(),
- display_name: "card_holder_name".to_string(),
- field_type: enums::FieldType::UserFullName,
- value: None,
- }
- ),
(
"email".to_string(),
RequiredFieldInfo {
@@ -2418,6 +2409,129 @@ impl Default for super::settings::RequiredFields {
common: HashMap::new(),
}
),
+ (
+ enums::Connector::Bankofamerica,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from(
+ [
+ (
+ "payment_method_data.card.card_number".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_number".to_string(),
+ display_name: "card_number".to_string(),
+ field_type: enums::FieldType::UserCardNumber,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_month".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_month".to_string(),
+ display_name: "card_exp_month".to_string(),
+ field_type: enums::FieldType::UserCardExpiryMonth,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_exp_year".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_exp_year".to_string(),
+ display_name: "card_exp_year".to_string(),
+ field_type: enums::FieldType::UserCardExpiryYear,
+ value: None,
+ }
+ ),
+ (
+ "payment_method_data.card.card_cvc".to_string(),
+ RequiredFieldInfo {
+ required_field: "payment_method_data.card.card_cvc".to_string(),
+ display_name: "card_cvc".to_string(),
+ field_type: enums::FieldType::UserCardCvc,
+ value: None,
+ }
+ ),
+ (
+ "email".to_string(),
+ RequiredFieldInfo {
+ required_field: "email".to_string(),
+ display_name: "email".to_string(),
+ field_type: enums::FieldType::UserEmailAddress,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.first_name".to_string(),
+ display_name: "billing_first_name".to_string(),
+ field_type: enums::FieldType::UserBillingName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.last_name".to_string(),
+ display_name: "billing_last_name".to_string(),
+ field_type: enums::FieldType::UserBillingName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserAddressCity,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.state".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.state".to_string(),
+ display_name: "state".to_string(),
+ field_type: enums::FieldType::UserAddressState,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ ),
+ (
+ "billing.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserAddressLine1,
+ value: None,
+ }
+ ),
+ ]
+ ),
+ common: HashMap::new(),
+ }
+ ),
(
enums::Connector::Bluesnap,
RequiredFieldFinal {
@@ -4250,6 +4364,93 @@ impl Default for super::settings::RequiredFields {
common: HashMap::new(),
}
),
+ (
+ enums::Connector::Bankofamerica,
+ RequiredFieldFinal {
+ mandate: HashMap::new(),
+ non_mandate: HashMap::from(
+ [
+ (
+ "email".to_string(),
+ RequiredFieldInfo {
+ required_field: "email".to_string(),
+ display_name: "email".to_string(),
+ field_type: enums::FieldType::UserEmailAddress,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.first_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.first_name".to_string(),
+ display_name: "billing_first_name".to_string(),
+ field_type: enums::FieldType::UserBillingName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.last_name".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.last_name".to_string(),
+ display_name: "billing_last_name".to_string(),
+ field_type: enums::FieldType::UserBillingName,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.city".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.city".to_string(),
+ display_name: "city".to_string(),
+ field_type: enums::FieldType::UserAddressCity,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.state".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.state".to_string(),
+ display_name: "state".to_string(),
+ field_type: enums::FieldType::UserAddressState,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.zip".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.zip".to_string(),
+ display_name: "zip".to_string(),
+ field_type: enums::FieldType::UserAddressPincode,
+ value: None,
+ }
+ ),
+ (
+ "billing.address.country".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.country".to_string(),
+ display_name: "country".to_string(),
+ field_type: enums::FieldType::UserAddressCountry{
+ options: vec![
+ "ALL".to_string(),
+ ]
+ },
+ value: None,
+ }
+ ),
+ (
+ "billing.address.line1".to_string(),
+ RequiredFieldInfo {
+ required_field: "billing.address.line1".to_string(),
+ display_name: "line1".to_string(),
+ field_type: enums::FieldType::UserAddressLine1,
+ value: None,
+ }
+ ),
+ ]
+ ),
+ common: HashMap::new(),
+ }
+ ),
]),
},
),
|
feat
|
[BANKOFAMERICA] Add Required Fields for GPAY (#3014)
|
a1a08ba7338a8df94a4b0cee10a4f6ba9ff1301d
|
2024-06-14 05:44:49
|
github-actions
|
chore(version): 2024.06.14.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 32bff5be635..831f7a2ac76 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,26 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.06.14.0
+
+### Features
+
+- **connectors:** [Iatapay] add payment methods ([#4968](https://github.com/juspay/hyperswitch/pull/4968)) ([`0e059e7`](https://github.com/juspay/hyperswitch/commit/0e059e7d847b0c15ed120c72bb4902ac60e6f955))
+- **payment_methods:** Use Ephemeral auth for pm list and pm delete ([#4996](https://github.com/juspay/hyperswitch/pull/4996)) ([`ad7886a`](https://github.com/juspay/hyperswitch/commit/ad7886a6ff636f99e62601483c907f5c90954eb4))
+- **router:** Include the pre-routing connectors in Apple Pay retries ([#4952](https://github.com/juspay/hyperswitch/pull/4952)) ([`fb83661`](https://github.com/juspay/hyperswitch/commit/fb836618a66f57fca5c78aa1c2a255792ab1dfb4))
+
+### Bug Fixes
+
+- **cypress:** Add `jwt_token` and `cookie` for routing test ([#4953](https://github.com/juspay/hyperswitch/pull/4953)) ([`0a86cdb`](https://github.com/juspay/hyperswitch/commit/0a86cdb5060679e9609c2db6d2f82b8edda1b374))
+
+### Refactors
+
+- **core:** Make country aggregator nodes weak for list payment methods ([#4994](https://github.com/juspay/hyperswitch/pull/4994)) ([`18493bd`](https://github.com/juspay/hyperswitch/commit/18493bd8f03b933b15bc3c40b3501222587fc59f))
+
+**Full Changelog:** [`2024.06.13.0...2024.06.14.0`](https://github.com/juspay/hyperswitch/compare/2024.06.13.0...2024.06.14.0)
+
+- - -
+
## 2024.06.13.0
### Features
|
chore
|
2024.06.14.0
|
7666748922ca209efea48dfc104322910326526b
|
2023-02-07 14:57:39
|
Nishant Joshi
|
fix: decide refund type by the request and not defaults (#505)
| false
|
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 6e8be43e251..f7f46b56505 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -491,7 +491,7 @@ pub async fn validate_and_create_refund(
.set_merchant_id(merchant_account.merchant_id.clone())
.set_connector_transaction_id(connecter_transaction_id.to_string())
.set_connector(connector)
- .set_refund_type(enums::RefundType::RegularRefund)
+ .set_refund_type(req.refund_type.unwrap_or_default().foreign_into())
.set_total_amount(payment_attempt.amount)
.set_refund_amount(refund_amount)
.set_currency(currency)
|
fix
|
decide refund type by the request and not defaults (#505)
|
b8c927593a85792588e582bf25f2daadfa5f7fb0
|
2024-03-21 14:43:01
|
Sai Harsha Vardhan
|
fix(router): handle redirection to return_url from nested iframe in separate 3ds flow (#4164)
| false
|
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 569538b5aff..0a3a93923b7 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -1100,7 +1100,7 @@ impl<Ctx: PaymentMethodRetrieve> PaymentRedirectFlow<Ctx> for PaymentAuthenticat
try {{
// if inside iframe, send post message to parent for redirection
if (window.self !== window.parent) {{
- window.parent.postMessage({{openurl: return_url}}, '*')
+ window.top.postMessage({{openurl: return_url}}, '*')
// if parent, redirect self to return_url
}} else {{
window.location.href = return_url
|
fix
|
handle redirection to return_url from nested iframe in separate 3ds flow (#4164)
|
0f6c97c47ddd0980ace13840faadc4b6eefaa48e
|
2024-03-15 15:18:30
|
Prajjwal Kumar
|
refactor(core): remove pament_method_status from payment_data (#4061)
| false
|
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 4eb05fdbafa..de4fc30a9b1 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -2222,7 +2222,6 @@ where
pub authorizations: Vec<diesel_models::authorization::Authorization>,
pub authentication: Option<(storage::Authentication, AuthenticationData)>,
pub frm_metadata: Option<serde_json::Value>,
- pub payment_method_status: Option<common_enums::PaymentMethodStatus>,
}
#[derive(Debug, Default, Clone)]
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index ba270e1d001..65b856364cc 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -165,7 +165,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
- payment_method_status: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index 8072984e20e..b25c0e2b909 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -175,7 +175,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
card_cvc: None,
creds_identifier,
pm_token: None,
- payment_method_status: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 9e6751757a1..47d339f15be 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -218,7 +218,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
sessions_token: vec![],
card_cvc: None,
creds_identifier,
- payment_method_status: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: 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 0f08d14e439..8a773904ea3 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -285,7 +285,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
multiple_capture_data: None,
redirect_response,
surcharge_details: None,
- payment_method_status: None,
frm_message: None,
payment_link_data: None,
incremental_authorization_details: None,
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 3ecb98a9c9f..97b1d8e9817 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -609,7 +609,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
card_cvc: request.card_cvc.clone(),
creds_identifier,
pm_token: None,
- payment_method_status: None,
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key: None,
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 5efbee0bc6b..7c856242659 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -410,7 +410,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
connector_customer_id: None,
recurring_mandate_payment_data,
ephemeral_key,
- payment_method_status: None,
multiple_capture_data: None,
redirect_response: None,
surcharge_details,
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index b59e87b826c..591ecb0a118 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -170,7 +170,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
surcharge_details: None,
frm_message: frm_response.ok(),
payment_link_data: None,
- payment_method_status: None,
incremental_authorization_details: None,
authorizations: vec![],
authentication: None,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 447ca14b156..2afac8b6139 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -441,7 +441,12 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
router_data: types::RouterData<F, T, types::PaymentsResponseData>,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentData<F>> {
- payment_data.payment_method_status = router_data.payment_method_status;
+ router_data.payment_method_status.and_then(|status| {
+ payment_data
+ .payment_method_info
+ .as_mut()
+ .map(|info| info.status = status)
+ });
let (capture_update, mut payment_attempt_update) = match router_data.response.clone() {
Err(err) => {
let (capture_update, attempt_update) = match payment_data.multiple_capture_data {
@@ -888,7 +893,12 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
)?;
payment_data.payment_intent = payment_intent;
- payment_data.payment_method_status = router_data.payment_method_status;
+ router_data.payment_method_status.and_then(|status| {
+ payment_data
+ .payment_method_info
+ .as_mut()
+ .map(|info| info.status = status)
+ });
Ok(payment_data)
}
@@ -907,7 +917,10 @@ async fn update_payment_method_status<F: Clone>(
if pm.status != attempt_status.into() {
let updated_pm_status = common_enums::PaymentMethodStatus::from(attempt_status);
- payment_data.payment_method_status = Some(updated_pm_status);
+ payment_data
+ .payment_method_info
+ .as_mut()
+ .map(|info| info.status = updated_pm_status);
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(updated_pm_status),
};
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 7129645601c..805b5fb3630 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -186,7 +186,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
sessions_token: vec![],
card_cvc: None,
creds_identifier,
- payment_method_status: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index ee85ffa8a5d..520336be0e1 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -181,7 +181,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
redirect_response: None,
surcharge_details: None,
frm_message: None,
- payment_method_status: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index 60b2c807766..fd28fbd18d5 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -467,7 +467,6 @@ async fn get_tracker_for_sync<
card_cvc: None,
creds_identifier,
pm_token: None,
- payment_method_status: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
ephemeral_key: None,
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 626b123a835..2a0b99bc54b 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -421,7 +421,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
redirect_response: None,
surcharge_details,
frm_message: None,
- payment_method_status: None,
payment_link_data: None,
incremental_authorization_details: None,
authorizations: vec![],
diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
index d60e56de662..ab7ab56d94f 100644
--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
@@ -134,7 +134,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
sessions_token: vec![],
card_cvc: None,
creds_identifier: None,
- payment_method_status: None,
pm_token: None,
connector_customer_id: None,
recurring_mandate_payment_data: None,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 73d780c0960..caed1b3a123 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -148,7 +148,7 @@ where
access_token: None,
session_token: None,
reference_id: None,
- payment_method_status: payment_data.payment_method_status,
+ payment_method_status: payment_data.payment_method_info.map(|info| info.status),
payment_method_token: payment_data.pm_token.map(types::PaymentMethodToken::Token),
connector_customer: payment_data.connector_customer_id,
recurring_mandate_payment_data: payment_data.recurring_mandate_payment_data,
@@ -781,7 +781,9 @@ where
payment_attempt.external_three_ds_authentication_attempted,
)
.set_payment_method_id(payment_attempt.payment_method_id)
- .set_payment_method_status(payment_data.payment_method_status)
+ .set_payment_method_status(
+ payment_data.payment_method_info.map(|info| info.status),
+ )
.to_owned(),
headers,
))
|
refactor
|
remove pament_method_status from payment_data (#4061)
|
23bd364a7819a48c3f5f89ff5b71cc237d6e2d46
|
2023-10-30 13:13:28
|
Swangi Kumari
|
feat(connector): [VOLT] Implement payment flows and bank redirect payment method (#2582)
| false
|
diff --git a/.github/secrets/connector_auth.toml.gpg b/.github/secrets/connector_auth.toml.gpg
index ae8c0961264..487e436df46 100644
Binary files a/.github/secrets/connector_auth.toml.gpg and b/.github/secrets/connector_auth.toml.gpg differ
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 65f6dea1b5e..ee67c1187e6 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -116,7 +116,7 @@ pub enum Connector {
Trustpay,
// Tsys,
Tsys,
- //Volt, added as template code for future usage,
+ Volt,
Wise,
Worldline,
Worldpay,
@@ -135,6 +135,7 @@ impl Connector {
| (Self::Payu, _)
| (Self::Trustpay, PaymentMethod::BankRedirect)
| (Self::Iatapay, _)
+ | (Self::Volt, _)
)
}
pub fn supports_file_storage_module(&self) -> bool {
@@ -235,7 +236,7 @@ pub enum RoutableConnectors {
Trustpay,
// Tsys,
Tsys,
- // Volt, added as template code for future usage
+ Volt,
Wise,
Worldline,
Worldpay,
diff --git a/crates/router/src/connector/volt.rs b/crates/router/src/connector/volt.rs
index 92d2955a0e0..e1af4c008b1 100644
--- a/crates/router/src/connector/volt.rs
+++ b/crates/router/src/connector/volt.rs
@@ -3,7 +3,7 @@ pub mod transformers;
use std::fmt::Debug;
use error_stack::{IntoReport, ResultExt};
-use masking::ExposeInterface;
+use masking::{ExposeInterface, PeekInterface};
use transformers as volt;
use crate::{
@@ -64,8 +64,15 @@ where
.to_string()
.into(),
)];
- let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
- header.append(&mut api_key);
+ let access_token = req
+ .access_token
+ .clone()
+ .ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
+ let auth_header = (
+ headers::AUTHORIZATION.to_string(),
+ format!("Bearer {}", access_token.token.peek()).into_masked(),
+ );
+ header.push(auth_header);
Ok(header)
}
}
@@ -95,7 +102,7 @@ impl ConnectorCommon for Volt {
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
- auth.api_key.expose().into_masked(),
+ auth.username.expose().into_masked(),
)])
}
@@ -108,11 +115,20 @@ impl ConnectorCommon for Volt {
.parse_struct("VoltErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ let reason = match &response.exception.error_list {
+ Some(error_list) => error_list
+ .iter()
+ .map(|error| error.message.clone())
+ .collect::<Vec<String>>()
+ .join(" & "),
+ None => response.exception.message.clone(),
+ };
+
Ok(ErrorResponse {
status_code: res.status_code,
- code: response.code,
- message: response.message,
- reason: response.reason,
+ code: response.exception.message.to_string(),
+ message: response.exception.message.clone(),
+ reason: Some(reason),
})
}
}
@@ -130,6 +146,84 @@ impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::Payme
impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
for Volt
{
+ fn get_url(
+ &self,
+ _req: &types::RefreshTokenRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Ok(format!("{}oauth", self.base_url(connectors)))
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ "application/x-www-form-urlencoded"
+ }
+ fn get_headers(
+ &self,
+ _req: &types::RefreshTokenRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ Ok(vec![(
+ headers::CONTENT_TYPE.to_string(),
+ types::RefreshTokenType::get_content_type(self)
+ .to_string()
+ .into(),
+ )])
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::RefreshTokenRouterData,
+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
+ let req_obj = volt::VoltAuthUpdateRequest::try_from(req)?;
+ let volt_req = types::RequestBody::log_and_get_request_body(
+ &req_obj,
+ utils::Encode::<volt::VoltAuthUpdateRequest>::url_encode,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ Ok(Some(volt_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefreshTokenRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let req = Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .attach_default_headers()
+ .headers(types::RefreshTokenType::get_headers(self, req, connectors)?)
+ .url(&types::RefreshTokenType::get_url(self, req, connectors)?)
+ .body(types::RefreshTokenType::get_request_body(self, req)?)
+ .build(),
+ );
+ Ok(req)
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefreshTokenRouterData,
+ res: Response,
+ ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> {
+ let response: volt::VoltAuthUpdateResponse = res
+ .response
+ .parse_struct("Volt VoltAuthUpdateResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
}
impl
@@ -159,9 +253,9 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
_req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ Ok(format!("{}v2/payments", self.base_url(connectors)))
}
fn get_request_body(
@@ -244,10 +338,18 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let connector_payment_id = req
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
+ Ok(format!(
+ "{}payments/{connector_payment_id}",
+ self.base_url(connectors)
+ ))
}
fn build_request(
@@ -270,7 +372,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
data: &types::PaymentsSyncRouterData,
res: Response,
) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
- let response: volt::VoltPaymentsResponse = res
+ let response: volt::VoltPsyncResponse = res
.response
.parse_struct("volt PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -381,10 +483,14 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let connector_payment_id = req.request.connector_transaction_id.clone();
+ Ok(format!(
+ "{}payments/{connector_payment_id}/request-refund",
+ self.base_url(connectors),
+ ))
}
fn get_request_body(
@@ -448,64 +554,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Volt {
- fn get_headers(
- &self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- self.build_headers(req, connectors)
- }
-
- fn get_content_type(&self) -> &'static str {
- self.common_get_content_type()
- }
-
- fn get_url(
- &self,
- _req: &types::RefundSyncRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
- }
-
- fn build_request(
- &self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
- .attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
- .body(types::RefundSyncType::get_request_body(self, req)?)
- .build(),
- ))
- }
-
- fn handle_response(
- &self,
- data: &types::RefundSyncRouterData,
- res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
- let response: volt::RefundResponse =
- res.response
- .parse_struct("volt RefundSyncResponse")
- .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
- types::RouterData::try_from(types::ResponseRouterData {
- response,
- data: data.clone(),
- http_code: res.status_code,
- })
- }
-
- fn get_error_response(
- &self,
- res: Response,
- ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
- self.build_error_response(res)
- }
+ //Volt does not support Refund Sync
}
#[async_trait::async_trait]
diff --git a/crates/router/src/connector/volt/transformers.rs b/crates/router/src/connector/volt/transformers.rs
index 1bbbe5ff1eb..e603ef2db06 100644
--- a/crates/router/src/connector/volt/transformers.rs
+++ b/crates/router/src/connector/volt/transformers.rs
@@ -1,12 +1,17 @@
+use common_utils::pii::Email;
+use diesel_models::enums;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::PaymentsAuthorizeRequestData,
+ connector::utils::{self, AddressDetailsData, RouterData},
core::errors,
- types::{self, api, storage::enums},
+ services,
+ types::{self, api, storage::enums as storage_enums},
};
+const PASSWORD: &str = "password";
+
pub struct VoltRouterData<T> {
pub amount: i64, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
@@ -29,7 +34,6 @@ impl<T>
T,
),
) -> Result<Self, Self::Error> {
- //Todo : use utils to convert the amount to the type of amount that a connector accepts
Ok(Self {
amount,
router_data: item,
@@ -37,20 +41,38 @@ impl<T>
}
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "camelCase")]
pub struct VoltPaymentsRequest {
amount: i64,
- card: VoltCard,
+ currency_code: storage_enums::Currency,
+ #[serde(rename = "type")]
+ transaction_type: TransactionType,
+ merchant_internal_reference: String,
+ shopper: ShopperDetails,
+ notification_url: Option<String>,
+ payment_success_url: Option<String>,
+ payment_failure_url: Option<String>,
+ payment_pending_url: Option<String>,
+ payment_cancel_url: Option<String>,
+}
+
+#[derive(Debug, Serialize)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum TransactionType {
+ Bills,
+ Goods,
+ PersonToPerson,
+ Other,
+ Services,
}
-#[derive(Default, Debug, Serialize, Eq, PartialEq)]
-pub struct VoltCard {
- name: Secret<String>,
- number: cards::CardNumber,
- expiry_month: Secret<String>,
- expiry_year: Secret<String>,
- cvc: Secret<String>,
- complete: bool,
+#[derive(Debug, Serialize)]
+pub struct ShopperDetails {
+ reference: String,
+ email: Option<Email>,
+ first_name: Secret<String>,
+ last_name: Secret<String>,
}
impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPaymentsRequest {
@@ -59,63 +81,184 @@ impl TryFrom<&VoltRouterData<&types::PaymentsAuthorizeRouterData>> for VoltPayme
item: &VoltRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
- api::PaymentMethodData::Card(req_card) => {
- let card = VoltCard {
- name: req_card.card_holder_name,
- number: req_card.card_number,
- expiry_month: req_card.card_exp_month,
- expiry_year: req_card.card_exp_year,
- cvc: req_card.card_cvc,
- complete: item.router_data.request.is_auto_capture()?,
- };
- Ok(Self {
- amount: item.amount.to_owned(),
- card,
- })
+ api::PaymentMethodData::BankRedirect(ref bank_redirect) => match bank_redirect {
+ api_models::payments::BankRedirectData::OpenBankingUk { .. } => {
+ let amount = item.amount;
+ let currency_code = item.router_data.request.currency;
+ let merchant_internal_reference =
+ item.router_data.connector_request_reference_id.clone();
+ let payment_success_url = item.router_data.request.router_return_url.clone();
+ let payment_failure_url = item.router_data.request.router_return_url.clone();
+ let payment_pending_url = item.router_data.request.router_return_url.clone();
+ let payment_cancel_url = item.router_data.request.router_return_url.clone();
+ let notification_url = item.router_data.request.webhook_url.clone();
+ let address = item.router_data.get_billing_address()?;
+ let shopper = ShopperDetails {
+ email: item.router_data.request.email.clone(),
+ first_name: address.get_first_name()?.to_owned(),
+ last_name: address.get_last_name()?.to_owned(),
+ reference: item.router_data.get_customer_id()?.to_owned(),
+ };
+ let transaction_type = TransactionType::Services; //transaction_type is a form of enum, it is pre defined and value for this can not be taken from user so we are keeping it as Services as this transaction is type of service.
+
+ Ok(Self {
+ amount,
+ currency_code,
+ merchant_internal_reference,
+ payment_success_url,
+ payment_failure_url,
+ payment_pending_url,
+ payment_cancel_url,
+ notification_url,
+ shopper,
+ transaction_type,
+ })
+ }
+ api_models::payments::BankRedirectData::BancontactCard { .. }
+ | api_models::payments::BankRedirectData::Bizum {}
+ | api_models::payments::BankRedirectData::Blik { .. }
+ | api_models::payments::BankRedirectData::Eps { .. }
+ | api_models::payments::BankRedirectData::Giropay { .. }
+ | api_models::payments::BankRedirectData::Ideal { .. }
+ | api_models::payments::BankRedirectData::Interac { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingFinland { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingPoland { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingSlovakia { .. }
+ | api_models::payments::BankRedirectData::Przelewy24 { .. }
+ | api_models::payments::BankRedirectData::Sofort { .. }
+ | api_models::payments::BankRedirectData::Trustly { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingFpx { .. }
+ | api_models::payments::BankRedirectData::OnlineBankingThailand { .. } => {
+ Err(errors::ConnectorError::NotSupported {
+ message: utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "Volt",
+ }
+ .into())
+ }
+ },
+ api_models::payments::PaymentMethodData::Card(_)
+ | api_models::payments::PaymentMethodData::CardRedirect(_)
+ | api_models::payments::PaymentMethodData::Wallet(_)
+ | api_models::payments::PaymentMethodData::PayLater(_)
+ | api_models::payments::PaymentMethodData::BankDebit(_)
+ | api_models::payments::PaymentMethodData::BankTransfer(_)
+ | api_models::payments::PaymentMethodData::Crypto(_)
+ | api_models::payments::PaymentMethodData::MandatePayment
+ | api_models::payments::PaymentMethodData::Reward
+ | api_models::payments::PaymentMethodData::Upi(_)
+ | api_models::payments::PaymentMethodData::Voucher(_)
+ | api_models::payments::PaymentMethodData::GiftCard(_) => {
+ Err(errors::ConnectorError::NotSupported {
+ message: utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "Volt",
+ }
+ .into())
}
- _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
}
}
}
+#[derive(Debug, Clone, Serialize, PartialEq)]
+pub struct VoltAuthUpdateRequest {
+ grant_type: String,
+ client_id: Secret<String>,
+ client_secret: Secret<String>,
+ username: Secret<String>,
+ password: Secret<String>,
+}
+
+impl TryFrom<&types::RefreshTokenRouterData> for VoltAuthUpdateRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> {
+ let auth = VoltAuthType::try_from(&item.connector_auth_type)?;
+ Ok(Self {
+ grant_type: PASSWORD.to_string(),
+ username: auth.username,
+ password: auth.password,
+ client_id: auth.client_id,
+ client_secret: auth.client_secret,
+ })
+ }
+}
+
+#[derive(Debug, Clone, Deserialize)]
+pub struct VoltAuthUpdateResponse {
+ pub access_token: Secret<String>,
+ pub token_type: String,
+ pub expires_in: i64,
+ pub refresh_token: String,
+}
+
+impl<F, T> TryFrom<types::ResponseRouterData<F, VoltAuthUpdateResponse, T, types::AccessToken>>
+ for types::RouterData<F, T, types::AccessToken>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, VoltAuthUpdateResponse, T, types::AccessToken>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::AccessToken {
+ token: item.response.access_token,
+ expires: item.response.expires_in,
+ }),
+ ..item.data
+ })
+ }
+}
+
pub struct VoltAuthType {
- pub(super) api_key: Secret<String>,
+ pub(super) username: Secret<String>,
+ pub(super) password: Secret<String>,
+ pub(super) client_id: Secret<String>,
+ pub(super) client_secret: Secret<String>,
}
impl TryFrom<&types::ConnectorAuthType> for VoltAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
- api_key: api_key.to_owned(),
+ types::ConnectorAuthType::MultiAuthKey {
+ api_key,
+ key1,
+ api_secret,
+ key2,
+ } => Ok(Self {
+ username: api_key.to_owned(),
+ password: api_secret.to_owned(),
+ client_id: key1.to_owned(),
+ client_secret: key2.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
-#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
-#[serde(rename_all = "lowercase")]
-pub enum VoltPaymentStatus {
- Succeeded,
- Failed,
- #[default]
- Processing,
-}
-
impl From<VoltPaymentStatus> for enums::AttemptStatus {
fn from(item: VoltPaymentStatus) -> Self {
match item {
- VoltPaymentStatus::Succeeded => Self::Charged,
- VoltPaymentStatus::Failed => Self::Failure,
- VoltPaymentStatus::Processing => Self::Authorizing,
+ VoltPaymentStatus::Completed
+ | VoltPaymentStatus::Received
+ | VoltPaymentStatus::Settled => Self::Charged,
+ VoltPaymentStatus::DelayedAtBank => Self::Pending,
+ VoltPaymentStatus::NewPayment
+ | VoltPaymentStatus::BankRedirect
+ | VoltPaymentStatus::AwaitingCheckoutAuthorisation => Self::AuthenticationPending,
+ VoltPaymentStatus::RefusedByBank
+ | VoltPaymentStatus::RefusedByRisk
+ | VoltPaymentStatus::NotReceived
+ | VoltPaymentStatus::ErrorAtBank
+ | VoltPaymentStatus::CancelledByUser
+ | VoltPaymentStatus::AbandonedByUser
+ | VoltPaymentStatus::Failed => Self::Failure,
}
}
}
-#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
pub struct VoltPaymentsResponse {
- status: VoltPaymentStatus,
+ checkout_url: String,
id: String,
}
@@ -126,16 +269,73 @@ impl<F, T>
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: types::ResponseRouterData<F, VoltPaymentsResponse, T, types::PaymentsResponseData>,
+ ) -> Result<Self, Self::Error> {
+ let url = item.response.checkout_url;
+ let redirection_data = Some(services::RedirectForm::Form {
+ endpoint: url,
+ method: services::Method::Get,
+ form_fields: Default::default(),
+ });
+ Ok(Self {
+ status: enums::AttemptStatus::AuthenticationPending,
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
+ redirection_data,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ connector_response_reference_id: Some(item.response.id),
+ }),
+ ..item.data
+ })
+ }
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
+pub enum VoltPaymentStatus {
+ NewPayment,
+ Completed,
+ Received,
+ NotReceived,
+ BankRedirect,
+ DelayedAtBank,
+ AwaitingCheckoutAuthorisation,
+ RefusedByBank,
+ RefusedByRisk,
+ ErrorAtBank,
+ CancelledByUser,
+ AbandonedByUser,
+ Failed,
+ Settled,
+}
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct VoltPsyncResponse {
+ status: VoltPaymentStatus,
+ id: String,
+ merchant_internal_reference: Option<String>,
+}
+
+impl<F, T> TryFrom<types::ResponseRouterData<F, VoltPsyncResponse, T, types::PaymentsResponseData>>
+ for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<F, VoltPsyncResponse, T, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: None,
mandate_reference: None,
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: item
+ .response
+ .merchant_internal_reference
+ .or(Some(item.response.id)),
}),
..item.data
})
@@ -147,13 +347,15 @@ impl<F, T>
#[derive(Default, Debug, Serialize)]
pub struct VoltRefundRequest {
pub amount: i64,
+ pub external_reference: String,
}
impl<F> TryFrom<&VoltRouterData<&types::RefundsRouterData<F>>> for VoltRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &VoltRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
- amount: item.amount.to_owned(),
+ amount: item.router_data.request.refund_amount,
+ external_reference: item.router_data.request.refund_id.clone(),
})
}
}
@@ -180,10 +382,9 @@ impl From<RefundStatus> for enums::RefundStatus {
}
}
-#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+#[derive(Default, Debug, Clone, Deserialize)]
pub struct RefundResponse {
id: String,
- status: RefundStatus,
}
impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
@@ -196,34 +397,28 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
Ok(Self {
response: Ok(types::RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
+ refund_status: enums::RefundStatus::Pending, //We get Refund Status only by Webhooks
}),
..item.data
})
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
- type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
- ) -> Result<Self, Self::Error> {
- Ok(Self {
- response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
- refund_status: enums::RefundStatus::from(item.response.status),
- }),
- ..item.data
- })
- }
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct VoltErrorResponse {
+ pub exception: VoltErrorException,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
-pub struct VoltErrorResponse {
- pub status_code: u16,
- pub code: String,
+#[serde(rename_all = "camelCase")]
+pub struct VoltErrorException {
+ pub code: u64,
+ pub message: String,
+ pub error_list: Option<Vec<VoltErrorList>>,
+}
+
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct VoltErrorList {
+ pub property: String,
pub message: String,
- pub reason: Option<String>,
}
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index c0d6c576dd5..11cdc49dd64 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1502,6 +1502,10 @@ pub(crate) fn validate_auth_and_metadata_type(
tsys::transformers::TsysAuthType::try_from(val)?;
Ok(())
}
+ api_enums::Connector::Volt => {
+ volt::transformers::VoltAuthType::try_from(val)?;
+ Ok(())
+ }
api_enums::Connector::Wise => {
wise::transformers::WiseAuthType::try_from(val)?;
Ok(())
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 9f1dbad1428..261195d166c 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -958,6 +958,11 @@ impl TryFrom<ConnectorAuthType> for AccessTokenRequestData {
app_id: api_key,
id: Some(key1),
}),
+ ConnectorAuthType::MultiAuthKey { api_key, key1, .. } => Ok(Self {
+ app_id: api_key,
+ id: Some(key1),
+ }),
+
_ => Err(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector_account_details",
}),
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 00e40cc908b..8f5a0f8a59f 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -362,7 +362,7 @@ impl ConnectorData {
enums::Connector::Paypal => Ok(Box::new(&connector::Paypal)),
enums::Connector::Trustpay => Ok(Box::new(&connector::Trustpay)),
enums::Connector::Tsys => Ok(Box::new(&connector::Tsys)),
- // enums::Connector::Volt => Ok(Box::new(&connector::Volt)), it is added as template code for future usage
+ enums::Connector::Volt => Ok(Box::new(&connector::Volt)),
enums::Connector::Zen => Ok(Box::new(&connector::Zen)),
enums::Connector::Signifyd | enums::Connector::Plaid => {
Err(report!(errors::ConnectorError::InvalidConnectorName)
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 8b5988dcb47..45d0bde9d32 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -3935,6 +3935,7 @@
"stripe",
"trustpay",
"tsys",
+ "volt",
"wise",
"worldline",
"worldpay",
diff --git a/postman/collection-dir/volt/.auth.json b/postman/collection-dir/volt/.auth.json
new file mode 100644
index 00000000000..915a2835790
--- /dev/null
+++ b/postman/collection-dir/volt/.auth.json
@@ -0,0 +1,22 @@
+{
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ }
+}
diff --git a/postman/collection-dir/volt/.event.meta.json b/postman/collection-dir/volt/.event.meta.json
new file mode 100644
index 00000000000..2df9d47d936
--- /dev/null
+++ b/postman/collection-dir/volt/.event.meta.json
@@ -0,0 +1,6 @@
+{
+ "eventOrder": [
+ "event.prerequest.js",
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/.info.json b/postman/collection-dir/volt/.info.json
new file mode 100644
index 00000000000..802b98a9e8f
--- /dev/null
+++ b/postman/collection-dir/volt/.info.json
@@ -0,0 +1,9 @@
+{
+ "info": {
+ "_postman_id": "ac5a089e-b4a3-43b2-8938-b2e44056e455",
+ "name": "volt",
+ "description": "## Get started\n\nJuspay Router provides a collection of APIs that enable you to process and manage payments. Our APIs accept and return JSON in the HTTP body, and return standard HTTP response codes. \nYou can consume the APIs directly using your favorite HTTP/REST library. \nWe have a testing environment referred to \"sandbox\", which you can setup to test API calls without affecting production data.\n\n### Base URLs\n\nUse the following base URLs when making requests to the APIs:\n\n| Environment | Base URL |\n| --- | --- |\n| Sandbox | [https://sandbox.hyperswitch.io](https://sandbox.hyperswitch.io) |\n| Production | [https://router.juspay.io](https://router.juspay.io) |\n\n# Authentication\n\nWhen you sign up for an account, you are given a secret key (also referred as api-key). You may authenticate all API requests with Juspay server by providing the appropriate key in the request Authorization header. \nNever share your secret api keys. Keep them guarded and secure.\n\nContact Support: \nName: Juspay Support \nEmail: [[email protected]](mailto:[email protected])",
+ "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json",
+ "_exporter_id": "27008363"
+ }
+}
diff --git a/postman/collection-dir/volt/.meta.json b/postman/collection-dir/volt/.meta.json
new file mode 100644
index 00000000000..91b6a65c5bc
--- /dev/null
+++ b/postman/collection-dir/volt/.meta.json
@@ -0,0 +1,6 @@
+{
+ "childrenOrder": [
+ "Health check",
+ "Flow Testcases"
+ ]
+}
diff --git a/postman/collection-dir/volt/.variable.json b/postman/collection-dir/volt/.variable.json
new file mode 100644
index 00000000000..755dab38d54
--- /dev/null
+++ b/postman/collection-dir/volt/.variable.json
@@ -0,0 +1,101 @@
+{
+ "variable": [
+ {
+ "key": "baseUrl",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "admin_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "merchant_id",
+ "value": ""
+ },
+ {
+ "key": "payment_id",
+ "value": ""
+ },
+ {
+ "key": "customer_id",
+ "value": ""
+ },
+ {
+ "key": "mandate_id",
+ "value": ""
+ },
+ {
+ "key": "payment_method_id",
+ "value": ""
+ },
+ {
+ "key": "refund_id",
+ "value": ""
+ },
+ {
+ "key": "merchant_connector_id",
+ "value": ""
+ },
+ {
+ "key": "client_secret",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_api_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_api_secret",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_key1",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "connector_key2",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "publishable_key",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "api_key_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "payment_token",
+ "value": ""
+ },
+ {
+ "key": "gateway_merchant_id",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate",
+ "value": "",
+ "type": "string"
+ },
+ {
+ "key": "certificate_keys",
+ "value": "",
+ "type": "string"
+ }
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/.meta.json b/postman/collection-dir/volt/Flow Testcases/.meta.json
new file mode 100644
index 00000000000..bd972090b19
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/.meta.json
@@ -0,0 +1,6 @@
+{
+ "childrenOrder": [
+ "QuickStart",
+ "Happy Cases"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/.meta.json
new file mode 100644
index 00000000000..2429b1c3988
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/.meta.json
@@ -0,0 +1,8 @@
+{
+ "childrenOrder": [
+ "Scenario1-Create payment with confirm true",
+ "Scenario2-Create payment with confirm false",
+ "Scenario3-Create payment without PMD",
+ "Scenario4-Bank Redirect-open_banking_uk"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/.meta.json
new file mode 100644
index 00000000000..60051ecca22
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/.meta.json
@@ -0,0 +1,6 @@
+{
+ "childrenOrder": [
+ "Payments - Create",
+ "Payments - Retrieve"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js
new file mode 100644
index 00000000000..3fd8b3c7cbe
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/event.test.js
@@ -0,0 +1,80 @@
+// Validate status 2xx
+pm.test("[POST]::/payments - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/payments - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[POST]::/payments - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+
+// Response body should have value "requires_customer_action" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments - Content check if value for 'status' matches 'requires_customer_action'",
+ function () {
+ pm.expect(jsonData.status).to.eql("requires_customer_action");
+ },
+ );
+}
+
+// Response body should have "connector_transaction_id"
+pm.test(
+ "[POST]::/payments - Content check if 'connector_transaction_id' exists",
+ function () {
+ pm.expect(typeof jsonData.connector_transaction_id !== "undefined").to.be
+ .true;
+ },
+);
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json
new file mode 100644
index 00000000000..6bfc6850096
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/request.json
@@ -0,0 +1,102 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "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": "open_banking_uk",
+ "payment_method_data": {
+ "bank_redirect": {
+ "open_banking_uk": {
+ "issuer": "citi",
+ "country": "GB"
+ }
+ }
+ },
+ "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"
+ },
+ "routing": {
+ "type": "single",
+ "data": "volt"
+ }
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/response.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Create/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Retrieve/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Retrieve/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Retrieve/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Retrieve/event.test.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Retrieve/event.test.js
new file mode 100644
index 00000000000..d1f1dc048ae
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Retrieve/event.test.js
@@ -0,0 +1,80 @@
+// Validate status 2xx
+pm.test("[GET]::/payments/:id - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[GET]::/payments/:id - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[GET]::/payments/:id - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+
+// Response body should have value "requires_customer_action" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments/:id - Content check if value for 'status' matches 'requires_customer_action'",
+ function () {
+ pm.expect(jsonData.status).to.eql("requires_customer_action");
+ },
+ );
+}
+
+// Response body should have "connector_transaction_id"
+pm.test(
+ "[POST]::/payments - Content check if 'connector_transaction_id' exists",
+ function () {
+ pm.expect(typeof jsonData.connector_transaction_id !== "undefined").to.be
+ .true;
+ },
+);
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Retrieve/request.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Retrieve/request.json
new file mode 100644
index 00000000000..b9ebc1be4aa
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Retrieve/request.json
@@ -0,0 +1,33 @@
+{
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Retrieve/response.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Retrieve/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario1-Create payment with confirm true/Payments - Retrieve/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/.meta.json
new file mode 100644
index 00000000000..57d3f8e2bc7
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/.meta.json
@@ -0,0 +1,7 @@
+{
+ "childrenOrder": [
+ "Payments - Create",
+ "Payments - Confirm",
+ "Payments - Retrieve"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/.event.meta.json
new file mode 100644
index 00000000000..4ac527d834a
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/.event.meta.json
@@ -0,0 +1,6 @@
+{
+ "eventOrder": [
+ "event.test.js",
+ "event.prerequest.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/event.prerequest.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/event.prerequest.js
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/event.test.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/event.test.js
new file mode 100644
index 00000000000..6a2040fb5b8
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/event.test.js
@@ -0,0 +1,103 @@
+// Validate status 2xx
+pm.test("[POST]::/payments/:id/confirm - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test(
+ "[POST]::/payments/:id/confirm - Content-Type is application/json",
+ function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+ },
+);
+
+// Validate if response has JSON Body
+pm.test("[POST]::/payments/:id/confirm - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+
+// Response body should have value "6540" for "amount"
+if (jsonData?.amount) {
+ pm.test(
+ "[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'",
+ function () {
+ pm.expect(jsonData.amount).to.eql(6540);
+ },
+ );
+}
+
+// Response body should have value "6540" for "amount_capturable"
+if (jsonData?.amount) {
+ pm.test(
+ "[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 6540'",
+ function () {
+ pm.expect(jsonData.amount_capturable).to.eql(6540);
+ },
+ );
+}
+
+// Response body should have value "requires_customer_action" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'",
+ function () {
+ pm.expect(jsonData.status).to.eql("requires_customer_action");
+ },
+ );
+}
+
+// Response body should have "connector_transaction_id"
+pm.test(
+ "[POST]::/payments - Content check if 'connector_transaction_id' exists",
+ function () {
+ pm.expect(typeof jsonData.connector_transaction_id !== "undefined").to.be
+ .true;
+ },
+);
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json
new file mode 100644
index 00000000000..16f6e13983f
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/request.json
@@ -0,0 +1,63 @@
+{
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "client_secret": "{{client_secret}}"
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/response.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Confirm/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/event.test.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/event.test.js
new file mode 100644
index 00000000000..55dc35b9128
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/event.test.js
@@ -0,0 +1,71 @@
+// Validate status 2xx
+pm.test("[POST]::/payments - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/payments - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[POST]::/payments - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+
+// Response body should have value "requires_confirmation" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments - Content check if value for 'status' matches 'requires_confirmation'",
+ function () {
+ pm.expect(jsonData.status).to.eql("requires_confirmation");
+ },
+ );
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json
new file mode 100644
index 00000000000..a4192d96b4a
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/request.json
@@ -0,0 +1,102 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "amount": 6540,
+ "currency": "EUR",
+ "confirm": false,
+ "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": "open_banking_uk",
+ "payment_method_data": {
+ "bank_redirect": {
+ "open_banking_uk": {
+ "issuer": "citi",
+ "country": "GB"
+ }
+ }
+ },
+ "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"
+ },
+ "routing": {
+ "type": "single",
+ "data": "volt"
+ }
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/response.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Create/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Retrieve/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Retrieve/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Retrieve/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Retrieve/event.test.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Retrieve/event.test.js
new file mode 100644
index 00000000000..0463f0e86c0
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Retrieve/event.test.js
@@ -0,0 +1,91 @@
+// Validate status 2xx
+pm.test("[GET]::/payments/:id - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[GET]::/payments/:id - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[GET]::/payments/:id - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+
+// Response body should have value "requires_customer_action" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'",
+ function () {
+ pm.expect(jsonData.status).to.eql("requires_customer_action");
+ },
+ );
+}
+
+// Response body should have value "6540" for "amount"
+if (jsonData?.amount) {
+ pm.test(
+ "[post]:://payments/:id/capture - Content check if value for 'amount' matches '6540'",
+ function () {
+ pm.expect(jsonData.amount).to.eql(6540);
+ },
+ );
+}
+
+// Response body should have value "6540" for "amount_capturable"
+if (jsonData?.amount) {
+ pm.test(
+ "[post]:://payments/:id/capture - Content check if value for 'amount_capturable' matches 'amount - 6540'",
+ function () {
+ pm.expect(jsonData.amount_capturable).to.eql(6540);
+ },
+ );
+}
\ No newline at end of file
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Retrieve/request.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Retrieve/request.json
new file mode 100644
index 00000000000..b9ebc1be4aa
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Retrieve/request.json
@@ -0,0 +1,33 @@
+{
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Retrieve/response.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Retrieve/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario2-Create payment with confirm false/Payments - Retrieve/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/.meta.json
new file mode 100644
index 00000000000..57d3f8e2bc7
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/.meta.json
@@ -0,0 +1,7 @@
+{
+ "childrenOrder": [
+ "Payments - Create",
+ "Payments - Confirm",
+ "Payments - Retrieve"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/.event.meta.json
new file mode 100644
index 00000000000..4ac527d834a
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/.event.meta.json
@@ -0,0 +1,6 @@
+{
+ "eventOrder": [
+ "event.test.js",
+ "event.prerequest.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/event.prerequest.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/event.prerequest.js
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/event.test.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/event.test.js
new file mode 100644
index 00000000000..8bbfce6d5b5
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/event.test.js
@@ -0,0 +1,73 @@
+// Validate status 2xx
+pm.test("[POST]::/payments/:id/confirm - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test(
+ "[POST]::/payments/:id/confirm - Content-Type is application/json",
+ function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+ },
+);
+
+// Validate if response has JSON Body
+pm.test("[POST]::/payments/:id/confirm - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+// Response body should have value "requires_customer_action" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments:id/confirm - Content check if value for 'status' matches 'requires_customer_action'",
+ function () {
+ pm.expect(jsonData.status).to.eql("requires_customer_action");
+ },
+ );
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/request.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/request.json
new file mode 100644
index 00000000000..f0f67b12fb4
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/request.json
@@ -0,0 +1,73 @@
+{
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "payment_method": "bank_redirect",
+ "payment_method_type": "open_banking_uk",
+ "payment_method_data": {
+ "bank_redirect": {
+ "open_banking_uk": {
+ "issuer": "citi",
+ "country": "GB"
+ }
+ }
+ },
+ "client_secret": "{{client_secret}}"
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/response.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Confirm/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/event.test.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/event.test.js
new file mode 100644
index 00000000000..0444324000a
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/event.test.js
@@ -0,0 +1,71 @@
+// Validate status 2xx
+pm.test("[POST]::/payments - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/payments - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[POST]::/payments - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+
+// Response body should have value "requires_payment_method" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'",
+ function () {
+ pm.expect(jsonData.status).to.eql("requires_payment_method");
+ },
+ );
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json
new file mode 100644
index 00000000000..7323f440e64
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/request.json
@@ -0,0 +1,83 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "amount": 6540,
+ "currency": "EUR",
+ "confirm": false,
+ "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",
+ "billing": {
+ "address": {
+ "line1": "1467",
+ "line2": "Harrison Street",
+ "line3": "Harrison Street",
+ "city": "San Fransico",
+ "state": "California",
+ "zip": "94122",
+ "country": "US",
+ "first_name": "sundari",
+ "last_name": "singh"
+ }
+ },
+ "shipping": {
+ "address": {
+ "line1": "1467",
+ "line2": "Harrison Street",
+ "line3": "Harrison Street",
+ "city": "San Fransico",
+ "state": "California",
+ "zip": "94122",
+ "country": "US",
+ "first_name": "sundari"
+ }
+ },
+ "statement_descriptor_name": "joseph",
+ "statement_descriptor_suffix": "JS",
+ "metadata": {
+ "udf1": "value1",
+ "new_customer": "true",
+ "login_date": "2019-09-10T10:11:12Z"
+ },
+ "routing": {
+ "type": "single",
+ "data": "volt"
+ }
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/response.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Create/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Retrieve/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Retrieve/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Retrieve/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Retrieve/event.test.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Retrieve/event.test.js
new file mode 100644
index 00000000000..9053ddab13b
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Retrieve/event.test.js
@@ -0,0 +1,71 @@
+// Validate status 2xx
+pm.test("[GET]::/payments/:id - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[GET]::/payments/:id - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[GET]::/payments/:id - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+
+// Response body should have value "requires_customer_action" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'",
+ function () {
+ pm.expect(jsonData.status).to.eql("requires_customer_action");
+ },
+ );
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Retrieve/request.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Retrieve/request.json
new file mode 100644
index 00000000000..b9ebc1be4aa
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Retrieve/request.json
@@ -0,0 +1,33 @@
+{
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Retrieve/response.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Retrieve/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario3-Create payment without PMD/Payments - Retrieve/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/.meta.json
new file mode 100644
index 00000000000..57d3f8e2bc7
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/.meta.json
@@ -0,0 +1,7 @@
+{
+ "childrenOrder": [
+ "Payments - Create",
+ "Payments - Confirm",
+ "Payments - Retrieve"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/.event.meta.json
new file mode 100644
index 00000000000..4ac527d834a
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/.event.meta.json
@@ -0,0 +1,6 @@
+{
+ "eventOrder": [
+ "event.test.js",
+ "event.prerequest.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/event.prerequest.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/event.prerequest.js
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/event.test.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/event.test.js
new file mode 100644
index 00000000000..9624b67240a
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/event.test.js
@@ -0,0 +1,103 @@
+// Validate status 2xx
+pm.test("[POST]::/payments/:id/confirm - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test(
+ "[POST]::/payments/:id/confirm - Content-Type is application/json",
+ function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+ },
+);
+
+// Validate if response has JSON Body
+pm.test("[POST]::/payments/:id/confirm - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+
+// Response body should have value "requires_customer_action" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments/:id/confirm - Content check if value for 'status' matches 'requires_customer_action'",
+ function () {
+ pm.expect(jsonData.status).to.eql("requires_customer_action");
+ },
+ );
+}
+
+// Response body should have "next_action.redirect_to_url"
+pm.test(
+ "[POST]::/payments - Content check if 'next_action.redirect_to_url' exists",
+ function () {
+ pm.expect(typeof jsonData.next_action.redirect_to_url !== "undefined").to.be
+ .true;
+ },
+);
+
+// Response body should have value "open_banking_uk" for "payment_method_type"
+if (jsonData?.payment_method_type) {
+ pm.test(
+ "[POST]::/payments/:id/confirm - Content check if value for 'payment_method_type' matches 'open_banking_uk'",
+ function () {
+ pm.expect(jsonData.payment_method_type).to.eql("open_banking_uk");
+ },
+ );
+}
+
+// Response body should have value "volt" for "connector"
+if (jsonData?.connector) {
+ pm.test(
+ "[POST]::/payments/:id/confirm - Content check if value for 'connector' matches 'volt'",
+ function () {
+ pm.expect(jsonData.connector).to.eql("volt");
+ },
+ );
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/request.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/request.json
new file mode 100644
index 00000000000..f0f67b12fb4
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/request.json
@@ -0,0 +1,73 @@
+{
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{publishable_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "payment_method": "bank_redirect",
+ "payment_method_type": "open_banking_uk",
+ "payment_method_data": {
+ "bank_redirect": {
+ "open_banking_uk": {
+ "issuer": "citi",
+ "country": "GB"
+ }
+ }
+ },
+ "client_secret": "{{client_secret}}"
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id/confirm",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id",
+ "confirm"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "This API is to confirm the payment request and forward payment to the payment processor. This API provides more granular control upon when the API is forwarded to the payment processor. Alternatively you can confirm the payment within the Payments-Create API"
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/response.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Confirm/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Create/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Create/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Create/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Create/event.test.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Create/event.test.js
new file mode 100644
index 00000000000..0444324000a
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Create/event.test.js
@@ -0,0 +1,71 @@
+// Validate status 2xx
+pm.test("[POST]::/payments - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/payments - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[POST]::/payments - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+
+// Response body should have value "requires_payment_method" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments - Content check if value for 'status' matches 'requires_payment_method'",
+ function () {
+ pm.expect(jsonData.status).to.eql("requires_payment_method");
+ },
+ );
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Create/request.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Create/request.json
new file mode 100644
index 00000000000..7323f440e64
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Create/request.json
@@ -0,0 +1,83 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "amount": 6540,
+ "currency": "EUR",
+ "confirm": false,
+ "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",
+ "billing": {
+ "address": {
+ "line1": "1467",
+ "line2": "Harrison Street",
+ "line3": "Harrison Street",
+ "city": "San Fransico",
+ "state": "California",
+ "zip": "94122",
+ "country": "US",
+ "first_name": "sundari",
+ "last_name": "singh"
+ }
+ },
+ "shipping": {
+ "address": {
+ "line1": "1467",
+ "line2": "Harrison Street",
+ "line3": "Harrison Street",
+ "city": "San Fransico",
+ "state": "California",
+ "zip": "94122",
+ "country": "US",
+ "first_name": "sundari"
+ }
+ },
+ "statement_descriptor_name": "joseph",
+ "statement_descriptor_suffix": "JS",
+ "metadata": {
+ "udf1": "value1",
+ "new_customer": "true",
+ "login_date": "2019-09-10T10:11:12Z"
+ },
+ "routing": {
+ "type": "single",
+ "data": "volt"
+ }
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Create/response.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Create/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Create/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Retrieve/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Retrieve/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Retrieve/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Retrieve/event.test.js b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Retrieve/event.test.js
new file mode 100644
index 00000000000..9053ddab13b
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Retrieve/event.test.js
@@ -0,0 +1,71 @@
+// Validate status 2xx
+pm.test("[GET]::/payments/:id - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[GET]::/payments/:id - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[GET]::/payments/:id - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+
+// Response body should have value "requires_customer_action" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments:id - Content check if value for 'status' matches 'requires_customer_action'",
+ function () {
+ pm.expect(jsonData.status).to.eql("requires_customer_action");
+ },
+ );
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Retrieve/request.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Retrieve/request.json
new file mode 100644
index 00000000000..b9ebc1be4aa
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Retrieve/request.json
@@ -0,0 +1,33 @@
+{
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Retrieve/response.json b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Retrieve/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/Happy Cases/Scenario4-Bank Redirect-open_banking_uk/Payments - Retrieve/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/.meta.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/.meta.json
new file mode 100644
index 00000000000..e3596ba357b
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/.meta.json
@@ -0,0 +1,9 @@
+{
+ "childrenOrder": [
+ "Merchant Account - Create",
+ "API Key - Create",
+ "Payment Connector - Create",
+ "Payments - Create",
+ "Payments - Retrieve"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/API Key - Create/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/API Key - Create/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/API Key - Create/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/API Key - Create/event.test.js b/postman/collection-dir/volt/Flow Testcases/QuickStart/API Key - Create/event.test.js
new file mode 100644
index 00000000000..4e27c5a5025
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/API Key - Create/event.test.js
@@ -0,0 +1,46 @@
+// Validate status 2xx
+pm.test("[POST]::/api_keys/:merchant_id - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test(
+ "[POST]::/api_keys/:merchant_id - Content-Type is application/json",
+ function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+ },
+);
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set api_key_id as variable for jsonData.key_id
+if (jsonData?.key_id) {
+ pm.collectionVariables.set("api_key_id", jsonData.key_id);
+ console.log(
+ "- use {{api_key_id}} as collection variable for value",
+ jsonData.key_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{api_key_id}}, as jsonData.key_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set api_key as variable for jsonData.api_key
+if (jsonData?.api_key) {
+ pm.collectionVariables.set("api_key", jsonData.api_key);
+ console.log(
+ "- use {{api_key}} as collection variable for value",
+ jsonData.api_key,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.",
+ );
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/API Key - Create/request.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/API Key - Create/request.json
new file mode 100644
index 00000000000..b89ff689685
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/API Key - Create/request.json
@@ -0,0 +1,52 @@
+{
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{admin_api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw_json_formatted": {
+ "name": "API Key 1",
+ "description": null,
+ "expiration": "2099-09-23T01:02:03.000Z"
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/api_keys/:merchant_id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "api_keys",
+ ":merchant_id"
+ ],
+ "variable": [
+ {
+ "key": "merchant_id",
+ "value": "{{merchant_id}}"
+ }
+ ]
+ }
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/API Key - Create/response.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/API Key - Create/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/API Key - Create/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Merchant Account - Create/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Merchant Account - Create/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Merchant Account - Create/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Merchant Account - Create/event.test.js b/postman/collection-dir/volt/Flow Testcases/QuickStart/Merchant Account - Create/event.test.js
new file mode 100644
index 00000000000..7de0d5beb31
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Merchant Account - Create/event.test.js
@@ -0,0 +1,56 @@
+// Validate status 2xx
+pm.test("[POST]::/accounts - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/accounts - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set merchant_id as variable for jsonData.merchant_id
+if (jsonData?.merchant_id) {
+ pm.collectionVariables.set("merchant_id", jsonData.merchant_id);
+ console.log(
+ "- use {{merchant_id}} as collection variable for value",
+ jsonData.merchant_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{merchant_id}}, as jsonData.merchant_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set api_key as variable for jsonData.api_key
+if (jsonData?.api_key) {
+ pm.collectionVariables.set("api_key", jsonData.api_key);
+ console.log(
+ "- use {{api_key}} as collection variable for value",
+ jsonData.api_key,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{api_key}}, as jsonData.api_key is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set publishable_key as variable for jsonData.publishable_key
+if (jsonData?.publishable_key) {
+ pm.collectionVariables.set("publishable_key", jsonData.publishable_key);
+ console.log(
+ "- use {{publishable_key}} as collection variable for value",
+ jsonData.publishable_key,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{publishable_key}}, as jsonData.publishable_key is undefined.",
+ );
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Merchant Account - Create/request.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Merchant Account - Create/request.json
new file mode 100644
index 00000000000..9f0ff5575c0
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Merchant Account - Create/request.json
@@ -0,0 +1,95 @@
+{
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{admin_api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "merchant_id": "postman_merchant_GHAction_{{$guid}}",
+ "locker_id": "m0010",
+ "merchant_name": "NewAge Retailer",
+ "merchant_details": {
+ "primary_contact_person": "John Test",
+ "primary_email": "[email protected]",
+ "primary_phone": "sunt laborum",
+ "secondary_contact_person": "John Test2",
+ "secondary_email": "[email protected]",
+ "secondary_phone": "cillum do dolor id",
+ "website": "www.example.com",
+ "about_business": "Online Retail with a wide selection of organic products for North America",
+ "address": {
+ "line1": "1467",
+ "line2": "Harrison Street",
+ "line3": "Harrison Street",
+ "city": "San Fransico",
+ "state": "California",
+ "zip": "94122",
+ "country": "US"
+ }
+ },
+ "return_url": "https://duck.com",
+ "webhook_details": {
+ "webhook_version": "1.0.1",
+ "webhook_username": "ekart_retail",
+ "webhook_password": "password_ekart@123",
+ "payment_created_enabled": true,
+ "payment_succeeded_enabled": true,
+ "payment_failed_enabled": true
+ },
+ "sub_merchants_enabled": false,
+ "metadata": {
+ "city": "NY",
+ "unit": "245"
+ },
+ "primary_business_details": [
+ {
+ "country": "US",
+ "business": "default"
+ }
+ ]
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/accounts",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "accounts"
+ ]
+ },
+ "description": "Create a new account for a merchant. The merchant could be a seller or retailer or client who likes to receive and send payments."
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Merchant Account - Create/response.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Merchant Account - Create/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Merchant Account - Create/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/event.test.js b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/event.test.js
new file mode 100644
index 00000000000..88e92d8d84a
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/event.test.js
@@ -0,0 +1,39 @@
+// Validate status 2xx
+pm.test(
+ "[POST]::/account/:account_id/connectors - Status code is 2xx",
+ function () {
+ pm.response.to.be.success;
+ },
+);
+
+// Validate if response header has matching content-type
+pm.test(
+ "[POST]::/account/:account_id/connectors - Content-Type is application/json",
+ function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+ },
+);
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id
+if (jsonData?.merchant_connector_id) {
+ pm.collectionVariables.set(
+ "merchant_connector_id",
+ jsonData.merchant_connector_id,
+ );
+ console.log(
+ "- use {{merchant_connector_id}} as collection variable for value",
+ jsonData.merchant_connector_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.",
+ );
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/request.json
new file mode 100644
index 00000000000..4c086eea1a6
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/request.json
@@ -0,0 +1,93 @@
+{
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{admin_api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "connector_type": "fiz_operations",
+ "connector_name": "volt",
+ "business_country": "US",
+ "business_label": "default",
+ "connector_account_details": {
+ "auth_type": "MultiAuthKey",
+ "api_key": "{{connector_api_key}}",
+ "api_secret": "{{connector_api_secret}}",
+ "key1": "{{connector_key1}}",
+ "key2": "{{connector_key2}}"
+ },
+ "test_mode": false,
+ "disabled": false,
+ "payment_methods_enabled": [
+ {
+ "payment_method": "bank_redirect",
+ "payment_method_types": [
+ {
+ "payment_method_type": "open_banking_uk",
+ "payment_experience": null,
+ "card_networks": null,
+ "accepted_currencies": null,
+ "accepted_countries": null,
+ "minimum_amount": 1,
+ "maximum_amount": 68607706,
+ "recurring_enabled": true,
+ "installment_payment_enabled": true
+ }
+ ]
+ }
+ ]
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/account/:account_id/connectors",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "account",
+ ":account_id",
+ "connectors"
+ ],
+ "variable": [
+ {
+ "key": "account_id",
+ "value": "{{merchant_id}}",
+ "description": "(Required) The unique identifier for the merchant account"
+ }
+ ]
+ },
+ "description": "Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialised services like Fraud / Accounting etc."
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/response.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payment Connector - Create/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Create/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Create/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Create/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Create/event.test.js b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Create/event.test.js
new file mode 100644
index 00000000000..a6947db94c0
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Create/event.test.js
@@ -0,0 +1,61 @@
+// Validate status 2xx
+pm.test("[POST]::/payments - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/payments - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[POST]::/payments - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Create/request.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Create/request.json
new file mode 100644
index 00000000000..6bfc6850096
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Create/request.json
@@ -0,0 +1,102 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "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": "open_banking_uk",
+ "payment_method_data": {
+ "bank_redirect": {
+ "open_banking_uk": {
+ "issuer": "citi",
+ "country": "GB"
+ }
+ }
+ },
+ "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"
+ },
+ "routing": {
+ "type": "single",
+ "data": "volt"
+ }
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments"
+ ]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Create/response.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Create/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Create/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Retrieve/.event.meta.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Retrieve/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Retrieve/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Retrieve/event.test.js b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Retrieve/event.test.js
new file mode 100644
index 00000000000..d0a02af7436
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Retrieve/event.test.js
@@ -0,0 +1,61 @@
+// Validate status 2xx
+pm.test("[GET]::/payments/:id - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[GET]::/payments/:id - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// Validate if response has JSON Body
+pm.test("[GET]::/payments/:id - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Retrieve/request.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Retrieve/request.json
new file mode 100644
index 00000000000..c71774083b2
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Retrieve/request.json
@@ -0,0 +1,27 @@
+{
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "payments",
+ ":id"
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+}
diff --git a/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Retrieve/response.json b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Retrieve/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Flow Testcases/QuickStart/Payments - Retrieve/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/Health check/.meta.json b/postman/collection-dir/volt/Health check/.meta.json
new file mode 100644
index 00000000000..66ee7e50cab
--- /dev/null
+++ b/postman/collection-dir/volt/Health check/.meta.json
@@ -0,0 +1,5 @@
+{
+ "childrenOrder": [
+ "New Request"
+ ]
+}
diff --git a/postman/collection-dir/volt/Health check/New Request/.event.meta.json b/postman/collection-dir/volt/Health check/New Request/.event.meta.json
new file mode 100644
index 00000000000..688c85746ef
--- /dev/null
+++ b/postman/collection-dir/volt/Health check/New Request/.event.meta.json
@@ -0,0 +1,5 @@
+{
+ "eventOrder": [
+ "event.test.js"
+ ]
+}
diff --git a/postman/collection-dir/volt/Health check/New Request/event.test.js b/postman/collection-dir/volt/Health check/New Request/event.test.js
new file mode 100644
index 00000000000..b490b8be090
--- /dev/null
+++ b/postman/collection-dir/volt/Health check/New Request/event.test.js
@@ -0,0 +1,4 @@
+// Validate status 2xx
+pm.test("[POST]::/accounts - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
diff --git a/postman/collection-dir/volt/Health check/New Request/request.json b/postman/collection-dir/volt/Health check/New Request/request.json
new file mode 100644
index 00000000000..4cc8d4b1a96
--- /dev/null
+++ b/postman/collection-dir/volt/Health check/New Request/request.json
@@ -0,0 +1,20 @@
+{
+ "method": "GET",
+ "header": [
+ {
+ "key": "x-feature",
+ "value": "router-custom",
+ "type": "text",
+ "disabled": true
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/health",
+ "host": [
+ "{{baseUrl}}"
+ ],
+ "path": [
+ "health"
+ ]
+ }
+}
diff --git a/postman/collection-dir/volt/Health check/New Request/response.json b/postman/collection-dir/volt/Health check/New Request/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/volt/Health check/New Request/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/volt/event.prerequest.js b/postman/collection-dir/volt/event.prerequest.js
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/postman/collection-dir/volt/event.test.js b/postman/collection-dir/volt/event.test.js
new file mode 100644
index 00000000000..fb52caec30f
--- /dev/null
+++ b/postman/collection-dir/volt/event.test.js
@@ -0,0 +1,13 @@
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log("[LOG]::payment_id - " + jsonData.payment_id);
+}
+
+console.log("[LOG]::x-request-id - " + pm.response.headers.get("x-request-id"));
|
feat
|
[VOLT] Implement payment flows and bank redirect payment method (#2582)
|
bc92e0cccbbc989f3b32ad16cae58a3e47babe8b
|
2024-07-23 05:47:48
|
github-actions
|
chore(version): 2024.07.23.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index b6f22e99431..2e8e5199a99 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,33 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.07.23.0
+
+### Features
+
+- **connector:** [Itau Bank] Add payment and sync flow for Pix ([#5342](https://github.com/juspay/hyperswitch/pull/5342)) ([`3fef96e`](https://github.com/juspay/hyperswitch/commit/3fef96e727ebb411d5699b8b37bdec30a2606da0))
+
+### Bug Fixes
+
+- **router:** Store `network_transaction_id` in stripe `authorize` flow ([#5399](https://github.com/juspay/hyperswitch/pull/5399)) ([`be78dfc`](https://github.com/juspay/hyperswitch/commit/be78dfc04eff671fb0b4e6037c84aee8ab367e70))
+- Add offset and limit to key transfer API ([#5358](https://github.com/juspay/hyperswitch/pull/5358)) ([`b393803`](https://github.com/juspay/hyperswitch/commit/b393803a6199a12f86d7bbdc998e5a0d8366c000))
+
+### Refactors
+
+- **connector:** Add billing_country in klarna dynamic fields ([#5373](https://github.com/juspay/hyperswitch/pull/5373)) ([`4838a86`](https://github.com/juspay/hyperswitch/commit/4838a86ebcb5000e65293e0d095e5de95e3a64a0))
+- **core:** Change primary keys in payment_methods table ([#5393](https://github.com/juspay/hyperswitch/pull/5393)) ([`ca749b3`](https://github.com/juspay/hyperswitch/commit/ca749b32591edcbf4676da4327f8b6ccbc839d4b))
+- **dashboard_metadata:** Alter query for merchant scoped metadata ([#5397](https://github.com/juspay/hyperswitch/pull/5397)) ([`eaa391a`](https://github.com/juspay/hyperswitch/commit/eaa391a959076424399fb9331a78a16eaf790478))
+- **router:** Make `original_payment_authorized_currency` and `original_payment_authorized_amount` mandatory fields for `Discover` cards and `Cybersource` connector during payment method migration. ([#5370](https://github.com/juspay/hyperswitch/pull/5370)) ([`06f1406`](https://github.com/juspay/hyperswitch/commit/06f1406cbc350a71f961a19dc2a6cfef2ceeb3a1))
+
+### Miscellaneous Tasks
+
+- Add missing logs for surcharge flow ([#5258](https://github.com/juspay/hyperswitch/pull/5258)) ([`bc19fca`](https://github.com/juspay/hyperswitch/commit/bc19fca1f4e76be6131e9c870b8aa1c709fef578))
+- Add customer, shipping and billing details to payment_response for payment list api ([#5401](https://github.com/juspay/hyperswitch/pull/5401)) ([`fa6c63b`](https://github.com/juspay/hyperswitch/commit/fa6c63bd5409ec45f23ddf4616c5eb3cf399aa1b))
+
+**Full Changelog:** [`2024.07.20.0...2024.07.23.0`](https://github.com/juspay/hyperswitch/compare/2024.07.20.0...2024.07.23.0)
+
+- - -
+
## 2024.07.20.0
### Features
|
chore
|
2024.07.23.0
|
759474cd4866aa7a6fba055594b9a96de26681a4
|
2025-03-04 18:19:01
|
Kashif
|
refactor(payment_methods): propagate empty wallet details for paypal … (#7423)
| false
|
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 7211b88a10a..6bb923f82ee 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -335,6 +335,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>
merchant_key_store,
profile_id,
&customer_acceptance,
+ merchant_account.storage_scheme,
)
.await?;
@@ -1092,6 +1093,7 @@ impl PaymentCreate {
_key_store: &domain::MerchantKeyStore,
profile_id: common_utils::id_type::ProfileId,
customer_acceptance: &Option<payments::CustomerAcceptance>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
storage::PaymentAttemptNew,
Option<api_models::payments::AdditionalPaymentData>,
@@ -1115,11 +1117,12 @@ impl PaymentCreate {
request: &api::PaymentsRequest,
browser_info: Option<serde_json::Value>,
state: &SessionState,
- payment_method_billing_address_id: Option<String>,
+ optional_payment_method_billing_address_id: Option<String>,
payment_method_info: &Option<domain::PaymentMethod>,
- _key_store: &domain::MerchantKeyStore,
+ key_store: &domain::MerchantKeyStore,
profile_id: common_utils::id_type::ProfileId,
customer_acceptance: &Option<payments::CustomerAcceptance>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
storage::PaymentAttemptNew,
Option<api_models::payments::AdditionalPaymentData>,
@@ -1196,6 +1199,16 @@ impl PaymentCreate {
},
_ => None,
})
+ .or_else(|| match payment_method_type {
+ Some(enums::PaymentMethodType::Paypal) => {
+ Some(api_models::payments::AdditionalPaymentData::Wallet {
+ apple_pay: None,
+ google_pay: None,
+ samsung_pay: None,
+ })
+ }
+ _ => None,
+ })
});
};
@@ -1238,6 +1251,44 @@ impl PaymentCreate {
additional_pm_data.as_ref(),
));
+ // TODO: remove once https://github.com/juspay/hyperswitch/issues/7421 is fixed
+ let payment_method_billing_address_id = match optional_payment_method_billing_address_id {
+ None => payment_method_info
+ .as_ref()
+ .and_then(|pm_info| pm_info.payment_method_billing_address.as_ref())
+ .map(|address| {
+ address.clone().deserialize_inner_value(|value| {
+ value.parse_value::<api_models::payments::Address>("Address")
+ })
+ })
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .ok()
+ .flatten()
+ .async_map(|addr| async move {
+ helpers::create_or_find_address_for_payment_by_request(
+ state,
+ Some(addr.get_inner()),
+ None,
+ merchant_id,
+ payment_method_info
+ .as_ref()
+ .map(|pmd_info| pmd_info.customer_id.clone())
+ .as_ref(),
+ key_store,
+ payment_id,
+ storage_scheme,
+ )
+ .await
+ })
+ .await
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)?
+ .flatten()
+ .map(|address| address.address_id),
+ address_id => address_id,
+ };
+
Ok((
storage::PaymentAttemptNew {
payment_id: payment_id.to_owned(),
|
refactor
|
propagate empty wallet details for paypal … (#7423)
|
3cd74966b279dc1c43935dc1bceb1c69b9eb0643
|
2024-01-08 17:40:56
|
Sahkal Poddar
|
fix(router): Payment link api contract change (#2975)
| false
|
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index ed49b6f27b5..c588bb87189 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -95,15 +95,8 @@ pub struct MerchantAccountCreate {
#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))]
pub frm_routing_algorithm: Option<serde_json::Value>,
- ///Will be used to expire client secret after certain amount of time to be supplied in seconds
- ///(900) for 15 mins
- #[schema(example = 900)]
- pub intent_fulfillment_time: Option<u32>,
-
/// The id of the organization to which the merchant belongs to
pub organization_id: Option<String>,
-
- pub payment_link_config: Option<PaymentLinkConfig>,
}
#[derive(Clone, Debug, Deserialize, Serialize, ToSchema)]
@@ -185,16 +178,10 @@ pub struct MerchantAccountUpdate {
#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))]
pub frm_routing_algorithm: Option<serde_json::Value>,
- ///Will be used to expire client secret after certain amount of time to be supplied in seconds
- ///(900) for 15 mins
- pub intent_fulfillment_time: Option<u32>,
-
/// The default business profile that must be used for creating merchant accounts and payments
/// To unset this field, pass an empty string
#[schema(max_length = 64)]
pub default_profile: Option<String>,
-
- pub payment_link_config: Option<serde_json::Value>,
}
#[derive(Clone, Debug, ToSchema, Serialize)]
@@ -288,8 +275,6 @@ pub struct MerchantAccountResponse {
/// A enum value to indicate the status of recon service. By default it is not_requested.
#[schema(value_type = ReconStatus, example = "not_requested")]
pub recon_status: enums::ReconStatus,
-
- pub payment_link_config: Option<serde_json::Value>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
@@ -460,26 +445,6 @@ pub struct PrimaryBusinessDetails {
pub business: String,
}
-#[derive(Clone, Debug, Deserialize, ToSchema, Serialize, PartialEq)]
-#[serde(deny_unknown_fields)]
-pub struct PaymentLinkConfig {
- #[schema(
- max_length = 255,
- max_length = 255,
- example = "https://i.imgur.com/RfxPFQo.png"
- )]
- pub merchant_logo: Option<String>,
- pub color_scheme: Option<PaymentLinkColorSchema>,
-}
-
-#[derive(Clone, Debug, Deserialize, ToSchema, Serialize, PartialEq)]
-#[serde(deny_unknown_fields)]
-
-pub struct PaymentLinkColorSchema {
- pub background_primary_color: Option<String>,
- pub sdk_theme: Option<String>,
-}
-
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct WebhookDetails {
@@ -1048,6 +1013,13 @@ pub struct BusinessProfileCreate {
/// Verified applepay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
+
+ /// Client Secret Default expiry for all payments created under this business profile
+ #[schema(example = 900)]
+ pub session_expiry: Option<u32>,
+
+ /// Default Payment Link config for all payment links created under this business profile
+ pub payment_link_config: Option<BusinessPaymentLinkConfig>,
}
#[derive(Clone, Debug, ToSchema, Serialize)]
@@ -1112,6 +1084,13 @@ pub struct BusinessProfileResponse {
/// Verified applepay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
+
+ /// Client Secret Default expiry for all payments created under this business profile
+ #[schema(example = 900)]
+ pub session_expiry: Option<i64>,
+
+ /// Default Payment Link config for all payment links created under this business profile
+ pub payment_link_config: Option<serde_json::Value>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
@@ -1169,4 +1148,41 @@ pub struct BusinessProfileUpdate {
/// Verified applepay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
+
+ /// Client Secret Default expiry for all payments created under this business profile
+ #[schema(example = 900)]
+ pub session_expiry: Option<u32>,
+
+ /// Default Payment Link config for all payment links created under this business profile
+ pub payment_link_config: Option<BusinessPaymentLinkConfig>,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
+pub struct BusinessPaymentLinkConfig {
+ pub domain_name: Option<String>,
+ #[serde(flatten)]
+ pub config: PaymentLinkConfigRequest,
+}
+
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
+pub struct PaymentLinkConfigRequest {
+ /// custom theme for the payment link
+ #[schema(value_type = Option<String>, max_length = 255, example = "#4E6ADD")]
+ pub theme: Option<String>,
+ /// merchant display logo
+ #[schema(value_type = Option<String>, max_length = 255, example = "https://i.pinimg.com/736x/4d/83/5c/4d835ca8aafbbb15f84d07d926fda473.jpg")]
+ pub logo: Option<String>,
+ /// Custom merchant name for payment link
+ #[schema(value_type = Option<String>, max_length = 255, example = "hyperswitch")]
+ pub seller_name: Option<String>,
+}
+
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, ToSchema)]
+pub struct PaymentLinkConfig {
+ /// custom theme for the payment link
+ pub theme: String,
+ /// merchant display logo
+ pub logo: String,
+ /// Custom merchant name for payment link
+ pub seller_name: String,
}
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 5a894e868a3..0bfee76304f 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -296,8 +296,14 @@ pub struct PaymentsRequest {
/// additional data that might be required by hyperswitch
pub feature_metadata: Option<FeatureMetadata>,
- /// payment link object required for generating the payment_link
- pub payment_link_object: Option<PaymentLinkObject>,
+
+ /// Whether to get the payment link (if applicable)
+ #[schema(default = false, example = true)]
+ pub payment_link: Option<bool>,
+
+ /// custom payment link config for the particular payment
+ #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)]
+ pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>,
/// The business profile to use for this payment, if not passed the default business profile
/// associated with the merchant account will be used.
@@ -314,6 +320,11 @@ pub struct PaymentsRequest {
///Request for an incremental authorization
pub request_incremental_authorization: Option<bool>,
+ ///Will be used to expire client secret after certain amount of time to be supplied in seconds
+ ///(900) for 15 mins
+ #[schema(example = 900)]
+ pub session_expiry: Option<u32>,
+
/// additional data related to some frm connectors
pub frm_metadata: Option<serde_json::Value>,
}
@@ -3309,17 +3320,6 @@ mod tests {
}
}
-#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
-pub struct PaymentLinkObject {
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub link_expiry: Option<PrimitiveDateTime>,
- pub merchant_custom_domain_name: Option<String>,
- #[schema(value_type = PaymentLinkConfig)]
- pub payment_link_config: Option<admin::PaymentLinkConfig>,
- /// Custom merchant name for payment link
- pub custom_merchant_name: Option<String>,
-}
-
#[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)]
pub struct RetrievePaymentLinkRequest {
pub client_secret: Option<String>,
@@ -3339,10 +3339,10 @@ pub struct RetrievePaymentLinkResponse {
pub amount: i64,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- pub link_expiry: Option<PrimitiveDateTime>,
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub expiry: Option<PrimitiveDateTime>,
pub description: Option<String>,
- pub status: String,
+ pub status: PaymentLinkStatus,
#[schema(value_type = Option<Currency>)]
pub currency: Option<api_enums::Currency>,
}
@@ -3360,14 +3360,15 @@ pub struct PaymentLinkDetails {
pub pub_key: String,
pub client_secret: String,
pub payment_id: String,
- #[serde(with = "common_utils::custom_serde::iso8601::option")]
- pub expiry: Option<PrimitiveDateTime>,
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub session_expiry: PrimitiveDateTime,
pub merchant_logo: String,
pub return_url: String,
pub merchant_name: String,
pub order_details: Option<Vec<OrderDetailsWithStringAmount>>,
pub max_items_visible_after_collapse: i8,
- pub sdk_theme: Option<String>,
+ pub theme: String,
+ pub merchant_description: Option<String>,
}
#[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)]
@@ -3424,6 +3425,13 @@ pub struct PaymentLinkListResponse {
pub data: Vec<PaymentLinkResponse>,
}
+#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
+pub struct PaymentCreatePaymentLinkConfig {
+ #[serde(flatten)]
+ #[schema(value_type = Option<PaymentLinkConfigRequest>)]
+ pub config: admin::PaymentLinkConfigRequest,
+}
+
#[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct OrderDetailsWithStringAmount {
/// Name of the product that is being purchased
@@ -3437,3 +3445,9 @@ pub struct OrderDetailsWithStringAmount {
/// Product Image link
pub product_img_link: Option<String>,
}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub enum PaymentLinkStatus {
+ Active,
+ Expired,
+}
diff --git a/crates/common_utils/src/consts.rs b/crates/common_utils/src/consts.rs
index 7f9533d7ead..169cb972c06 100644
--- a/crates/common_utils/src/consts.rs
+++ b/crates/common_utils/src/consts.rs
@@ -33,11 +33,8 @@ pub const SURCHARGE_PERCENTAGE_PRECISION_LENGTH: u8 = 2;
/// Header Key for application overhead of a request
pub const X_HS_LATENCY: &str = "x-hs-latency";
-/// SDK Default Theme const
-pub const DEFAULT_SDK_THEME: &str = "#7EA8F6";
-
/// Default Payment Link Background color
-pub const DEFAULT_BACKGROUND_COLOR: &str = "#E5E5E5";
+pub const DEFAULT_BACKGROUND_COLOR: &str = "#212E46";
/// Default product Img Link
pub const DEFAULT_PRODUCT_IMG: &str = "https://i.imgur.com/On3VtKF.png";
@@ -50,3 +47,9 @@ pub const PROPHETPAY_REDIRECT_URL: &str = "https://ccm-thirdparty.cps.golf/hp/to
/// Variable which store the card token for Prophetpay
pub const PROPHETPAY_TOKEN: &str = "cctoken";
+
+/// Payment intent fulfillment default timeout (in seconds)
+pub const DEFAULT_FULFILLMENT_TIME: i64 = 15 * 60;
+
+/// Payment intent default client secret expiry (in seconds)
+pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60;
diff --git a/crates/data_models/src/payments.rs b/crates/data_models/src/payments.rs
index b3e2c2e520a..cc6b03f89a5 100644
--- a/crates/data_models/src/payments.rs
+++ b/crates/data_models/src/payments.rs
@@ -53,4 +53,5 @@ pub struct PaymentIntent {
pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
+ pub session_expiry: Option<PrimitiveDateTime>,
}
diff --git a/crates/data_models/src/payments/payment_intent.rs b/crates/data_models/src/payments/payment_intent.rs
index 5389cfdd78d..80671ec7f61 100644
--- a/crates/data_models/src/payments/payment_intent.rs
+++ b/crates/data_models/src/payments/payment_intent.rs
@@ -110,6 +110,7 @@ pub struct PaymentIntentNew {
pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
+ pub session_expiry: Option<PrimitiveDateTime>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -162,6 +163,7 @@ pub enum PaymentIntentUpdate {
metadata: Option<pii::SecretSerdeValue>,
payment_confirm_source: Option<storage_enums::PaymentSource>,
updated_by: String,
+ session_expiry: Option<PrimitiveDateTime>,
},
PaymentAttemptAndAttemptCountUpdate {
active_attempt_id: String,
@@ -226,6 +228,7 @@ pub struct PaymentIntentUpdateInternal {
pub surcharge_applicable: Option<bool>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
+ pub session_expiry: Option<PrimitiveDateTime>,
}
impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
@@ -249,6 +252,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
metadata,
payment_confirm_source,
updated_by,
+ session_expiry,
} => Self {
amount: Some(amount),
currency: Some(currency),
@@ -268,6 +272,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
metadata,
payment_confirm_source,
updated_by,
+ session_expiry,
..Default::default()
},
PaymentIntentUpdate::MetadataUpdate {
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index 700104aaaec..ad66eb7f6f1 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -32,6 +32,8 @@ pub struct BusinessProfile {
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
+ pub payment_link_config: Option<serde_json::Value>,
+ pub session_expiry: Option<i64>,
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
@@ -55,6 +57,8 @@ pub struct BusinessProfileNew {
pub is_recon_enabled: bool,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
+ pub payment_link_config: Option<serde_json::Value>,
+ pub session_expiry: Option<i64>,
}
#[derive(Clone, Debug, Default, AsChangeset, router_derive::DebugAsDisplay)]
@@ -75,6 +79,8 @@ pub struct BusinessProfileUpdateInternal {
pub is_recon_enabled: Option<bool>,
#[diesel(deserialize_as = super::OptionalDieselArray<String>)]
pub applepay_verified_domains: Option<Vec<String>>,
+ pub payment_link_config: Option<serde_json::Value>,
+ pub session_expiry: Option<i64>,
}
impl From<BusinessProfileNew> for BusinessProfile {
@@ -97,6 +103,8 @@ impl From<BusinessProfileNew> for BusinessProfile {
payout_routing_algorithm: new.payout_routing_algorithm,
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,
}
}
}
@@ -118,6 +126,8 @@ impl BusinessProfileUpdateInternal {
payout_routing_algorithm,
is_recon_enabled,
applepay_verified_domains,
+ payment_link_config,
+ session_expiry,
} = self;
BusinessProfile {
profile_name: profile_name.unwrap_or(source.profile_name),
@@ -136,6 +146,8 @@ impl BusinessProfileUpdateInternal {
payout_routing_algorithm,
is_recon_enabled: is_recon_enabled.unwrap_or(source.is_recon_enabled),
applepay_verified_domains,
+ payment_link_config,
+ session_expiry,
..source
}
}
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index df567f58357..6b546f90787 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -55,18 +55,11 @@ pub struct PaymentIntent {
pub request_incremental_authorization: Option<RequestIncrementalAuthorization>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
+ pub session_expiry: Option<PrimitiveDateTime>,
}
#[derive(
- Clone,
- Debug,
- Default,
- Eq,
- PartialEq,
- Insertable,
- router_derive::DebugAsDisplay,
- Serialize,
- Deserialize,
+ Clone, Debug, Eq, PartialEq, Insertable, router_derive::DebugAsDisplay, Serialize, Deserialize,
)]
#[diesel(table_name = payment_intent)]
pub struct PaymentIntentNew {
@@ -112,6 +105,8 @@ pub struct PaymentIntentNew {
pub request_incremental_authorization: Option<RequestIncrementalAuthorization>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
+ pub session_expiry: Option<PrimitiveDateTime>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -164,6 +159,7 @@ pub enum PaymentIntentUpdate {
metadata: Option<pii::SecretSerdeValue>,
payment_confirm_source: Option<storage_enums::PaymentSource>,
updated_by: String,
+ session_expiry: Option<PrimitiveDateTime>,
},
PaymentAttemptAndAttemptCountUpdate {
active_attempt_id: String,
@@ -229,6 +225,7 @@ pub struct PaymentIntentUpdateInternal {
pub surcharge_applicable: Option<bool>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
+ pub session_expiry: Option<PrimitiveDateTime>,
}
impl PaymentIntentUpdate {
@@ -261,6 +258,7 @@ impl PaymentIntentUpdate {
surcharge_applicable,
incremental_authorization_allowed,
authorization_count,
+ session_expiry,
} = self.into();
PaymentIntent {
amount: amount.unwrap_or(source.amount),
@@ -290,10 +288,10 @@ impl PaymentIntentUpdate {
payment_confirm_source: payment_confirm_source.or(source.payment_confirm_source),
updated_by,
surcharge_applicable: surcharge_applicable.or(source.surcharge_applicable),
-
incremental_authorization_allowed: incremental_authorization_allowed
.or(source.incremental_authorization_allowed),
authorization_count: authorization_count.or(source.authorization_count),
+ session_expiry,
..source
}
}
@@ -320,6 +318,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
metadata,
payment_confirm_source,
updated_by,
+ session_expiry,
} => Self {
amount: Some(amount),
currency: Some(currency),
@@ -339,6 +338,7 @@ impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
metadata,
payment_confirm_source,
updated_by,
+ session_expiry,
..Default::default()
},
PaymentIntentUpdate::MetadataUpdate {
diff --git a/crates/diesel_models/src/payment_link.rs b/crates/diesel_models/src/payment_link.rs
index 999a6767d8f..ed0e979d026 100644
--- a/crates/diesel_models/src/payment_link.rs
+++ b/crates/diesel_models/src/payment_link.rs
@@ -18,17 +18,17 @@ pub struct PaymentLink {
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
pub fulfilment_time: Option<PrimitiveDateTime>,
pub custom_merchant_name: Option<String>,
pub payment_link_config: Option<serde_json::Value>,
pub description: Option<String>,
+ pub profile_id: Option<String>,
}
#[derive(
Clone,
Debug,
- Default,
Eq,
PartialEq,
Insertable,
@@ -48,9 +48,10 @@ pub struct PaymentLinkNew {
pub created_at: Option<PrimitiveDateTime>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub last_modified_at: Option<PrimitiveDateTime>,
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ #[serde(with = "common_utils::custom_serde::iso8601::option")]
pub fulfilment_time: Option<PrimitiveDateTime>,
pub custom_merchant_name: Option<String>,
pub payment_link_config: Option<serde_json::Value>,
pub description: Option<String>,
+ pub profile_id: Option<String>,
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index f4a0437c6cc..f4e41cefdef 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -83,6 +83,8 @@ diesel::table! {
payout_routing_algorithm -> Nullable<Jsonb>,
is_recon_enabled -> Bool,
applepay_verified_domains -> Nullable<Array<Nullable<Text>>>,
+ payment_link_config -> Nullable<Jsonb>,
+ session_expiry -> Nullable<Int8>,
}
}
@@ -705,6 +707,7 @@ diesel::table! {
request_incremental_authorization -> Nullable<RequestIncrementalAuthorization>,
incremental_authorization_allowed -> Nullable<Bool>,
authorization_count -> Nullable<Int4>,
+ session_expiry -> Nullable<Timestamp>,
}
}
@@ -731,6 +734,8 @@ diesel::table! {
payment_link_config -> Nullable<Jsonb>,
#[max_length = 255]
description -> Nullable<Varchar>,
+ #[max_length = 64]
+ profile_id -> Nullable<Varchar>,
}
}
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index eff42c0cd7c..afe76184630 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -24,6 +24,9 @@ pub const REQUEST_TIMEOUT_ERROR_MESSAGE_FROM_PSYNC: &str =
///Payment intent fulfillment default timeout (in seconds)
pub const DEFAULT_FULFILLMENT_TIME: i64 = 15 * 60;
+/// Payment intent default client secret expiry (in seconds)
+pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60;
+
// String literals
pub(crate) const NO_ERROR_MESSAGE: &str = "No error message";
pub(crate) const NO_ERROR_CODE: &str = "No error code";
@@ -71,4 +74,10 @@ pub const VERIFY_CONNECTOR_ID_PREFIX: &str = "conn_verify";
#[cfg(feature = "olap")]
pub const VERIFY_CONNECTOR_MERCHANT_ID: &str = "test_merchant";
+/// Max payment session expiry
+pub const MAX_SESSION_EXPIRY: u32 = 7890000;
+
+/// Min payment session expiry
+pub const MIN_SESSION_EXPIRY: u32 = 60;
+
pub const LOCKER_HEALTH_CALL_PATH: &str = "/health";
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 84a2f442de8..53810593206 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -140,17 +140,6 @@ pub async fn create_merchant_account(
.transpose()?
.map(Secret::new);
- let payment_link_config = req
- .payment_link_config
- .as_ref()
- .map(|pl_metadata| {
- utils::Encode::<admin_types::PaymentLinkConfig>::encode_to_value(pl_metadata)
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "payment_link_config",
- })
- })
- .transpose()?;
-
let organization_id = if let Some(organization_id) = req.organization_id.as_ref() {
db.find_organization_by_org_id(organization_id)
.await
@@ -199,15 +188,15 @@ pub async fn create_merchant_account(
primary_business_details,
created_at: date_time::now(),
modified_at: date_time::now(),
+ intent_fulfillment_time: None,
frm_routing_algorithm: req.frm_routing_algorithm,
- intent_fulfillment_time: req.intent_fulfillment_time.map(i64::from),
payout_routing_algorithm: req.payout_routing_algorithm,
id: None,
organization_id,
is_recon_enabled: false,
default_profile: None,
recon_status: diesel_models::enums::ReconStatus::NotRequested,
- payment_link_config,
+ payment_link_config: None,
})
}
.await
@@ -429,6 +418,8 @@ pub async fn update_business_profile_cascade(
frm_routing_algorithm: None,
payout_routing_algorithm: None,
applepay_verified_domains: None,
+ payment_link_config: None,
+ session_expiry: None,
};
let update_futures = business_profiles.iter().map(|business_profile| async {
@@ -581,10 +572,10 @@ pub async fn merchant_account_update(
publishable_key: None,
primary_business_details,
frm_routing_algorithm: req.frm_routing_algorithm,
- intent_fulfillment_time: req.intent_fulfillment_time.map(i64::from),
+ intent_fulfillment_time: None,
payout_routing_algorithm: req.payout_routing_algorithm,
default_profile: business_profile_id_update,
- payment_link_config: req.payment_link_config,
+ payment_link_config: None,
};
let response = db
@@ -1426,6 +1417,9 @@ pub async fn create_business_profile(
request: api::BusinessProfileCreate,
merchant_id: &str,
) -> RouterResponse<api_models::admin::BusinessProfileResponse> {
+ if let Some(session_expiry) = &request.session_expiry {
+ helpers::validate_session_expiry(session_expiry.to_owned())?;
+ }
let db = state.store.as_ref();
let key_store = db
.get_merchant_key_store_by_merchant_id(merchant_id, &db.get_master_key().to_vec().into())
@@ -1539,6 +1533,10 @@ pub async fn update_business_profile(
})?
}
+ if let Some(session_expiry) = &request.session_expiry {
+ helpers::validate_session_expiry(session_expiry.to_owned())?;
+ }
+
let webhook_details = request
.webhook_details
.as_ref()
@@ -1561,6 +1559,17 @@ pub async fn update_business_profile(
.attach_printable("Invalid routing algorithm given")?;
}
+ let payment_link_config = request
+ .payment_link_config
+ .as_ref()
+ .map(|pl_metadata| {
+ utils::Encode::<admin_types::BusinessPaymentLinkConfig>::encode_to_value(pl_metadata)
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "payment_link_config",
+ })
+ })
+ .transpose()?;
+
let business_profile_update = storage::business_profile::BusinessProfileUpdateInternal {
profile_name: request.profile_name,
modified_at: Some(date_time::now()),
@@ -1576,6 +1585,8 @@ pub async fn update_business_profile(
payout_routing_algorithm: request.payout_routing_algorithm,
is_recon_enabled: None,
applepay_verified_domains: request.applepay_verified_domains,
+ payment_link_config,
+ session_expiry: request.session_expiry.map(i64::from),
};
let updated_business_profile = db
diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs
index 81b06f5f9aa..f2043d392ab 100644
--- a/crates/router/src/core/payment_link.rs
+++ b/crates/router/src/core/payment_link.rs
@@ -1,7 +1,8 @@
use api_models::admin as admin_types;
use common_utils::{
consts::{
- DEFAULT_BACKGROUND_COLOR, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG, DEFAULT_SDK_THEME,
+ DEFAULT_BACKGROUND_COLOR, DEFAULT_MERCHANT_LOGO, DEFAULT_PRODUCT_IMG,
+ DEFAULT_SESSION_EXPIRY,
},
ext_traits::{OptionExt, ValueExt},
};
@@ -27,15 +28,20 @@ pub async fn retrieve_payment_link(
payment_link_id: String,
) -> RouterResponse<api_models::payments::RetrievePaymentLinkResponse> {
let db = &*state.store;
- let payment_link_object = db
+ let payment_link_config = db
.find_payment_link_by_payment_link_id(&payment_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?;
- let status = check_payment_link_status(payment_link_object.fulfilment_time);
+ let session_expiry = payment_link_config.fulfilment_time.unwrap_or_else(|| {
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY))
+ });
+
+ let status = check_payment_link_status(session_expiry);
let response = api_models::payments::RetrievePaymentLinkResponse::foreign_from((
- payment_link_object,
+ payment_link_config,
status,
));
Ok(services::ApplicationResponse::Json(response))
@@ -74,15 +80,25 @@ pub async fn intiate_payment_link_flow(
"use payment link for",
)?;
+ let merchant_name_from_merchant_account = merchant_account
+ .merchant_name
+ .clone()
+ .map(|merchant_name| merchant_name.into_inner().peek().to_owned())
+ .unwrap_or_default();
+
let payment_link = db
.find_payment_link_by_payment_link_id(&payment_link_id)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?;
- let payment_link_config = if let Some(pl_config) = payment_link.payment_link_config.clone() {
- extract_payment_link_config(Some(pl_config))?
+ let payment_link_config = if let Some(pl_config_value) = payment_link.payment_link_config {
+ extract_payment_link_config(pl_config_value)?
} else {
- extract_payment_link_config(merchant_account.payment_link_config.clone())?
+ admin_types::PaymentLinkConfig {
+ theme: DEFAULT_BACKGROUND_COLOR.to_string(),
+ logo: DEFAULT_MERCHANT_LOGO.to_string(),
+ seller_name: merchant_name_from_merchant_account,
+ }
};
let return_url = if let Some(payment_create_return_url) = payment_intent.return_url {
@@ -102,8 +118,13 @@ pub async fn intiate_payment_link_flow(
)?;
let order_details = validate_order_details(payment_intent.order_details, currency)?;
- let (default_sdk_theme, default_background_color) =
- (DEFAULT_SDK_THEME, DEFAULT_BACKGROUND_COLOR);
+ let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| {
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY))
+ });
+
+ // converting first letter of merchant name to upperCase
+ let merchant_name = capitalize_first_char(&payment_link_config.seller_name);
let payment_details = api_models::payments::PaymentLinkDetails {
amount: currency
@@ -112,38 +133,20 @@ pub async fn intiate_payment_link_flow(
.change_context(errors::ApiErrorResponse::CurrencyConversionFailed)?,
currency,
payment_id: payment_intent.payment_id,
- merchant_name: payment_link.custom_merchant_name.unwrap_or(
- merchant_account
- .merchant_name
- .map(|merchant_name| merchant_name.into_inner().peek().to_owned())
- .unwrap_or_default(),
- ),
+ merchant_name,
order_details,
return_url,
- expiry: payment_link.fulfilment_time,
+ session_expiry,
pub_key,
client_secret,
- merchant_logo: payment_link_config
- .clone()
- .map(|pl_config| {
- pl_config
- .merchant_logo
- .unwrap_or(DEFAULT_MERCHANT_LOGO.to_string())
- })
- .unwrap_or_default(),
+ merchant_logo: payment_link_config.clone().logo,
max_items_visible_after_collapse: 3,
- sdk_theme: payment_link_config.clone().and_then(|pl_config| {
- pl_config
- .color_scheme
- .map(|color| color.sdk_theme.unwrap_or(default_sdk_theme.to_string()))
- }),
+ theme: payment_link_config.clone().theme,
+ merchant_description: payment_intent.description,
};
let js_script = get_js_script(payment_details)?;
- let css_script = get_color_scheme_css(
- payment_link_config.clone(),
- default_background_color.to_string(),
- );
+ let css_script = get_color_scheme_css(payment_link_config.clone());
let payment_link_data = services::PaymentLinkFormData {
js_script,
sdk_url: state.conf.payment_link.sdk_url.clone(),
@@ -168,20 +171,8 @@ fn get_js_script(
Ok(format!("window.__PAYMENT_DETAILS = {payment_details_str};"))
}
-fn get_color_scheme_css(
- payment_link_config: Option<api_models::admin::PaymentLinkConfig>,
- default_primary_color: String,
-) -> String {
- let background_primary_color = payment_link_config
- .and_then(|pl_config| {
- pl_config.color_scheme.map(|color| {
- color
- .background_primary_color
- .unwrap_or(default_primary_color.clone())
- })
- })
- .unwrap_or(default_primary_color);
-
+fn get_color_scheme_css(payment_link_config: api_models::admin::PaymentLinkConfig) -> String {
+ let background_primary_color = payment_link_config.theme;
format!(
":root {{
--primary-color: {background_primary_color};
@@ -226,13 +217,15 @@ pub async fn list_payment_link(
Ok(services::ApplicationResponse::Json(payment_link_list))
}
-pub fn check_payment_link_status(fulfillment_time: Option<PrimitiveDateTime>) -> String {
- let curr_time = Some(common_utils::date_time::now());
+pub fn check_payment_link_status(
+ max_age: PrimitiveDateTime,
+) -> api_models::payments::PaymentLinkStatus {
+ let curr_time = common_utils::date_time::now();
- if curr_time > fulfillment_time {
- "expired".to_string()
+ if curr_time > max_age {
+ api_models::payments::PaymentLinkStatus::Expired
} else {
- "active".to_string()
+ api_models::payments::PaymentLinkStatus::Active
}
}
@@ -276,7 +269,8 @@ fn validate_order_details(
.to_currency_base_unit(order.amount)
.into_report()
.change_context(errors::ApiErrorResponse::CurrencyConversionFailed)?;
- order_details_amount_string.product_name = order.product_name.clone();
+ order_details_amount_string.product_name =
+ capitalize_first_char(&order.product_name.clone());
order_details_amount_string.quantity = order.quantity;
order_details_amount_string_array.push(order_details_amount_string)
}
@@ -287,16 +281,91 @@ fn validate_order_details(
Ok(updated_order_details)
}
-fn extract_payment_link_config(
- pl_config: Option<serde_json::Value>,
-) -> Result<Option<admin_types::PaymentLinkConfig>, error_stack::Report<errors::ApiErrorResponse>> {
- pl_config
- .map(|config| {
- serde_json::from_value::<admin_types::PaymentLinkConfig>(config)
- .into_report()
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "payment_link_config",
- })
+pub fn extract_payment_link_config(
+ pl_config: serde_json::Value,
+) -> Result<api_models::admin::PaymentLinkConfig, error_stack::Report<errors::ApiErrorResponse>> {
+ serde_json::from_value::<api_models::admin::PaymentLinkConfig>(pl_config.clone())
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "payment_link_config",
})
- .transpose()
+}
+
+pub fn get_payment_link_config_based_on_priority(
+ payment_create_link_config: Option<api_models::payments::PaymentCreatePaymentLinkConfig>,
+ business_link_config: Option<serde_json::Value>,
+ merchant_name: String,
+ default_domain_name: String,
+) -> Result<(admin_types::PaymentLinkConfig, String), error_stack::Report<errors::ApiErrorResponse>>
+{
+ let (domain_name, business_config) = if let Some(business_config) = business_link_config {
+ let extracted_value: api_models::admin::BusinessPaymentLinkConfig = business_config
+ .parse_value("BusinessPaymentLinkConfig")
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "payment_link_config",
+ })
+ .attach_printable("Invalid payment_link_config given in business config")?;
+
+ (
+ extracted_value
+ .domain_name
+ .clone()
+ .map(|d_name| format!("https://{}", d_name))
+ .unwrap_or_else(|| default_domain_name.clone()),
+ Some(extracted_value.config),
+ )
+ } else {
+ (default_domain_name, None)
+ };
+
+ let theme = payment_create_link_config
+ .as_ref()
+ .and_then(|pc_config| pc_config.config.theme.clone())
+ .or_else(|| {
+ business_config
+ .as_ref()
+ .and_then(|business_config| business_config.theme.clone())
+ })
+ .unwrap_or(DEFAULT_BACKGROUND_COLOR.to_string());
+
+ let logo = payment_create_link_config
+ .as_ref()
+ .and_then(|pc_config| pc_config.config.logo.clone())
+ .or_else(|| {
+ business_config
+ .as_ref()
+ .and_then(|business_config| business_config.logo.clone())
+ })
+ .unwrap_or(DEFAULT_MERCHANT_LOGO.to_string());
+
+ let seller_name = payment_create_link_config
+ .as_ref()
+ .and_then(|pc_config| pc_config.config.seller_name.clone())
+ .or_else(|| {
+ business_config
+ .as_ref()
+ .and_then(|business_config| business_config.seller_name.clone())
+ })
+ .unwrap_or(merchant_name.clone());
+
+ let payment_link_config = admin_types::PaymentLinkConfig {
+ theme,
+ logo,
+ seller_name,
+ };
+
+ Ok((payment_link_config, domain_name))
+}
+
+fn capitalize_first_char(s: &str) -> String {
+ if let Some(first_char) = s.chars().next() {
+ let capitalized = first_char.to_uppercase();
+ let mut result = capitalized.to_string();
+ if let Some(remaining) = s.get(1..) {
+ result.push_str(remaining);
+ }
+ result
+ } else {
+ s.to_owned()
+ }
}
diff --git a/crates/router/src/core/payment_link/payment_link.html b/crates/router/src/core/payment_link/payment_link.html
index 0ca4abd340d..4fb5bb98efe 100644
--- a/crates/router/src/core/payment_link/payment_link.html
+++ b/crates/router/src/core/payment_link/payment_link.html
@@ -1,9 +1,9 @@
<!DOCTYPE html>
-<html>
+<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
- {{ hyperloader_sdk_link }}
+ <title>Payments requested by HyperSwitch</title>
<style>
{{ css_color_scheme }}
@@ -19,8 +19,7 @@
align-items: center;
justify-content: flex-start;
margin: 0;
- background-color: #fafafa;
- color: #292929;
+ color: #333333;
}
/* Hide scrollbar for Chrome, Safari and Opera */
@@ -36,16 +35,27 @@
/* Firefox */
}
+ /* For ellipsis on text lines */
+ .ellipsis-container-3 {
+ height: 4em;
+ overflow: hidden;
+ display: -webkit-box;
+ -webkit-line-clamp: 3;
+ -webkit-box-orient: vertical;
+ text-overflow: ellipsis;
+ white-space: normal;
+ }
+
.hidden {
display: none !important;
}
.hyper-checkout {
display: flex;
- background-color: #fafafa;
+ background-color: #f8f9fb;
+ color: #333333;
width: 100%;
height: 100%;
- max-width: 1900px;
overflow: scroll;
}
@@ -54,7 +64,6 @@
display: flex;
justify-content: center;
background-color: white;
- z-index: 100;
padding: 20px 0;
}
@@ -63,8 +72,7 @@
flex-flow: column;
justify-content: center;
align-items: center;
- background-color: #fdfdfd;
- min-width: 500px;
+ min-width: 600px;
width: 50vw;
}
@@ -73,15 +81,23 @@
}
.hyper-checkout-payment {
- border: 1px solid #e6e6e6;
+ min-width: 600px;
+ box-shadow: 0px 0px 5px #d1d1d1;
border-radius: 8px;
- min-width: 582px;
+ background-color: #fefefe;
}
.hyper-checkout-payment-content-details {
+ display: flex;
+ flex-flow: column;
+ justify-content: space-between;
+ align-content: space-between;
+ }
+
+ .content-details-wrap {
display: flex;
flex-flow: row;
- margin: 20px;
+ margin: 20px 20px 30px 20px;
justify-content: space-between;
}
@@ -94,16 +110,17 @@
}
#hyper-checkout-payment-merchant-details {
- margin-top: 20px;
+ margin-top: 5px;
}
.hyper-checkout-payment-merchant-name {
font-weight: 600;
- font-size: 18px;
+ font-size: 19px;
}
.hyper-checkout-payment-ref {
- font-size: 13px;
+ font-size: 12px;
+ margin-top: 5px;
}
.hyper-checkout-image-header {
@@ -119,13 +136,14 @@
border: 1px solid #e6e6e6;
border-radius: 4px;
display: flex;
+ align-self: flex-start;
align-items: center;
justify-content: center;
}
#hyper-checkout-merchant-image > img {
- height: 40px;
- width: 40px;
+ height: 48px;
+ width: 48px;
}
#hyper-checkout-cart-image {
@@ -138,25 +156,24 @@
}
#hyper-checkout-payment-footer {
- padding: 8px 20px;
+ margin-top: 20px;
background-color: #f5f5f5;
font-size: 13px;
font-weight: 500;
+ padding: 12px 20px;
+ border-radius: 0 0 8px 8px;
}
#hyper-checkout-cart {
display: flex;
flex-flow: column;
- min-width: 584px;
- width: 400px;
- margin-top: 30px;
- max-height: 600px;
+ min-width: 600px;
+ margin-top: 40px;
+ max-height: 60vh;
}
#hyper-checkout-cart-items {
- margin: 10px 20px 10px 0;
- max-height: 354px;
- height: 354px;
+ max-height: 291px;
overflow: scroll;
transition: all 0.3s ease;
}
@@ -181,14 +198,14 @@
.hyper-checkout-cart-item {
display: flex;
flex-flow: row;
- padding: 20px 10px;
+ padding: 20px 0;
font-size: 15px;
- box-shadow: 0px 0px 10px #efefef;
}
.hyper-checkout-cart-product-image {
height: 56px;
width: 56px;
+ border-radius: 4px;
}
.hyper-checkout-card-item-name {
@@ -213,7 +230,7 @@
.hyper-checkout-cart-product-details {
display: flex;
flex-flow: column;
- margin-left: 10px;
+ margin-left: 15px;
justify-content: space-between;
width: 100%;
}
@@ -233,10 +250,30 @@
}
.hyper-checkout-cart-button {
- color: var(--primary-color);
- font-size: 15px;
- font-weight: 600;
+ font-size: 12px;
+ font-weight: 500;
cursor: pointer;
+ align-self: flex-start;
+ display: flex;
+ align-content: flex-end;
+ gap: 3px;
+ text-decoration: none;
+ transition: text-decoration 0.3s;
+ margin-top: 10px;
+ }
+
+ .hyper-checkout-cart-button:hover {
+ text-decoration: underline;
+ }
+
+ #hyper-checkout-merchant-description {
+ font-size: 13px;
+ color: #808080;
+ }
+
+ .powered-by-hyper {
+ margin-top: 40px;
+ align-self: flex-start;
}
.hyper-checkout-sdk {
@@ -259,10 +296,6 @@
border-radius: 3px;
}
- .powered-by-hyper {
- margin-top: 20px;
- }
-
#hyper-checkout-sdk-header {
padding: 10px 10px 10px 22px;
display: flex;
@@ -315,82 +348,155 @@
margin-top: 10px;
}
- .page-spinner,
- .page-spinner::before,
- .page-spinner::after {
- border-radius: 50%;
- }
-
.page-spinner {
- color: #ffffff;
- font-size: 22px;
- text-indent: -99999px;
- margin: 0px auto;
- position: relative;
- width: 20px;
- height: 20px;
- box-shadow: inset 0 0 0 2px;
- -webkit-transform: translateZ(0);
- -ms-transform: translateZ(0);
- transform: translateZ(0);
- }
-
- .page-spinner::before,
- .page-spinner::after {
position: absolute;
- content: "";
+ width: 100vw;
+ height: 100vh;
+ z-index: 3;
+ background-color: #fff;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .sdk-spinner {
+ width: 100%;
+ height: 100%;
+ z-index: 3;
+ background-color: #fff;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ }
+ .spinner {
+ width: 60px;
+ height: 60px;
+ }
+ .spinner div {
+ transform-origin: 30px 30px;
+ animation: spinner 1.2s linear infinite;
+ }
+ .spinner div:after {
+ content: " ";
+ display: block;
+ position: absolute;
+ top: 3px;
+ left: 28px;
+ width: 4px;
+ height: 15px;
+ border-radius: 20%;
+ background: var(--primary-color);
+ }
+ .spinner div:nth-child(1) {
+ transform: rotate(0deg);
+ animation-delay: -1.1s;
+ }
+ .spinner div:nth-child(2) {
+ transform: rotate(30deg);
+ animation-delay: -1s;
+ }
+ .spinner div:nth-child(3) {
+ transform: rotate(60deg);
+ animation-delay: -0.9s;
+ }
+ .spinner div:nth-child(4) {
+ transform: rotate(90deg);
+ animation-delay: -0.8s;
+ }
+ .spinner div:nth-child(5) {
+ transform: rotate(120deg);
+ animation-delay: -0.7s;
+ }
+ .spinner div:nth-child(6) {
+ transform: rotate(150deg);
+ animation-delay: -0.6s;
+ }
+ .spinner div:nth-child(7) {
+ transform: rotate(180deg);
+ animation-delay: -0.5s;
+ }
+ .spinner div:nth-child(8) {
+ transform: rotate(210deg);
+ animation-delay: -0.4s;
+ }
+ .spinner div:nth-child(9) {
+ transform: rotate(240deg);
+ animation-delay: -0.3s;
+ }
+ .spinner div:nth-child(10) {
+ transform: rotate(270deg);
+ animation-delay: -0.2s;
+ }
+ .spinner div:nth-child(11) {
+ transform: rotate(300deg);
+ animation-delay: -0.1s;
+ }
+ .spinner div:nth-child(12) {
+ transform: rotate(330deg);
+ animation-delay: 0s;
+ }
+ @keyframes spinner {
+ 0% {
+ opacity: 1;
+ }
+ 100% {
+ opacity: 0;
+ }
}
- .page-spinner {
- color: var(--primary-color) !important;
- height: 50px !important;
- width: 50px !important;
- box-shadow: inset 0 0 0 4px !important;
- margin: auto !important;
+ #hyper-checkout-status-canvas {
+ width: 100%;
+ height: 100%;
+ justify-content: center;
+ align-items: center;
+ background-color: var(--primary-color);
}
- #hyper-checkout-status {
+ .hyper-checkout-status-wrap {
display: flex;
flex-flow: column;
font-family: "Montserrat";
- height: 100%;
- width: 100%;
+ width: auto;
+ min-width: 400px;
+ background-color: white;
+ border-radius: 5px;
}
#hyper-checkout-status-header {
max-width: 1200px;
- border: 1px solid #e6e6e6;
border-radius: 3px;
- padding: 20px;
+ border-bottom: 1px solid #e6e6e6;
}
#hyper-checkout-status-header,
#hyper-checkout-status-content {
- width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
font-size: 24px;
font-weight: 600;
+ padding: 15px 20px;
}
.hyper-checkout-status-amount {
font-family: "Montserrat";
- font-size: 40px;
+ font-size: 35px;
font-weight: 700;
}
.hyper-checkout-status-merchant-logo {
border: 1px solid #e6e6e6;
- height: 62px;
- width: 62px;
+ border-radius: 5px;
+ padding: 9px;
+ height: 48px;
+ width: 48px;
}
#hyper-checkout-status-content {
- justify-content: center;
- align-items: center;
- flex-flow: column;
height: 100%;
+ flex-flow: column;
+ min-height: 500px;
+ align-items: center;
+ justify-content: center;
}
.hyper-checkout-status-image {
@@ -400,17 +506,18 @@
.hyper-checkout-status-text {
text-align: center;
- font-size: 28px;
+ font-size: 21px;
font-weight: 600;
margin-top: 20px;
}
.hyper-checkout-status-message {
text-align: center;
- font-size: 12px;
+ font-size: 12px !important;
margin-top: 10px;
font-size: 14px;
font-weight: 500;
+ max-width: 400px;
}
.hyper-checkout-status-details {
@@ -419,7 +526,7 @@
margin-top: 20px;
border-radius: 3px;
border: 1px solid #e6e6e6;
- width: 90vw;
+ max-width: calc(100vw - 40px);
}
.hyper-checkout-status-item {
@@ -427,6 +534,7 @@
align-items: center;
padding: 5px 10px;
border-bottom: 1px solid #e6e6e6;
+ word-wrap: break-word;
}
.hyper-checkout-status-item:last-child {
@@ -443,6 +551,13 @@
overflow-x: hidden;
overflow-y: auto;
word-wrap: break-word;
+ font-weight: 400;
+ }
+
+ #hyper-checkout-status-redirect-message {
+ margin-top: 20px;
+ font-family: "Montserrat";
+ font-size: 13px;
}
@keyframes loading {
@@ -490,10 +605,20 @@
text-align: center;
}
- @media only screen and (max-width: 1200px) {
+ @media only screen and (max-width: 1400px) {
+ body {
+ overflow: scroll;
+ }
+
.hyper-checkout {
flex-flow: column;
margin: 0;
+ height: auto;
+ overflow: visible;
+ }
+
+ #hyper-checkout-payment-merchant-details {
+ margin-top: 20px;
}
.main {
@@ -502,9 +627,10 @@
}
.hyper-checkout-payment {
- min-width: 100px;
- width: 100vw;
+ min-width: 300px;
+ width: calc(100vw - 50px);
margin: 0;
+ padding: 25px;
border: 0;
border-radius: 0;
background-color: var(--primary-color);
@@ -515,9 +641,16 @@
}
.hyper-checkout-payment-content-details {
+ max-width: 520px;
+ width: 100%;
+ align-self: center;
+ margin-bottom: 0;
+ }
+
+ .content-details-wrap {
flex-flow: column;
flex-direction: column-reverse;
- margin: 24px;
+ margin: 0;
}
#hyper-checkout-merchant-image {
@@ -538,11 +671,9 @@
}
#hyper-checkout-payment-footer {
- background-color: var(--primary-accent-color);
border-radius: 50px;
- width: auto;
- align-self: center;
- margin: 0 24px 24px 24px;
+ width: max-content;
+ padding: 10px 20px;
}
#hyper-checkout-cart {
@@ -574,7 +705,6 @@
#hyper-checkout-cart-items {
margin: 20px 20px 0 20px;
padding: 0;
- max-height: max-content;
}
.hyper-checkout-cart-button {
@@ -582,17 +712,30 @@
text-align: right;
}
+ .powered-by-hyper {
+ display: none;
+ }
+
#hyper-checkout-sdk {
- margin: 20px 0 0 0;
background-color: transparent;
+ width: auto;
min-width: 300px;
- width: 100vw;
}
#payment-form-wrap {
min-width: 300px;
- padding: 10px;
- width: calc(100vw - 20px);
+ width: calc(100vw - 40px);
+ margin: 0;
+ padding: 25px 20px;
+ }
+
+ #hyper-checkout-status-canvas {
+ background-color: #fefefe;
+ }
+
+ .hyper-checkout-status-wrap {
+ min-width: 100vw;
+ width: 100vw;
}
#hyper-checkout-status-header {
@@ -604,7 +747,8 @@
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;500;600;700;800"
/>
-
+ </head>
+ <body>
<!-- SVG ICONS -->
<svg xmlns="http://www.w3.org/2000/svg" display="none">
<defs>
@@ -618,7 +762,7 @@
width="16"
height="16"
>
- <path d="M16 0H0V16H16V0Z" fill="white" />
+ <path d="M16 0H0V16H16V0Z" fill="white"></path>
</mask>
<g mask="url(#mask0_1_13)">
<mask
@@ -630,19 +774,19 @@
width="16"
height="16"
>
- <path d="M16 0H0V16H16V0Z" fill="#D9D9D9" />
+ <path d="M16 0H0V16H16V0Z" fill="#D9D9D9"></path>
</mask>
<g mask="url(#mask1_1_13)">
<path
d="M3.53716 14.3331C3.20469 14.3331 2.92071 14.2153 2.68525 13.9798C2.44977 13.7444 2.33203 13.4604 2.33203 13.1279V5.53823C2.33203 5.20575 2.44977 4.92178 2.68525 4.68631C2.92071 4.45083 3.20469 4.3331 3.53716 4.3331H4.9987C4.9987 3.50063 5.29058 2.79252 5.87433 2.20876C6.4581 1.62501 7.16621 1.33313 7.99868 1.33313C8.83115 1.33313 9.53927 1.62501 10.123 2.20876C10.7068 2.79252 10.9987 3.50063 10.9987 4.3331H12.4602C12.7927 4.3331 13.0766 4.45083 13.3121 4.68631C13.5476 4.92178 13.6653 5.20575 13.6653 5.53823V13.1279C13.6653 13.4604 13.5476 13.7444 13.3121 13.9798C13.0766 14.2153 12.7927 14.3331 12.4602 14.3331H3.53716ZM3.53716 13.3331H12.4602C12.5115 13.3331 12.5585 13.3117 12.6012 13.269C12.644 13.2262 12.6653 13.1792 12.6653 13.1279V5.53823C12.6653 5.48694 12.644 5.43992 12.6012 5.39718C12.5585 5.35445 12.5115 5.33308 12.4602 5.33308H3.53716C3.48588 5.33308 3.43886 5.35445 3.39611 5.39718C3.35338 5.43992 3.33201 5.48694 3.33201 5.53823V13.1279C3.33201 13.1792 3.35338 13.2262 3.39611 13.269C3.43886 13.3117 3.48588 13.3331 3.53716 13.3331ZM7.99868 8.99973C8.83115 8.99973 9.53927 8.70785 10.123 8.1241C10.7068 7.54033 10.9987 6.83221 10.9987 5.99975H9.99868C9.99868 6.5553 9.80424 7.02752 9.41535 7.41641C9.02646 7.8053 8.55424 7.99975 7.99868 7.99975C7.44313 7.99975 6.9709 7.8053 6.58202 7.41641C6.19313 7.02752 5.99868 6.5553 5.99868 5.99975H4.9987C4.9987 6.83221 5.29058 7.54033 5.87433 8.1241C6.4581 8.70785 7.16621 8.99973 7.99868 8.99973ZM5.99868 4.3331H9.99868C9.99868 3.77754 9.80424 3.30532 9.41535 2.91643C9.02646 2.52754 8.55424 2.3331 7.99868 2.3331C7.44313 2.3331 6.9709 2.52754 6.58202 2.91643C6.19313 3.30532 5.99868 3.77754 5.99868 4.3331Z"
fill="#333333"
- />
+ ></path>
</g>
</g>
</symbol>
<symbol id="cart-icon-big">
<mask
- id="mask0_1_13"
+ id="mask0_1_14"
style="mask-type: luminance"
maskUnits="userSpaceOnUse"
x="0"
@@ -650,11 +794,11 @@
width="30"
height="30"
>
- <path d="M30 0H0V30H30V0Z" fill="white" />
+ <path d="M30 0H0V30H30V0Z" fill="white"></path>
</mask>
- <g mask="url(#mask0_1_13)">
+ <g mask="url(#mask0_1_14)">
<mask
- id="mask1_1_13"
+ id="mask1_1_14"
style="mask-type: alpha"
maskUnits="userSpaceOnUse"
x="0"
@@ -662,13 +806,13 @@
width="30"
height="30"
>
- <path d="M30 0H0V30H30V0Z" fill="#D9D9D9" />
+ <path d="M30 0H0V30H30V0Z" fill="#D9D9D9"></path>
</mask>
- <g mask="url(#mask1_1_13)">
+ <g mask="url(#mask1_1_14)">
<path
d="M6.63218 26.8746C6.0088 26.8746 5.47633 26.6537 5.03485 26.2121C4.59332 25.7708 4.37256 25.2383 4.37256 24.6148V10.3842C4.37256 9.76078 4.59332 9.22834 5.03485 8.78683C5.47633 8.34531 6.0088 8.12456 6.63218 8.12456H9.37257C9.37257 6.56368 9.91984 5.23597 11.0144 4.14142C12.1089 3.04689 13.4366 2.49962 14.9975 2.49962C16.5584 2.49962 17.8861 3.04689 18.9806 4.14142C20.0753 5.23597 20.6226 6.56368 20.6226 8.12456H23.3629C23.9863 8.12456 24.5186 8.34531 24.9602 8.78683C25.4018 9.22834 25.6224 9.76078 25.6224 10.3842V24.6148C25.6224 25.2383 25.4018 25.7708 24.9602 26.2121C24.5186 26.6537 23.9863 26.8746 23.3629 26.8746H6.63218ZM6.63218 24.9996H23.3629C23.4591 24.9996 23.5472 24.9594 23.6273 24.8794C23.7075 24.7991 23.7474 24.711 23.7474 24.6148V10.3842C23.7474 10.288 23.7075 10.1999 23.6273 10.1197C23.5472 10.0396 23.4591 9.99952 23.3629 9.99952H6.63218C6.53603 9.99952 6.44786 10.0396 6.36771 10.1197C6.28759 10.1999 6.24752 10.288 6.24752 10.3842V24.6148C6.24752 24.711 6.28759 24.7991 6.36771 24.8794C6.44786 24.9594 6.53603 24.9996 6.63218 24.9996ZM14.9975 16.8745C16.5584 16.8745 17.8861 16.3272 18.9806 15.2327C20.0753 14.1381 20.6226 12.8104 20.6226 11.2495H18.7475C18.7475 12.2912 18.383 13.1766 17.6538 13.9058C16.9246 14.6349 16.0392 14.9995 14.9975 14.9995C13.9559 14.9995 13.0704 14.6349 12.3413 13.9058C11.6121 13.1766 11.2475 12.2912 11.2475 11.2495H9.37257C9.37257 12.8104 9.91984 14.1381 11.0144 15.2327C12.1089 16.3272 13.4366 16.8745 14.9975 16.8745ZM11.2475 8.12456H18.7475C18.7475 7.08289 18.383 6.19747 17.6538 5.46831C16.9246 4.73914 16.0392 4.37456 14.9975 4.37456C13.9559 4.37456 13.0704 4.73914 12.3413 5.46831C11.6121 6.19747 11.2475 7.08289 11.2475 8.12456Z"
fill="#333333"
- />
+ ></path>
</g>
</g>
</symbol>
@@ -730,52 +874,100 @@
></path>
</g>
</symbol>
+ <symbol id="arrow-down">
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M8.20573 11.0351C8.33593 11.0351 8.45573 10.9831 8.54948 10.8841L12.5911 6.75911C12.6797 6.66536 12.7266 6.55078 12.7266 6.41536C12.7266 6.14974 12.5234 5.94141 12.2526 5.94141C12.1224 5.94141 12.0026 5.99349 11.9141 6.07682L8.20573 9.86848L4.4974 6.07682C4.40887 5.99349 4.29429 5.94141 4.15882 5.94141C3.88798 5.94141 3.68486 6.14974 3.68486 6.41536C3.68486 6.55078 3.7318 6.66536 3.82549 6.75911L7.86198 10.8841C7.96094 10.9831 8.07551 11.0351 8.20573 11.0351Z"
+ fill="#333333"
+ ></path>
+ </svg>
+ </symbol>
+ <symbol id="arrow-up">
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 16 16"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ >
+ <path
+ d="M7.79427 4.96485C7.66407 4.96485 7.54427 5.01694 7.45052 5.11587L3.40886 9.24089C3.32032 9.33464 3.27344 9.44922 3.27344 9.58464C3.27344 9.85026 3.47657 10.0586 3.7474 10.0586C3.87761 10.0586 3.9974 10.0065 4.08594 9.92318L7.79427 6.13152L11.5026 9.92318C11.5911 10.0065 11.7057 10.0586 11.8412 10.0586C12.112 10.0586 12.3151 9.85026 12.3151 9.58464C12.3151 9.44922 12.2682 9.33464 12.1745 9.24089L8.13802 5.11587C8.03906 5.01694 7.92449 4.96485 7.79427 4.96485Z"
+ fill="#333333"
+ ></path>
+ </svg>
+ </symbol>
</defs>
</svg>
- </head>
-
- <body onload="showSDK()">
- <div class="page-spinner hidden" id="page-spinner"></div>
+ <div id="page-spinner" class="page-spinner hidden">
+ <div class="spinner">
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ </div>
+ </div>
<div class="hyper-checkout">
- <div class="main hidden" id="hyper-checkout-status">
- <div id="hyper-checkout-status-header"></div>
- <div id="hyper-checkout-status-content"></div>
+ <div class="main hidden" id="hyper-checkout-status-canvas">
+ <div class="hyper-checkout-status-wrap">
+ <div id="hyper-checkout-status-header"></div>
+ <div id="hyper-checkout-status-content"></div>
+ </div>
+ <div id="hyper-checkout-status-redirect-message"></div>
</div>
- <div class="main hidden" id="hyper-checkout-details">
- <div class="hyper-checkout-payment">
+ <div class="main" id="hyper-checkout-details">
+ <div id="hyper-checkout-payment" class="hyper-checkout-payment">
<div class="hyper-checkout-payment-content-details">
- <div id="hyper-checkout-payment-context">
- <div id="hyper-checkout-payment-merchant-details"></div>
- </div>
- <div class="hyper-checkout-image-header">
- <div id="hyper-checkout-merchant-image"></div>
- <div
- id="hyper-checkout-cart-image"
- onclick="viewCartInMobileView()"
- >
- <svg
- width="30"
- height="30"
- viewBox="0 0 30 30"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- class="cart-icon"
+ <div class="content-details-wrap">
+ <div id="hyper-checkout-payment-context">
+ <div id="hyper-checkout-payment-merchant-details"></div>
+ </div>
+ <div class="hyper-checkout-image-header">
+ <div id="hyper-checkout-merchant-image"></div>
+ <div
+ id="hyper-checkout-cart-image"
+ onclick="viewCartInMobileView()"
>
- <use
- xlink:href="#cart-icon-big"
- x="0"
- y="0"
+ <svg
width="30"
height="30"
- />
- </svg>
+ viewBox="0 0 30 30"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ class="cart-icon"
+ >
+ <use
+ xlink:href="#cart-icon-big"
+ x="0"
+ y="0"
+ width="30"
+ height="30"
+ ></use>
+ </svg>
+ </div>
</div>
</div>
+ <div id="hyper-checkout-payment-footer"></div>
</div>
- <div id="hyper-checkout-payment-footer"></div>
</div>
<div id="hyper-checkout-cart" class="">
- <div class="hyper-checkout-cart-header">
+ <div
+ id="hyper-checkout-cart-header"
+ class="hyper-checkout-cart-header"
+ >
<svg
width="16"
height="16"
@@ -790,7 +982,7 @@
y="0"
width="16"
height="16"
- />
+ ></use>
</svg>
<span>Your Cart</span>
<svg
@@ -807,61 +999,58 @@
y="0"
width="50"
height="50"
- />
+ ></use>
</svg>
</div>
<div id="hyper-checkout-cart-items" class="hide-scrollbar"></div>
+ <div id="hyper-checkout-merchant-description"></div>
+ <div class="powered-by-hyper">
+ <svg class="fill-current" height="18" width="130">
+ <use
+ xlink:href="#hyperswitch-brand"
+ x="0"
+ y="0"
+ height="18"
+ width="130"
+ ></use>
+ </svg>
+ </div>
</div>
</div>
- <div class="hyper-checkout-sdk hidden" id="hyper-checkout-sdk">
+ <div class="hyper-checkout-sdk" id="hyper-checkout-sdk">
<div id="payment-form-wrap">
- <form id="payment-form">
- <div id="unified-checkout">
- <div
- id="orca-element-unified-checkout"
- style="height: auto"
- class="payment base"
- >
- <div id="orca-fullscreen-iframeRef-unified-checkout"></div>
- <iframe
- id="orca-payment-element-iframeRef-unified-checkout"
- name="orca-payment-element-iframeRef-unified-checkout"
- src="http://localhost:9050/?componentName=payment"
- allow="payment *"
- style="
- border: 0px;
- transition: height 0.35s ease 0s, opacity 0.4s ease 0.1s;
- height: 368px;
- "
- width="100%"
- ></iframe>
- </div>
+ <div id="sdk-spinner" class="sdk-spinner">
+ <div class="spinner">
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
+ <div></div>
</div>
+ </div>
+ <form id="payment-form">
+ <div id="unified-checkout"></div>
<div id="payment-message" class="hidden"></div>
</form>
</div>
- <div class="powered-by-hyper">
- <svg class="fill-current" height="18" width="130" transform="">
- <use
- xlink:href="#hyperswitch-brand"
- x="0"
- y="0"
- height="18"
- width="130"
- />
- </svg>
- </div>
</div>
</div>
<div id="hyper-footer" class="hidden">
- <svg class="fill-current" height="18" width="130" transform="">
+ <svg class="fill-current" height="18" width="130">
<use
xlink:href="#hyperswitch-brand"
x="0"
y="0"
height="18"
width="130"
- />
+ ></use>
</svg>
</div>
@@ -872,25 +1061,152 @@
prevHeight: window.innerHeight,
prevWidth: window.innerWidth,
isMobileView: window.innerWidth <= 1200,
+ currentScreen: "payment_link",
};
var widgets = null;
var unifiedCheckout = null;
var pub_key = window.__PAYMENT_DETAILS.pub_key;
- var hyper = Hyper(pub_key);
+ var hyper = null;
- function mountUnifiedCheckout(id) {
- if (unifiedCheckout !== null) {
- unifiedCheckout.mount(id);
+ // Boot functions
+ function boot() {
+ // Update HTML doc
+ var paymentDetails = window.__PAYMENT_DETAILS;
+
+ if (paymentDetails.merchant_name) {
+ document.title =
+ "Payment requested by " + paymentDetails.merchant_name;
+ }
+
+ if (paymentDetails.merchant_logo) {
+ var link = document.createElement("link");
+ link.rel = "icon";
+ link.href = paymentDetails.merchant_logo;
+ link.type = "image/x-icon";
+ document.head.appendChild(link);
+ }
+
+ // Render UI
+ renderPaymentDetails();
+ renderSDKHeader();
+ renderCart();
+
+ // Deal w loaders
+ show("#sdk-spinner");
+ hide("#page-spinner");
+ hide("#unified-checkout");
+
+ // Add event listeners
+ initializeEventListeners();
+
+ // Initialize SDK
+ if (window.Hyper) {
+ initializeSDK();
+ }
+
+ // State specific functions
+ if (window.state.isMobileView) {
+ show("#hyper-footer");
+ hide("#hyper-checkout-cart");
+ } else {
+ show("#hyper-checkout-cart");
}
}
+ boot();
+
+ function initializeEventListeners() {
+ var primaryColor = window
+ .getComputedStyle(document.documentElement)
+ .getPropertyValue("--primary-color");
+ var lighterColor = adjustLightness(primaryColor, 1.4);
+ var darkerColor = adjustLightness(primaryColor, 0.8);
+ var contrastBWColor = invert(primaryColor, true);
+ var hyperCheckoutNode = document.getElementById(
+ "hyper-checkout-payment"
+ );
+ var hyperCheckoutFooterNode = document.getElementById(
+ "hyper-checkout-payment-footer"
+ );
+ var statusRedirectTextNode = document.getElementById(
+ "hyper-checkout-status-redirect-message"
+ );
+
+ if (window.innerWidth <= 1200) {
+ statusRedirectTextNode.style.color = "#333333";
+ hyperCheckoutNode.style.color = contrastBWColor;
+ var a = lighterColor.match(/[fF]/gi);
+ hyperCheckoutFooterNode.style.backgroundColor =
+ Array.isArray(a) && a.length > 4 ? darkerColor : lighterColor;
+ } else if (window.innerWidth > 1200) {
+ statusRedirectTextNode.style.color = contrastBWColor;
+ hyperCheckoutNode.style.color = "#333333";
+ hyperCheckoutFooterNode.style.backgroundColor = "#F5F5F5";
+ }
- async function initialize() {
+ window.addEventListener("resize", function (event) {
+ var currentHeight = window.innerHeight;
+ var currentWidth = window.innerWidth;
+ if (currentWidth <= 1200 && window.state.prevWidth > 1200) {
+ hide("#hyper-checkout-cart");
+ if (window.state.currentScreen === "payment_link") {
+ show("#hyper-footer");
+ }
+ try {
+ statusRedirectTextNode.style.color = "#333333";
+ hyperCheckoutNode.style.color = contrastBWColor;
+ hyperCheckoutFooterNode.style.backgroundColor = lighterColor;
+ } catch (error) {
+ console.error(
+ "Failed to fetch primary-color, using default",
+ error
+ );
+ }
+ } else if (currentWidth > 1200 && window.state.prevWidth <= 1200) {
+ if (window.state.currentScreen === "payment_link") {
+ hide("#hyper-footer");
+ }
+ show("#hyper-checkout-cart");
+ try {
+ statusRedirectTextNode.style.color = contrastBWColor;
+ hyperCheckoutNode.style.color = "#333333";
+ hyperCheckoutFooterNode.style.backgroundColor = "#F5F5F5";
+ } catch (error) {
+ console.error("Failed to revert back to default colors", error);
+ }
+ }
+
+ window.state.prevHeight = currentHeight;
+ window.state.prevWidth = currentWidth;
+ window.state.isMobileView = currentWidth <= 1200;
+ });
+ }
+
+ function showSDK() {
+ checkStatus()
+ .then(function (res) {
+ if (res.showSdk) {
+ show("#hyper-checkout-sdk");
+ show("#hyper-checkout-details");
+ } else {
+ hide("#hyper-checkout-details");
+ hide("#hyper-checkout-sdk");
+ show("#hyper-checkout-status-canvas");
+ hide("#hyper-footer");
+ window.state.currentScreen = "status";
+ }
+ })
+ .catch(function (err) {
+ console.error("Failed to check status", err);
+ });
+ }
+
+ function initializeSDK() {
var paymentDetails = window.__PAYMENT_DETAILS;
var client_secret = paymentDetails.client_secret;
var appearance = {
variables: {
- colorPrimary: paymentDetails.sdk_theme || "rgb(0, 109, 249)",
+ colorPrimary: paymentDetails.theme || "rgb(0, 109, 249)",
fontFamily: "Work Sans, sans-serif",
fontSizeBase: "16px",
colorText: "rgb(51, 65, 85)",
@@ -901,12 +1217,11 @@
colorBackground: "rgb(255, 255, 255)",
},
};
-
+ hyper = window.Hyper(pub_key);
widgets = hyper.widgets({
- appearance,
+ appearance: appearance,
clientSecret: client_secret,
});
-
var unifiedCheckoutOptions = {
layout: "tabs",
sdkHandleConfirmPayment: true,
@@ -920,10 +1235,29 @@
},
},
};
-
unifiedCheckout = widgets.create("payment", unifiedCheckoutOptions);
mountUnifiedCheckout("#unified-checkout");
+ // Add event listener for SDK iframe mutations
+ var orcaIFrame = document.getElementById(
+ "orca-payment-element-iframeRef-unified-checkout"
+ );
+ var callback = function (mutationList, observer) {
+ for (var i = 0; i < mutationList.length; i++) {
+ var mutation = mutationList[i];
+
+ if (
+ mutation.type === "attributes" &&
+ mutation.attributeName === "style"
+ ) {
+ show("#unified-checkout");
+ hide("#sdk-spinner");
+ }
+ }
+ };
+ var observer = new MutationObserver(callback);
+ observer.observe(orcaIFrame, { attributes: true });
+
// Handle button press callback
var paymentElement = widgets.getElement("payment");
if (paymentElement) {
@@ -931,111 +1265,132 @@
handleSubmit(event);
});
}
+ showSDK();
}
- initialize();
-
- async function handleSubmit(e) {
- var paymentDetails = window.__PAYMENT_DETAILS;
- var { error, data, status } = await hyper.confirmPayment({
- widgets,
- confirmParams: {
- // Make sure to change this to your payment completion page
- return_url: paymentDetails.return_url,
- },
- });
- // This point will only be reached if there is an immediate error occurring while confirming the payment. Otherwise, your customer will be redirected to your 'return_url'.
- // For some payment flows such as Sofort, iDEAL, your customer will be redirected to an intermediate page to complete authorization of the payment, and then redirected to the 'return_url'.
-
- if (error) {
- if (error.type === "validation_error") {
- showMessage(error.message);
- } else {
- showMessage("An unexpected error occurred.");
- }
- // Re-initialize SDK
- mountUnifiedCheckout("#unified-checkout");
- } else {
- var { paymentIntent } = await hyper.retrievePaymentIntent(
- paymentDetails.client_secret
- );
- if (paymentIntent && paymentIntent.status) {
- hide("#hyper-checkout-sdk");
- hide("#hyper-checkout-details");
- show("#hyper-checkout-status");
- show("#hyper-footer");
- showStatus(paymentIntent);
- }
+ // Util functions
+ function mountUnifiedCheckout(id) {
+ if (unifiedCheckout !== null) {
+ unifiedCheckout.mount(id);
}
}
- // Fetches the payment status after payment submission
- async function checkStatus() {
+ function handleSubmit(e) {
var paymentDetails = window.__PAYMENT_DETAILS;
- var res = {
- showSdk: true,
- };
-
- let clientSecret = new URLSearchParams(window.location.search).get(
- "payment_intent_client_secret"
- );
-
- // If clientSecret is not found in URL params, try to fetch from window context
- if (!clientSecret) {
- clientSecret = paymentDetails.client_secret;
- }
+ hyper
+ .confirmPayment({
+ widgets: widgets,
+ confirmParams: {
+ // Make sure to change this to your payment completion page
+ return_url: paymentDetails.return_url,
+ },
+ })
+ .then(function (result) {
+ var error = result.error;
+ if (error) {
+ if (error.type === "validation_error") {
+ showMessage(error.message);
+ } else {
+ showMessage("An unexpected error occurred.");
+ }
- // If clientSecret is not present, show status
- if (!clientSecret) {
- res.showSdk = false;
- showStatus(
- Object.assign({}, paymentDetails, {
- status: "",
- error: {
- code: "NO_CLIENT_SECRET",
- message: "client_secret not found",
- },
- })
- );
- return res;
- }
+ // Re-initialize SDK
+ mountUnifiedCheckout("#unified-checkout");
+ } else {
+ // This point will only be reached if there is an immediate error occurring while confirming the payment. Otherwise, your customer will be redirected to your 'return_url'.
+ // For some payment flows such as Sofort, iDEAL, your customer will be redirected to an intermediate page to complete authorization of the payment, and then redirected to the 'return_url'.
+ hyper
+ .retrievePaymentIntent(paymentDetails.client_secret)
+ .then(function (result) {
+ var paymentIntent = result.paymentIntent;
+ if (paymentIntent && paymentIntent.status) {
+ hide("#hyper-checkout-sdk");
+ hide("#hyper-checkout-details");
+ show("#hyper-checkout-status-canvas");
+ showStatus(
+ paymentDetails.amount,
+ Object.assign(paymentDetails, paymentIntent)
+ );
+ }
+ })
+ .catch(function (error) {
+ console.error("Error retrieving payment_intent", error);
+ });
+ }
+ })
+ .catch(function (error) {
+ console.error("Error confirming payment_intent", error);
+ });
+ }
- var { paymentIntent } = await hyper.retrievePaymentIntent(clientSecret);
-
- // If paymentIntent was not found, show status
- if (!paymentIntent) {
- res.showSdk = false;
- showStatus(
- Object.assign({}, paymentDetails, {
- status: "",
- error: {
- code: "NOT_FOUND",
- message: "PaymentIntent was not found",
- },
- })
+ // Fetches the payment status after payment submission
+ function checkStatus() {
+ return new window.Promise(function (resolve, reject) {
+ var paymentDetails = window.__PAYMENT_DETAILS;
+ var res = {
+ showSdk: true,
+ };
+
+ var clientSecret = new URLSearchParams(window.location.search).get(
+ "payment_intent_client_secret"
);
- return res;
- }
-
- // Show SDK only if paymentIntent status has not been initiated
- switch (paymentIntent.status) {
- case "requires_confirmation":
- case "requires_payment_method":
- return res;
- }
- showStatus(paymentIntent);
- res.showSdk = false;
-
- return res;
- }
+ // If clientSecret is not found in URL params, try to fetch from window context
+ if (!clientSecret) {
+ clientSecret = paymentDetails.client_secret;
+ }
- function setPageLoading(showLoader) {
- if (showLoader) {
- show(".page-spinner");
- } else {
- hide(".page-spinner");
- }
+ // If clientSecret is not present, show status
+ if (!clientSecret) {
+ res.showSdk = false;
+ showStatus(
+ paymentDetails.amount,
+ Object.assign(paymentDetails, {
+ status: "",
+ error: {
+ code: "NO_CLIENT_SECRET",
+ message: "client_secret not found",
+ },
+ })
+ );
+ return resolve(res);
+ }
+ hyper
+ .retrievePaymentIntent(clientSecret)
+ .then(function (response) {
+ var paymentIntent = response.paymentIntent;
+ // If paymentIntent was not found, show status
+ if (!paymentIntent) {
+ res.showSdk = false;
+ showStatus(
+ paymentDetails.amount,
+ Object.assign(paymentDetails, {
+ status: "",
+ error: {
+ code: "NOT_FOUND",
+ message: "PaymentIntent was not found",
+ },
+ })
+ );
+ return resolve(res);
+ }
+ // Show SDK only if paymentIntent status has not been initiated
+ switch (paymentIntent.status) {
+ case "requires_confirmation":
+ case "requires_payment_method":
+ return resolve(res);
+ }
+ showStatus(
+ paymentDetails.amount,
+ Object.assign(paymentDetails, paymentIntent)
+ );
+ res.showSdk = false;
+ resolve(res);
+ })
+ .catch(function (error) {
+ reject(error);
+ });
+ });
}
function show(id) {
@@ -1050,9 +1405,9 @@
addText("#payment-message", msg);
}
- function showStatus(paymentDetails) {
+ function showStatus(amount, paymentDetails) {
var status = paymentDetails.status;
- let statusDetails = {
+ var statusDetails = {
imageSource: "",
message: null,
status: status,
@@ -1142,8 +1497,7 @@
// Form header items
var amountNode = document.createElement("div");
amountNode.className = "hyper-checkout-status-amount";
- amountNode.innerText =
- paymentDetails.currency + " " + paymentDetails.amount;
+ amountNode.innerText = paymentDetails.currency + " " + amount;
var merchantLogoNode = document.createElement("img");
merchantLogoNode.className = "hyper-checkout-status-merchant-logo";
merchantLogoNode.src = window.__PAYMENT_DETAILS.merchant_logo;
@@ -1163,23 +1517,72 @@
statusDetailsNode.className = "hyper-checkout-status-details";
// Append items
- statusDetails.items.map((item) => statusDetailsNode?.append(item));
+ if (statusDetailsNode instanceof HTMLDivElement) {
+ statusDetails.items.map(function (item) {
+ statusDetailsNode.append(item);
+ });
+ }
var statusHeaderNode = document.getElementById(
"hyper-checkout-status-header"
);
- if (statusHeaderNode !== null) {
+ if (statusHeaderNode instanceof HTMLDivElement) {
statusHeaderNode.append(amountNode, merchantLogoNode);
}
var statusContentNode = document.getElementById(
"hyper-checkout-status-content"
);
- if (statusContentNode !== null) {
+ if (statusContentNode instanceof HTMLDivElement) {
statusContentNode.append(statusImageNode, statusTextNode);
- if (statusDetails.message !== null) {
+ if (statusDetails.message instanceof HTMLDivElement) {
statusContentNode.append(statusMessageNode);
}
statusContentNode.append(statusDetailsNode);
}
+
+ // Form redirect text
+ var statusRedirectTextNode = document.getElementById(
+ "hyper-checkout-status-redirect-message"
+ );
+ if (
+ statusRedirectTextNode &&
+ typeof paymentDetails.return_url === "string"
+ ) {
+ var timeout = 5,
+ j = 0;
+ for (var i = 0; i <= timeout; i++) {
+ setTimeout(function () {
+ var secondsLeft = timeout - j++;
+ var innerText =
+ secondsLeft === 0
+ ? "Redirecting ..."
+ : "Redirecting in " + secondsLeft + " seconds ...";
+ statusRedirectTextNode.innerText = innerText;
+ if (secondsLeft === 0) {
+ // Form query params
+ var queryParams = {
+ payment_id: paymentDetails.payment_id,
+ status: paymentDetails.status,
+ payment_intent_client_secret: paymentDetails.client_secret,
+ amount: amount,
+ manual_retry_allowed: paymentDetails.manual_retry_allowed,
+ };
+ var url = new URL(paymentDetails.return_url);
+ var params = new URLSearchParams(url.search);
+ // Attach query params to return_url
+ for (var key in queryParams) {
+ if (queryParams.hasOwnProperty(key)) {
+ params.set(key, queryParams[key]);
+ }
+ }
+ url.search = params.toString();
+ setTimeout(function () {
+ // Finally redirect
+ window.location.href = url.toString();
+ }, 1000);
+ }
+ }, i * 1000);
+ }
+ }
}
function createItem(heading, value) {
@@ -1211,6 +1614,61 @@
element.classList.remove(className);
}
+ function formatDate(date) {
+ var months = [
+ "January",
+ "February",
+ "March",
+ "April",
+ "May",
+ "June",
+ "July",
+ "August",
+ "September",
+ "October",
+ "November",
+ "December",
+ ];
+
+ var hours = date.getHours();
+ var minutes = date.getMinutes();
+ minutes = minutes < 10 ? "0" + minutes : minutes;
+ var suffix = hours > 11 ? "PM" : "AM";
+ hours = hours % 12;
+ hours = hours ? hours : 12;
+ var day = date.getDate();
+ var month = months[date.getMonth()];
+ var year = date.getUTCFullYear();
+
+ var locale = navigator.language || navigator.userLanguage;
+ var timezoneShorthand = date
+ .toLocaleDateString(locale, {
+ day: "2-digit",
+ timeZoneName: "long",
+ })
+ .substring(4)
+ .split(" ")
+ .reduce(function (tz, c) {
+ return tz + c.charAt(0).toUpperCase();
+ }, "");
+
+ var formatted =
+ hours +
+ ":" +
+ minutes +
+ " " +
+ suffix +
+ " " +
+ timezoneShorthand +
+ " " +
+ month +
+ " " +
+ day +
+ ", " +
+ year;
+ return formatted;
+ }
+
function renderPaymentDetails() {
var paymentDetails = window.__PAYMENT_DETAILS;
@@ -1238,8 +1696,9 @@
// Create expiry node
var paymentExpiryNode = document.createElement("div");
paymentExpiryNode.className = "hyper-checkout-payment-footer-expiry";
- paymentExpiryNode.innerText =
- "Link expires on: " + new Date(paymentDetails.expiry).toTimeString();
+ var expiryDate = new Date(paymentDetails.session_expiry);
+ var formattedDate = formatDate(expiryDate);
+ paymentExpiryNode.innerText = "Link expires on: " + formattedDate;
// Append information to DOM
var paymentContextNode = document.getElementById(
@@ -1264,17 +1723,17 @@
function renderCart() {
var paymentDetails = window.__PAYMENT_DETAILS;
var orderDetails = paymentDetails.order_details;
- var cartNode = document.getElementById("hyper-checkout-cart");
- var cartItemsNode = document.getElementById(
- "hyper-checkout-cart-items"
- );
-
- var MAX_ITEMS_VISIBLE_AFTER_COLLAPSE =
- paymentDetails.max_items_visible_after_collapse;
// Cart items
- if (Array.isArray(orderDetails)) {
- orderDetails.map((item, index) => {
+ if (Array.isArray(orderDetails) && orderDetails.length > 0) {
+ var cartNode = document.getElementById("hyper-checkout-cart");
+ var cartItemsNode = document.getElementById(
+ "hyper-checkout-cart-items"
+ );
+ var MAX_ITEMS_VISIBLE_AFTER_COLLAPSE =
+ paymentDetails.max_items_visible_after_collapse;
+
+ orderDetails.map(function (item, index) {
if (index >= MAX_ITEMS_VISIBLE_AFTER_COLLAPSE) {
return;
}
@@ -1285,22 +1744,38 @@
cartItemsNode
);
});
- }
-
- // Expand / collapse button
- var totalItems = orderDetails.length;
- if (totalItems > MAX_ITEMS_VISIBLE_AFTER_COLLAPSE) {
- var expandButtonNode = document.createElement("div");
- expandButtonNode.className = "hyper-checkout-cart-button";
- expandButtonNode.onclick = handleCartView;
- var buttonImageNode = document.createElement("img");
- var buttonTextNode = document.createElement("span");
- buttonTextNode.id = "hyper-checkout-cart-button-text";
- var hiddenItemsCount =
- orderDetails.length - MAX_ITEMS_VISIBLE_AFTER_COLLAPSE;
- buttonTextNode.innerText = "Show More (" + hiddenItemsCount + ")";
- expandButtonNode.append(buttonTextNode, buttonImageNode);
- cartNode.append(expandButtonNode);
+ // Expand / collapse button
+ var totalItems = orderDetails.length;
+ if (totalItems > MAX_ITEMS_VISIBLE_AFTER_COLLAPSE) {
+ var expandButtonNode = document.createElement("div");
+ expandButtonNode.className = "hyper-checkout-cart-button";
+ expandButtonNode.onclick = handleCartView;
+ var buttonImageNode = document.createElement("svg");
+ buttonImageNode.id = "hyper-checkout-cart-button-arrow";
+ buttonImageNode.innerHTML =
+ document.getElementById("arrow-down").innerHTML;
+ var buttonTextNode = document.createElement("span");
+ buttonTextNode.id = "hyper-checkout-cart-button-text";
+ var hiddenItemsCount =
+ orderDetails.length - MAX_ITEMS_VISIBLE_AFTER_COLLAPSE;
+ buttonTextNode.innerText = "Show More (" + hiddenItemsCount + ")";
+ expandButtonNode.append(buttonTextNode, buttonImageNode);
+ cartNode.insertBefore(expandButtonNode, cartNode.lastElementChild);
+ }
+ } else {
+ hide("#hyper-checkout-cart-header");
+ hide("#hyper-checkout-cart-items");
+ hide("#hyper-checkout-cart-image");
+ if (
+ typeof paymentDetails.merchant_description === "string" &&
+ paymentDetails.merchant_description.length > 0
+ ) {
+ show("#hyper-checkout-merchant-description");
+ var merchantDescription = paymentDetails.merchant_description;
+ document.getElementById(
+ "hyper-checkout-merchant-description"
+ ).innerText = merchantDescription;
+ }
}
}
@@ -1367,9 +1842,12 @@
var cartButtonTextNode = document.getElementById(
"hyper-checkout-cart-button-text"
);
+ var cartButtonImageNode = document.getElementById(
+ "hyper-checkout-cart-button-arrow"
+ );
if (isHidden) {
if (Array.isArray(orderDetails)) {
- orderDetails.map((item, index) => {
+ orderDetails.map(function (item, index) {
if (index < MAX_ITEMS_VISIBLE_AFTER_COLLAPSE) {
return;
}
@@ -1384,18 +1862,20 @@
cartItemsNode.style.maxHeight = cartItemsNode.scrollHeight + "px";
cartItemsNode.style.height = cartItemsNode.scrollHeight + "px";
cartButtonTextNode.innerText = "Show Less";
+ cartButtonImageNode.innerHTML =
+ document.getElementById("arrow-up").innerHTML;
} else {
- cartItemsNode.style.maxHeight = "354px";
- cartItemsNode.style.height = "354px";
+ cartItemsNode.style.maxHeight = "300px";
+ cartItemsNode.style.height = "290px";
cartItemsNode.scrollTo({ top: 0, behavior: "smooth" });
setTimeout(function () {
- cartItems.map((item, index) => {
+ cartItems.map(function (item, index) {
if (index < MAX_ITEMS_VISIBLE_AFTER_COLLAPSE) {
return;
}
cartItemsNode.removeChild(item);
});
- dividerItems.map((item, index) => {
+ dividerItems.map(function (item, index) {
if (index < MAX_ITEMS_VISIBLE_AFTER_COLLAPSE - 1) {
return;
}
@@ -1407,6 +1887,8 @@
orderDetails.length - MAX_ITEMS_VISIBLE_AFTER_COLLAPSE;
cartButtonTextNode.innerText =
"Show More (" + hiddenItemsCount + ")";
+ cartButtonImageNode.innerHTML =
+ document.getElementById("arrow-down").innerHTML;
}, 250);
}
}
@@ -1450,53 +1932,168 @@
var sdkHeaderNode = document.getElementById(
"hyper-checkout-sdk-header"
);
- if (sdkHeaderNode !== null) {
+ if (sdkHeaderNode instanceof HTMLDivElement) {
sdkHeaderNode.append(sdkHeaderLogoNode);
sdkHeaderNode.append(sdkHeaderItemNode);
}
}
- function showSDK(e) {
- if (window.state.isMobileView) {
- hide("#hyper-checkout-cart");
+ function adjustLightness(hexColor, factor) {
+ // Convert hex to RGB
+ var r = parseInt(hexColor.slice(1, 3), 16);
+ var g = parseInt(hexColor.slice(3, 5), 16);
+ var b = parseInt(hexColor.slice(5, 7), 16);
+
+ // Convert RGB to HSL
+ var hsl = rgbToHsl(r, g, b);
+
+ // Adjust lightness
+ hsl[2] = Math.max(0, Math.min(100, hsl[2] * factor));
+
+ // Convert HSL back to RGB
+ var rgb = hslToRgb(hsl[0], hsl[1], hsl[2]);
+
+ // Convert RGB to hex
+ var newHexColor = rgbToHex(rgb[0], rgb[1], rgb[2]);
+
+ return newHexColor;
+ }
+ function rgbToHsl(r, g, b) {
+ r /= 255;
+ g /= 255;
+ b /= 255;
+ var max = Math.max(r, g, b),
+ min = Math.min(r, g, b);
+ var h,
+ s,
+ l = (max + min) / 2;
+
+ if (max === min) {
+ h = s = 0;
} else {
- show("#hyper-checkout-cart");
+ var d = max - min;
+ s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
+ switch (max) {
+ case r:
+ h = (g - b) / d + (g < b ? 6 : 0);
+ break;
+ case g:
+ h = (b - r) / d + 2;
+ break;
+ case b:
+ h = (r - g) / d + 4;
+ break;
+ }
+ h /= 6;
}
- setPageLoading(true);
- checkStatus()
- .then((res) => {
- if (res.showSdk) {
- renderPaymentDetails();
- renderCart();
- renderSDKHeader();
- show("#hyper-checkout-sdk");
- show("#hyper-checkout-details");
- } else {
- hide("#hyper-checkout-sdk");
- hide("#hyper-checkout-details");
- show("#hyper-checkout-status");
- show("#hyper-footer");
- }
- })
- .catch((err) => {})
- .finally(() => {
- setPageLoading(false);
- });
+
+ return [h * 360, s * 100, l * 100];
}
+ function hslToRgb(h, s, l) {
+ h /= 360;
+ s /= 100;
+ l /= 100;
+ var r, g, b;
- window.addEventListener("resize", (event) => {
- var currentHeight = window.innerHeight;
- var currentWidth = window.innerWidth;
- if (currentWidth <= 1200 && window.state.prevWidth > 1200) {
- hide("#hyper-checkout-cart");
- } else if (currentWidth > 1200 && window.state.prevWidth <= 1200) {
- show("#hyper-checkout-cart");
+ if (s === 0) {
+ r = g = b = l;
+ } else {
+ var hue2rgb = function (p, q, t) {
+ if (t < 0) t += 1;
+ if (t > 1) t -= 1;
+ if (t < 1 / 6) return p + (q - p) * 6 * t;
+ if (t < 1 / 2) return q;
+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
+ return p;
+ };
+
+ var q = l < 0.5 ? l * (1 + s) : l + s - l * s;
+ var p = 2 * l - q;
+
+ r = hue2rgb(p, q, h + 1 / 3);
+ g = hue2rgb(p, q, h);
+ b = hue2rgb(p, q, h - 1 / 3);
}
- window.state.prevHeight = currentHeight;
- window.state.prevWidth = currentWidth;
- window.state.isMobileView = currentWidth <= 1200;
- });
+ return [r * 255, g * 255, b * 255];
+ }
+ function rgbToHex(r, g, b) {
+ var toHex = function (c) {
+ var hex = Math.round(c).toString(16);
+ return hex.length === 1 ? "0" + hex : hex;
+ };
+ return "#" + toHex(r) + toHex(g) + toHex(b);
+ }
+
+ /**
+ * Ref - https://github.com/onury/invert-color/blob/master/lib/cjs/invert.js
+ */
+ function padz(str, len) {
+ if (len === void 0) {
+ len = 2;
+ }
+ return (new Array(len).join("0") + str).slice(-len);
+ }
+ function hexToRgbArray(hex) {
+ if (hex.slice(0, 1) === "#") hex = hex.slice(1);
+ var RE_HEX = /^(?:[0-9a-f]{3}){1,2}$/i;
+ if (!RE_HEX.test(hex))
+ throw new Error('Invalid HEX color: "' + hex + '"');
+ if (hex.length === 3) {
+ hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
+ }
+ return [
+ parseInt(hex.slice(0, 2), 16),
+ parseInt(hex.slice(2, 4), 16),
+ parseInt(hex.slice(4, 6), 16),
+ ];
+ }
+ function toRgbArray(c) {
+ if (!c) throw new Error("Invalid color value");
+ if (Array.isArray(c)) return c;
+ return typeof c === "string" ? hexToRgbArray(c) : [c.r, c.g, c.b];
+ }
+ function getLuminance(c) {
+ var i, x;
+ var a = [];
+ for (i = 0; i < c.length; i++) {
+ x = c[i] / 255;
+ a[i] = x <= 0.03928 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4);
+ }
+ return 0.2126 * a[0] + 0.7152 * a[1] + 0.0722 * a[2];
+ }
+ function invertToBW(color, bw, asArr) {
+ var DEFAULT_BW = {
+ black: "#090302",
+ white: "#FFFFFC",
+ threshold: Math.sqrt(1.05 * 0.05) - 0.05,
+ };
+ var options =
+ bw === true ? DEFAULT_BW : Object.assign({}, DEFAULT_BW, bw);
+ return getLuminance(color) > options.threshold
+ ? asArr
+ ? hexToRgbArray(options.black)
+ : options.black
+ : asArr
+ ? hexToRgbArray(options.white)
+ : options.white;
+ }
+ function invert(color, bw) {
+ if (bw === void 0) {
+ bw = false;
+ }
+ color = toRgbArray(color);
+ if (bw) return invertToBW(color, bw);
+ return (
+ "#" +
+ color
+ .map(function (c) {
+ return padz((255 - c).toString(16));
+ })
+ .join("")
+ );
+ }
</script>
+ {{ hyperloader_sdk_link }}
</body>
</html>
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index aaecd86627c..39bc54fa157 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -21,7 +21,10 @@ use common_utils::{
ext_traits::{AsyncExt, StringExt, ValueExt},
generate_id,
};
-use diesel_models::{encryption::Encryption, enums as storage_enums, payment_method};
+use diesel_models::{
+ business_profile::BusinessProfile, encryption::Encryption, enums as storage_enums,
+ payment_method,
+};
use error_stack::{report, IntoReport, ResultExt};
use masking::Secret;
use router_env::{instrument, tracing};
@@ -44,6 +47,7 @@ use crate::{
helpers,
routing::{self, SessionFlowRoutingInput},
},
+ utils as core_utils,
},
db, logger,
pii::prelude::*,
@@ -1077,6 +1081,12 @@ pub async fn list_payment_methods(
})
.await
.transpose()?;
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ profile_id.as_ref(),
+ &merchant_account.merchant_id,
+ )
+ .await?;
// filter out connectors based on the business country
let filtered_mcas = helpers::filter_mca_based_on_business_profile(all_mcas, profile_id);
@@ -1690,13 +1700,18 @@ pub async fn list_payment_methods(
payment_method_types: bank_transfer_payment_method_types,
});
}
-
let merchant_surcharge_configs =
- if let Some((attempt, payment_intent)) = payment_attempt.as_ref().zip(payment_intent) {
+ if let Some((payment_attempt, payment_intent, business_profile)) = payment_attempt
+ .as_ref()
+ .zip(payment_intent)
+ .zip(business_profile)
+ .map(|((pa, pi), bp)| (pa, pi, bp))
+ {
Box::pin(call_surcharge_decision_management(
state,
&merchant_account,
- attempt,
+ &business_profile,
+ payment_attempt,
payment_intent,
billing_address,
&mut payment_method_responses,
@@ -1705,7 +1720,6 @@ pub async fn list_payment_methods(
} else {
api_surcharge_decision_configs::MerchantSurchargeConfigs::default()
};
-
Ok(services::ApplicationResponse::Json(
api::PaymentMethodListResponse {
redirect_url: merchant_account.return_url,
@@ -1747,6 +1761,7 @@ pub async fn list_payment_methods(
pub async fn call_surcharge_decision_management(
state: routes::AppState,
merchant_account: &domain::MerchantAccount,
+ business_profile: &BusinessProfile,
payment_attempt: &storage::PaymentAttempt,
payment_intent: storage::PaymentIntent,
billing_address: Option<domain::Address>,
@@ -1777,7 +1792,7 @@ pub async fn call_surcharge_decision_management(
.attach_printable("error performing surcharge decision operation")?;
if !surcharge_results.is_empty_result() {
surcharge_results
- .persist_individual_surcharge_details_in_redis(&state, merchant_account)
+ .persist_individual_surcharge_details_in_redis(&state, business_profile)
.await?;
let _ = state
.store
@@ -1800,6 +1815,7 @@ pub async fn call_surcharge_decision_management(
pub async fn call_surcharge_decision_management_for_saved_card(
state: &routes::AppState,
merchant_account: &domain::MerchantAccount,
+ business_profile: &BusinessProfile,
payment_attempt: &storage::PaymentAttempt,
payment_intent: storage::PaymentIntent,
customer_payment_method_response: &mut api::CustomerPaymentMethodsListResponse,
@@ -1827,7 +1843,7 @@ pub async fn call_surcharge_decision_management_for_saved_card(
.attach_printable("error performing surcharge decision operation")?;
if !surcharge_results.is_empty_result() {
surcharge_results
- .persist_individual_surcharge_details_in_redis(state, merchant_account)
+ .persist_individual_surcharge_details_in_redis(state, business_profile)
.await?;
let _ = state
.store
@@ -2536,10 +2552,38 @@ pub async fn list_customer_payment_method(
.await
.transpose()?;
- if let Some((payment_attempt, payment_intent)) = payment_attempt.zip(payment_intent) {
+ let profile_id = payment_intent
+ .as_ref()
+ .async_map(|payment_intent| async {
+ crate::core::utils::get_profile_id_from_business_details(
+ payment_intent.business_country,
+ payment_intent.business_label.as_ref(),
+ &merchant_account,
+ payment_intent.profile_id.as_ref(),
+ db,
+ false,
+ )
+ .await
+ .attach_printable("Could not find profile id from business details")
+ })
+ .await
+ .transpose()?;
+ let business_profile = core_utils::validate_and_get_business_profile(
+ db,
+ profile_id.as_ref(),
+ &merchant_account.merchant_id,
+ )
+ .await?;
+
+ if let Some((payment_attempt, payment_intent, business_profile)) = payment_attempt
+ .zip(payment_intent)
+ .zip(business_profile)
+ .map(|((pa, pi), bp)| (pa, pi, bp))
+ {
call_surcharge_decision_management_for_saved_card(
state,
&merchant_account,
+ &business_profile,
&payment_attempt,
payment_intent,
&mut response,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 62d66926efa..04e947d36e4 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -337,6 +337,7 @@ where
call_surcharge_decision_management_for_session_flow(
state,
&merchant_account,
+ &business_profile,
&mut payment_data,
&connectors,
)
@@ -570,6 +571,7 @@ pub fn get_connector_data(
pub async fn call_surcharge_decision_management_for_session_flow<O>(
state: &AppState,
merchant_account: &domain::MerchantAccount,
+ business_profile: &diesel_models::business_profile::BusinessProfile,
payment_data: &mut PaymentData<O>,
session_connector_data: &[api::SessionConnectorData],
) -> RouterResult<Option<api::SessionSurchargeDetails>>
@@ -615,7 +617,7 @@ where
.attach_printable("error performing surcharge decision operation")?;
surcharge_results
- .persist_individual_surcharge_details_in_redis(state, merchant_account)
+ .persist_individual_surcharge_details_in_redis(state, business_profile)
.await?;
Ok(if surcharge_results.is_empty_result() {
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 08e2e5dab1a..29e59a1af7f 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -23,7 +23,6 @@ use openssl::{
symm::{decrypt_aead, Cipher},
};
use router_env::{instrument, logger, tracing};
-use time::Duration;
use uuid::Uuid;
use x509_parser::parse_x509_certificate;
@@ -2377,24 +2376,23 @@ pub fn generate_mandate(
pub fn authenticate_client_secret(
request_client_secret: Option<&String>,
payment_intent: &PaymentIntent,
- merchant_intent_fulfillment_time: Option<i64>,
) -> Result<(), errors::ApiErrorResponse> {
match (request_client_secret, &payment_intent.client_secret) {
(Some(req_cs), Some(pi_cs)) => {
if req_cs != pi_cs {
Err(errors::ApiErrorResponse::ClientSecretInvalid)
} else {
- //This is done to check whether the merchant_account's intent fulfillment time has expired or not
- let payment_intent_fulfillment_deadline =
- payment_intent.created_at.saturating_add(Duration::seconds(
- merchant_intent_fulfillment_time
- .unwrap_or(consts::DEFAULT_FULFILLMENT_TIME),
- ));
let current_timestamp = common_utils::date_time::now();
- fp_utils::when(
- current_timestamp > payment_intent_fulfillment_deadline,
- || Err(errors::ApiErrorResponse::ClientSecretExpired),
- )
+
+ let session_expiry = payment_intent.session_expiry.unwrap_or(
+ payment_intent
+ .created_at
+ .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
+ );
+
+ fp_utils::when(current_timestamp > session_expiry, || {
+ Err(errors::ApiErrorResponse::ClientSecretExpired)
+ })
}
}
// If there is no client in payment intent, then it has expired
@@ -2403,26 +2401,6 @@ pub fn authenticate_client_secret(
}
}
-pub async fn get_merchant_fullfillment_time(
- payment_link_id: Option<String>,
- intent_fulfillment_time: Option<i64>,
- db: &dyn StorageInterface,
-) -> RouterResult<Option<i64>> {
- if let Some(payment_link_id) = payment_link_id {
- let payment_link_db = db
- .find_payment_link_by_payment_link_id(&payment_link_id)
- .await
- .to_not_found_response(errors::ApiErrorResponse::PaymentLinkNotFound)?;
-
- let curr_time = common_utils::date_time::now();
- Ok(payment_link_db
- .fulfilment_time
- .map(|merchant_expiry_time| (merchant_expiry_time - curr_time).whole_seconds()))
- } else {
- Ok(intent_fulfillment_time)
- }
-}
-
pub(crate) fn validate_payment_status_against_allowed_statuses(
intent_status: &storage_enums::IntentStatus,
allowed_statuses: &[storage_enums::IntentStatus],
@@ -2495,14 +2473,7 @@ pub async fn verify_payment_intent_time_and_client_secret(
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
- let intent_fulfillment_time = get_merchant_fullfillment_time(
- payment_intent.payment_link_id.clone(),
- merchant_account.intent_fulfillment_time,
- db,
- )
- .await?;
-
- authenticate_client_secret(Some(&cs), &payment_intent, intent_fulfillment_time)?;
+ authenticate_client_secret(Some(&cs), &payment_intent)?;
Ok(payment_intent)
})
.await
@@ -2634,15 +2605,14 @@ mod tests {
),
incremental_authorization_allowed: None,
authorization_count: None,
+ session_expiry: Some(
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
+ ),
};
let req_cs = Some("1".to_string());
- let merchant_fulfillment_time = Some(900);
- assert!(authenticate_client_secret(
- req_cs.as_ref(),
- &payment_intent,
- merchant_fulfillment_time,
- )
- .is_ok()); // Check if the result is an Ok variant
+ assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok());
+ // Check if the result is an Ok variant
}
#[test]
@@ -2664,7 +2634,7 @@ mod tests {
billing_address_id: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
- created_at: common_utils::date_time::now().saturating_sub(Duration::seconds(20)),
+ created_at: common_utils::date_time::now().saturating_sub(time::Duration::seconds(20)),
modified_at: common_utils::date_time::now(),
last_synced: None,
setup_future_usage: None,
@@ -2689,15 +2659,13 @@ mod tests {
),
incremental_authorization_allowed: None,
authorization_count: None,
+ session_expiry: Some(
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
+ ),
};
let req_cs = Some("1".to_string());
- let merchant_fulfillment_time = Some(10);
- assert!(authenticate_client_secret(
- req_cs.as_ref(),
- &payment_intent,
- merchant_fulfillment_time,
- )
- .is_err())
+ assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err())
}
#[test]
@@ -2719,7 +2687,7 @@ mod tests {
billing_address_id: None,
statement_descriptor_name: None,
statement_descriptor_suffix: None,
- created_at: common_utils::date_time::now().saturating_sub(Duration::seconds(20)),
+ created_at: common_utils::date_time::now().saturating_sub(time::Duration::seconds(20)),
modified_at: common_utils::date_time::now(),
last_synced: None,
setup_future_usage: None,
@@ -2744,15 +2712,13 @@ mod tests {
),
incremental_authorization_allowed: None,
authorization_count: None,
+ session_expiry: Some(
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY)),
+ ),
};
let req_cs = Some("1".to_string());
- let merchant_fulfillment_time = Some(10);
- assert!(authenticate_client_secret(
- req_cs.as_ref(),
- &payment_intent,
- merchant_fulfillment_time,
- )
- .is_err())
+ assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err())
}
}
@@ -3732,22 +3698,11 @@ pub fn get_key_params_for_surcharge_details(
}
pub fn validate_payment_link_request(
- payment_link_object: &api_models::payments::PaymentLinkObject,
confirm: Option<bool>,
- order_details: Option<Vec<api_models::payments::OrderDetailsWithAmount>>,
) -> Result<(), errors::ApiErrorResponse> {
if let Some(cnf) = confirm {
if !cnf {
- let current_time = Some(common_utils::date_time::now());
- if current_time > payment_link_object.link_expiry {
- return Err(errors::ApiErrorResponse::InvalidRequestData {
- message: "link_expiry time cannot be less than current time".to_string(),
- });
- } else if order_details.is_none() {
- return Err(errors::ApiErrorResponse::InvalidRequestData {
- message: "cannot create payment link without order details".to_string(),
- });
- }
+ return Ok(());
} else {
return Err(errors::ApiErrorResponse::InvalidRequestData {
message: "cannot confirm a payment while creating a payment link".to_string(),
@@ -3818,3 +3773,14 @@ pub fn validate_order_details_amount(
Ok(())
}
}
+
+// This function validates the client secret expiry set by the merchant in the request
+pub fn validate_session_expiry(session_expiry: u32) -> Result<(), errors::ApiErrorResponse> {
+ if !(consts::MIN_SESSION_EXPIRY..=consts::MAX_SESSION_EXPIRY).contains(&session_expiry) {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "session_expiry should be between 60(1 min) to 7890000(3 months).".to_string(),
+ })
+ } else {
+ Ok(())
+ }
+}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 58983f264c7..6a50abc5432 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -50,7 +50,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
key_store: &domain::MerchantKeyStore,
auth_flow: services::AuthFlow,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, Ctx>> {
- let db = &*state.store;
let merchant_id = &merchant_account.merchant_id;
let storage_scheme = merchant_account.storage_scheme;
let (currency, amount);
@@ -122,18 +121,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
"confirm",
)?;
- let intent_fulfillment_time = helpers::get_merchant_fullfillment_time(
- payment_intent.payment_link_id.clone(),
- merchant_account.intent_fulfillment_time,
- db,
- )
- .await?;
-
- helpers::authenticate_client_secret(
- request.client_secret.as_ref(),
- &payment_intent,
- intent_fulfillment_time,
- )?;
+ helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
let customer_details = helpers::get_customer_details_from_request(request);
@@ -161,7 +149,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.await
});
- let store = state.clone().store;
+ let store = state.store.clone();
+
let m_payment_id = payment_intent.payment_id.clone();
let m_merchant_id = merchant_id.clone();
@@ -774,6 +763,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
let m_metadata = metadata.clone();
let m_db = state.clone().store;
let m_storage_scheme = storage_scheme.to_string();
+ let session_expiry = m_payment_data_payment_intent.session_expiry;
let payment_intent_fut = tokio::spawn(
async move {
@@ -797,6 +787,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
metadata: m_metadata,
payment_confirm_source: header_payload.payment_confirm_source,
updated_by: m_storage_scheme,
+ session_expiry,
},
storage_scheme,
)
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 798678e64df..6f4f10e0ab3 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -6,14 +6,17 @@ use common_utils::ext_traits::{AsyncExt, Encode, ValueExt};
use data_models::{mandates::MandateData, payments::payment_attempt::PaymentAttempt};
use diesel_models::ephemeral_key;
use error_stack::{self, ResultExt};
+use masking::PeekInterface;
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
+use time::PrimitiveDateTime;
use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest};
use crate::{
consts,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
+ payment_link,
payment_methods::PaymentMethodRetrieve,
payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
@@ -66,31 +69,36 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
- let payment_link_data = if let Some(payment_link_object) = &request.payment_link_object {
- create_payment_link(
- request,
- payment_link_object.clone(),
- merchant_id.clone(),
- payment_id.clone(),
- db,
- state,
- amount,
- request.description.clone(),
- )
- .await?
- } else {
- None
- };
-
helpers::validate_business_details(
request.business_country,
request.business_label.as_ref(),
merchant_account,
)?;
+ // If profile id is not passed, get it from the business_country and business_label
+ let profile_id = core_utils::get_profile_id_from_business_details(
+ request.business_country,
+ request.business_label.as_ref(),
+ merchant_account,
+ request.profile_id.as_ref(),
+ &*state.store,
+ true,
+ )
+ .await?;
+
// Validate whether profile_id passed in request is valid and is linked to the merchant
- core_utils::validate_and_get_business_profile(db, request.profile_id.as_ref(), merchant_id)
- .await?;
+ let business_profile = if let Some(business_profile) =
+ core_utils::validate_and_get_business_profile(db, Some(&profile_id), merchant_id)
+ .await?
+ {
+ business_profile
+ } else {
+ db.find_business_profile_by_profile_id(&profile_id)
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
+ id: profile_id.to_string(),
+ })?
+ };
let (
token,
@@ -154,6 +162,52 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
utils::get_payment_attempt_id(payment_id.clone(), 1)
};
+ let session_expiry =
+ common_utils::date_time::now().saturating_add(time::Duration::seconds(
+ request.session_expiry.map(i64::from).unwrap_or(
+ business_profile
+ .session_expiry
+ .unwrap_or(consts::DEFAULT_SESSION_EXPIRY),
+ ),
+ ));
+
+ let payment_link_data = if let Some(payment_link_create) = request.payment_link {
+ if payment_link_create {
+ let merchant_name = merchant_account
+ .merchant_name
+ .clone()
+ .map(|merchant_name| merchant_name.into_inner().peek().to_owned())
+ .unwrap_or_default();
+
+ let default_domain_name = state.conf.server.base_url.clone();
+
+ let (payment_link_config, domain_name) =
+ payment_link::get_payment_link_config_based_on_priority(
+ request.payment_link_config.clone(),
+ business_profile.payment_link_config.clone(),
+ merchant_name,
+ default_domain_name,
+ )?;
+ create_payment_link(
+ request,
+ payment_link_config,
+ merchant_id.clone(),
+ payment_id.clone(),
+ db,
+ amount,
+ request.description.clone(),
+ profile_id.clone(),
+ domain_name,
+ session_expiry,
+ )
+ .await?
+ } else {
+ None
+ }
+ } else {
+ None
+ };
+
let payment_intent_new = Self::make_payment_intent(
&payment_id,
merchant_account,
@@ -163,7 +217,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
payment_link_data.clone(),
billing_address.clone().map(|x| x.address_id),
attempt_id,
- state,
+ profile_id,
+ session_expiry,
)
.await?;
@@ -200,20 +255,6 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
payment_id: payment_id.clone(),
})?;
- 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(profile_id)
- .await
- .to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
- id: profile_id.to_string(),
- })?;
-
let mandate_id = request
.mandate_id
.as_ref()
@@ -396,7 +437,7 @@ impl<F: Clone + Send, Ctx: PaymentMethodRetrieve> Domain<F, api::PaymentsRequest
_state: &'a AppState,
_payment_attempt: &PaymentAttempt,
_requeue: bool,
- _schedule_time: Option<time::PrimitiveDateTime>,
+ _schedule_time: Option<PrimitiveDateTime>,
) -> CustomResult<(), errors::ApiErrorResponse> {
Ok(())
}
@@ -531,15 +572,16 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
operations::ValidateResult<'a>,
)> {
helpers::validate_customer_details_in_request(request)?;
-
- if let Some(payment_link_object) = &request.payment_link_object {
- helpers::validate_payment_link_request(
- payment_link_object,
- request.confirm,
- request.order_details.clone(),
- )?;
+ if let Some(session_expiry) = &request.session_expiry {
+ helpers::validate_session_expiry(session_expiry.to_owned())?;
}
+ if let Some(payment_link) = &request.payment_link {
+ if *payment_link {
+ helpers::validate_payment_link_request(request.confirm)?;
+ }
+ };
+
let payment_id = request.payment_id.clone().ok_or(error_stack::report!(
errors::ApiErrorResponse::PaymentNotFound
))?;
@@ -697,7 +739,8 @@ impl PaymentCreate {
payment_link_data: Option<api_models::payments::PaymentLinkResponse>,
billing_address_id: Option<String>,
active_attempt_id: String,
- state: &AppState,
+ profile_id: String,
+ session_expiry: PrimitiveDateTime,
) -> RouterResult<storage::PaymentIntentNew> {
let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now());
let status =
@@ -711,17 +754,6 @@ impl PaymentCreate {
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert order details to value")?;
- // If profile id is not passed, get it from the business_country and business_label
- let profile_id = core_utils::get_profile_id_from_business_details(
- request.business_country,
- request.business_label.as_ref(),
- merchant_account,
- request.profile_id.as_ref(),
- &*state.store,
- true,
- )
- .await?;
-
let allowed_payment_method_types = request
.get_allowed_payment_method_types_as_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -784,6 +816,7 @@ impl PaymentCreate {
request_incremental_authorization,
incremental_authorization_allowed: None,
authorization_count: None,
+ session_expiry: Some(session_expiry),
})
}
@@ -825,32 +858,31 @@ pub fn payments_create_request_validation(
#[allow(clippy::too_many_arguments)]
async fn create_payment_link(
request: &api::PaymentsRequest,
- payment_link_object: api_models::payments::PaymentLinkObject,
+ payment_link_config: api_models::admin::PaymentLinkConfig,
merchant_id: String,
payment_id: String,
db: &dyn StorageInterface,
- state: &AppState,
amount: api::Amount,
description: Option<String>,
+ profile_id: String,
+ domain_name: String,
+ session_expiry: PrimitiveDateTime,
) -> RouterResult<Option<api_models::payments::PaymentLinkResponse>> {
let created_at @ last_modified_at = Some(common_utils::date_time::now());
- let domain = if let Some(domain_name) = payment_link_object.merchant_custom_domain_name {
- format!("https://{domain_name}")
- } else {
- state.conf.server.base_url.clone()
- };
-
let payment_link_id = utils::generate_id(consts::ID_LENGTH, "plink");
let payment_link = format!(
"{}/payment_link/{}/{}",
- domain,
+ domain_name,
merchant_id.clone(),
payment_id.clone()
);
- let payment_link_config = payment_link_object.payment_link_config.map(|pl_config|{
- common_utils::ext_traits::Encode::<api_models::admin::PaymentLinkConfig>::encode_to_value(&pl_config)
- }).transpose().change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "payment_link_config" })?;
+ let payment_link_config_encoded_value = common_utils::ext_traits::Encode::<
+ api_models::admin::PaymentLinkConfig,
+ >::encode_to_value(&payment_link_config)
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "payment_link_config",
+ })?;
let payment_link_req = storage::PaymentLinkNew {
payment_link_id: payment_link_id.clone(),
@@ -861,10 +893,11 @@ async fn create_payment_link(
currency: request.currency,
created_at,
last_modified_at,
- fulfilment_time: payment_link_object.link_expiry,
+ fulfilment_time: Some(session_expiry),
+ custom_merchant_name: Some(payment_link_config.seller_name),
description,
- payment_link_config,
- custom_merchant_name: payment_link_object.custom_merchant_name,
+ payment_link_config: Some(payment_link_config_encoded_value),
+ profile_id: Some(profile_id),
};
let payment_link_db = db
.insert_payment_link(payment_link_req)
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 6f7dcd6c11a..49fad8f078d 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -66,18 +66,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
"create a session token for",
)?;
- let intent_fulfillment_time = helpers::get_merchant_fullfillment_time(
- payment_intent.payment_link_id.clone(),
- merchant_account.intent_fulfillment_time,
- db,
- )
- .await?;
-
- helpers::authenticate_client_secret(
- Some(&request.client_secret),
- &payment_intent,
- intent_fulfillment_time,
- )?;
+ helpers::authenticate_client_secret(Some(&request.client_secret), &payment_intent)?;
let mut payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 8896e4e43ef..ea05cdcb745 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -66,17 +66,9 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
"update",
)?;
- let intent_fulfillment_time = helpers::get_merchant_fullfillment_time(
- payment_intent.payment_link_id.clone(),
- merchant_account.intent_fulfillment_time,
- db,
- )
- .await?;
-
helpers::authenticate_client_secret(
payment_intent.client_secret.as_ref(),
&payment_intent,
- intent_fulfillment_time,
)?;
payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index c5311ce3d03..e5db177c83b 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -229,17 +229,7 @@ async fn get_tracker_for_sync<
)
.await?;
- let intent_fulfillment_time = helpers::get_merchant_fullfillment_time(
- payment_intent.payment_link_id.clone(),
- merchant_account.intent_fulfillment_time,
- db,
- )
- .await?;
- helpers::authenticate_client_secret(
- request.client_secret.as_ref(),
- &payment_intent,
- intent_fulfillment_time,
- )?;
+ helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
let payment_id_str = payment_attempt.payment_id.clone();
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 153ded14f4b..5019a662338 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -86,18 +86,7 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve>
"update",
)?;
- let intent_fulfillment_time = helpers::get_merchant_fullfillment_time(
- payment_intent.payment_link_id.clone(),
- merchant_account.intent_fulfillment_time,
- db,
- )
- .await?;
-
- helpers::authenticate_client_secret(
- request.client_secret.as_ref(),
- &payment_intent,
- intent_fulfillment_time,
- )?;
+ helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?;
let (
token,
payment_method,
@@ -595,11 +584,12 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
.clone();
let order_details = payment_data.payment_intent.order_details.clone();
let metadata = payment_data.payment_intent.metadata.clone();
+ let session_expiry = payment_data.payment_intent.session_expiry;
payment_data.payment_intent = state
.store
.update_payment_intent(
- payment_data.payment_intent,
+ payment_data.payment_intent.clone(),
storage::PaymentIntentUpdate::Update {
amount: payment_data.amount.into(),
currency: payment_data.currency,
@@ -618,6 +608,7 @@ impl<F: Clone, Ctx: PaymentMethodRetrieve>
metadata,
payment_confirm_source: None,
updated_by: storage_scheme.to_string(),
+ session_expiry,
},
storage_scheme,
)
@@ -646,6 +637,9 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
operations::ValidateResult<'a>,
)> {
helpers::validate_customer_details_in_request(request)?;
+ if let Some(session_expiry) = &request.session_expiry {
+ helpers::validate_session_expiry(session_expiry.to_owned())?;
+ }
let payment_id = request
.payment_id
.clone()
diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs
index 00160db9855..41a8850ab3d 100644
--- a/crates/router/src/core/payments/types.rs
+++ b/crates/router/src/core/payments/types.rs
@@ -3,6 +3,7 @@ use std::{collections::HashMap, num::TryFromIntError};
use api_models::{payment_methods::SurchargeDetailsResponse, payments::RequestSurchargeDetails};
use common_utils::{consts, errors::CustomResult, ext_traits::Encode, types as common_types};
use data_models::payments::payment_attempt::PaymentAttempt;
+use diesel_models::business_profile::BusinessProfile;
use error_stack::{IntoReport, ResultExt};
use redis_interface::errors::RedisError;
use router_env::{instrument, tracing};
@@ -12,7 +13,6 @@ use crate::{
core::errors::{self, RouterResult},
routes::AppState,
types::{
- domain,
storage::{self, enums as storage_enums},
transformers::ForeignTryFrom,
},
@@ -322,7 +322,7 @@ impl SurchargeMetadata {
pub async fn persist_individual_surcharge_details_in_redis(
&self,
state: &AppState,
- merchant_account: &domain::MerchantAccount,
+ business_profile: &BusinessProfile,
) -> RouterResult<()> {
if !self.is_empty_result() {
let redis_conn = state
@@ -341,7 +341,7 @@ impl SurchargeMetadata {
.attach_printable("Failed to encode to string of json")?,
));
}
- let intent_fulfillment_time = merchant_account
+ let intent_fulfillment_time = business_profile
.intent_fulfillment_time
.unwrap_or(router_consts::DEFAULT_FULFILLMENT_TIME);
redis_conn
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 6eec39f53bc..c86e527b00d 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -255,6 +255,8 @@ pub async fn update_business_profile_active_algorithm_ref(
applepay_verified_domains: None,
modified_at: None,
is_recon_enabled: None,
+ payment_link_config: None,
+ session_expiry: None,
};
db.update_business_profile_by_profile_id(current_business_profile, business_profile_update)
.await
diff --git a/crates/router/src/db/payment_link.rs b/crates/router/src/db/payment_link.rs
index 5dc9871e707..a56f9dcce2e 100644
--- a/crates/router/src/db/payment_link.rs
+++ b/crates/router/src/db/payment_link.rs
@@ -42,10 +42,10 @@ impl PaymentLinkInterface for Store {
async fn insert_payment_link(
&self,
- payment_link_object: storage::PaymentLinkNew,
+ payment_link_config: storage::PaymentLinkNew,
) -> CustomResult<storage::PaymentLink, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
- payment_link_object
+ payment_link_config
.insert(&conn)
.await
.map_err(Into::into)
diff --git a/crates/router/src/macros.rs b/crates/router/src/macros.rs
index efe71e49bb0..e6c9dba7d6e 100644
--- a/crates/router/src/macros.rs
+++ b/crates/router/src/macros.rs
@@ -1 +1,4 @@
-pub use common_utils::{collect_missing_value_keys, newtype};
+pub use common_utils::{
+ async_spawn, collect_missing_value_keys, fallback_reverse_lookup_not_found, newtype,
+ newtype_impl,
+};
diff --git a/crates/router/src/openapi.rs b/crates/router/src/openapi.rs
index c7d3b11abbc..79b38e03f31 100644
--- a/crates/router/src/openapi.rs
+++ b/crates/router/src/openapi.rs
@@ -186,8 +186,9 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::admin::MerchantConnectorDetailsWrap,
api_models::admin::MerchantConnectorDetails,
api_models::admin::MerchantConnectorWebhookDetails,
+ api_models::admin::BusinessPaymentLinkConfig,
+ api_models::admin::PaymentLinkConfigRequest,
api_models::admin::PaymentLinkConfig,
- api_models::admin::PaymentLinkColorSchema,
api_models::disputes::DisputeResponse,
api_models::disputes::DisputeResponsePaymentsRetrieve,
api_models::gsm::GsmCreateRequest,
@@ -318,6 +319,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentAttemptResponse,
api_models::payments::CaptureResponse,
api_models::payments::IncrementalAuthorizationResponse,
+ api_models::payments::PaymentCreatePaymentLinkConfig,
api_models::payment_methods::RequiredFieldInfo,
api_models::payment_methods::MaskedBankDetails,
api_models::payment_methods::SurchargeDetailsResponse,
@@ -368,7 +370,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::PaymentLinkResponse,
api_models::payments::RetrievePaymentLinkResponse,
api_models::payments::PaymentLinkInitiateRequest,
- api_models::payments::PaymentLinkObject,
+ api_models::payments::PaymentLinkStatus
)),
modifiers(&SecurityAddon)
)]
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index ba3607fb7dc..54df0285512 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1631,7 +1631,7 @@ pub fn build_payment_link_html(
}
fn get_hyper_loader_sdk(sdk_url: &str) -> String {
- format!("<script src=\"{sdk_url}\"></script>")
+ format!("<script src=\"{sdk_url}\" onload=\"initializeSDK()\"></script>")
}
#[cfg(test)]
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index fe99d084223..487cea88d15 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -14,6 +14,7 @@ use masking::Secret;
use crate::{
core::errors,
types::{domain, storage, transformers::ForeignTryFrom},
+ utils::{self},
};
impl TryFrom<domain::MerchantAccount> for MerchantAccountResponse {
@@ -46,7 +47,6 @@ impl TryFrom<domain::MerchantAccount> for MerchantAccountResponse {
is_recon_enabled: item.is_recon_enabled,
default_profile: item.default_profile,
recon_status: item.recon_status,
- payment_link_config: item.payment_link_config,
})
}
}
@@ -72,6 +72,8 @@ impl ForeignTryFrom<storage::business_profile::BusinessProfile> for BusinessProf
frm_routing_algorithm: item.frm_routing_algorithm,
payout_routing_algorithm: item.payout_routing_algorithm,
applepay_verified_domains: item.applepay_verified_domains,
+ payment_link_config: item.payment_link_config,
+ session_expiry: item.session_expiry,
})
}
}
@@ -105,6 +107,18 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)>
.or(merchant_account.payment_response_hash_key)
.unwrap_or(common_utils::crypto::generate_cryptographically_secure_random_string(64));
+ let payment_link_config_value = request
+ .payment_link_config
+ .map(|pl_config| {
+ utils::Encode::<api_models::admin::BusinessPaymentLinkConfig>::encode_to_value(
+ &pl_config,
+ )
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "payment_link_config_value",
+ })
+ })
+ .transpose()?;
+
Ok(Self {
profile_id,
merchant_id: merchant_account.merchant_id,
@@ -140,6 +154,11 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)>
.or(merchant_account.payout_routing_algorithm),
is_recon_enabled: merchant_account.is_recon_enabled,
applepay_verified_domains: request.applepay_verified_domains,
+ payment_link_config: payment_link_config_value,
+ session_expiry: request
+ .session_expiry
+ .map(i64::from)
+ .or(Some(common_utils::consts::DEFAULT_SESSION_EXPIRY)),
})
}
}
diff --git a/crates/router/src/types/api/payment_link.rs b/crates/router/src/types/api/payment_link.rs
index e56af6b4aec..d0ce8c043ba 100644
--- a/crates/router/src/types/api/payment_link.rs
+++ b/crates/router/src/types/api/payment_link.rs
@@ -1,6 +1,7 @@
pub use api_models::payments::RetrievePaymentLinkResponse;
use crate::{
+ consts::DEFAULT_SESSION_EXPIRY,
core::{errors::RouterResult, payment_link},
types::storage::{self},
};
@@ -13,7 +14,11 @@ pub(crate) trait PaymentLinkResponseExt: Sized {
#[async_trait::async_trait]
impl PaymentLinkResponseExt for RetrievePaymentLinkResponse {
async fn from_db_payment_link(payment_link: storage::PaymentLink) -> RouterResult<Self> {
- let status = payment_link::check_payment_link_status(payment_link.fulfilment_time);
+ let session_expiry = payment_link.fulfilment_time.unwrap_or_else(|| {
+ common_utils::date_time::now()
+ .saturating_add(time::Duration::seconds(DEFAULT_SESSION_EXPIRY))
+ });
+ let status = payment_link::check_payment_link_status(session_expiry);
Ok(Self {
link_to_pay: payment_link.link_to_pay,
payment_link_id: payment_link.payment_link_id,
@@ -21,7 +26,7 @@ impl PaymentLinkResponseExt for RetrievePaymentLinkResponse {
description: payment_link.description,
created_at: payment_link.created_at,
merchant_id: payment_link.merchant_id,
- link_expiry: payment_link.fulfilment_time,
+ expiry: payment_link.fulfilment_time,
currency: payment_link.currency,
status,
})
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index ce8350bd9eb..8f204814ec4 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -344,10 +344,8 @@ impl NewUserMerchant {
merchant_details: None,
routing_algorithm: None,
parent_merchant_id: None,
- payment_link_config: None,
sub_merchants_enabled: None,
frm_routing_algorithm: None,
- intent_fulfillment_time: None,
payout_routing_algorithm: None,
primary_business_details: None,
payment_response_hash_key: None,
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 5bd03fe833a..c3818caf051 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -943,19 +943,27 @@ impl
}
}
-impl ForeignFrom<(storage::PaymentLink, String)>
- for api_models::payments::RetrievePaymentLinkResponse
+impl
+ ForeignFrom<(
+ storage::PaymentLink,
+ api_models::payments::PaymentLinkStatus,
+ )> for api_models::payments::RetrievePaymentLinkResponse
{
- fn foreign_from((payment_link_object, status): (storage::PaymentLink, String)) -> Self {
+ fn foreign_from(
+ (payment_link_config, status): (
+ storage::PaymentLink,
+ api_models::payments::PaymentLinkStatus,
+ ),
+ ) -> Self {
Self {
- payment_link_id: payment_link_object.payment_link_id,
- merchant_id: payment_link_object.merchant_id,
- link_to_pay: payment_link_object.link_to_pay,
- amount: payment_link_object.amount,
- created_at: payment_link_object.created_at,
- link_expiry: payment_link_object.fulfilment_time,
- description: payment_link_object.description,
- currency: payment_link_object.currency,
+ payment_link_id: payment_link_config.payment_link_id,
+ merchant_id: payment_link_config.merchant_id,
+ link_to_pay: payment_link_config.link_to_pay,
+ amount: payment_link_config.amount,
+ created_at: payment_link_config.created_at,
+ expiry: payment_link_config.fulfilment_time,
+ description: payment_link_config.description,
+ currency: payment_link_config.currency,
status,
}
}
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index 5ce0818b82b..33f1e211534 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -146,6 +146,8 @@ pub async fn generate_sample_data(
common_utils::date_time::now() - time::Duration::days(7)
}),
);
+ let session_expiry =
+ created_at.saturating_add(time::Duration::seconds(consts::DEFAULT_SESSION_EXPIRY));
// After some set of payments sample data will have a failed attempt
let is_failed_payment =
@@ -197,6 +199,7 @@ pub async fn generate_sample_data(
request_incremental_authorization: Default::default(),
incremental_authorization_allowed: Default::default(),
authorization_count: Default::default(),
+ session_expiry: Some(session_expiry),
};
let payment_attempt = PaymentAttemptBatchNew {
attempt_id: attempt_id.clone(),
diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs
index 1da3df0bdef..ee8676106f1 100644
--- a/crates/storage_impl/src/mock_db/payment_intent.rs
+++ b/crates/storage_impl/src/mock_db/payment_intent.rs
@@ -109,6 +109,7 @@ impl PaymentIntentInterface for MockDb {
request_incremental_authorization: new.request_incremental_authorization,
incremental_authorization_allowed: new.incremental_authorization_allowed,
authorization_count: new.authorization_count,
+ session_expiry: new.session_expiry,
};
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 61229ca890c..07d70c9056b 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -101,6 +101,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
request_incremental_authorization: new.request_incremental_authorization,
incremental_authorization_allowed: new.incremental_authorization_allowed,
authorization_count: new.authorization_count,
+ session_expiry: new.session_expiry,
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
@@ -768,6 +769,7 @@ impl DataModelExt for PaymentIntentNew {
request_incremental_authorization: self.request_incremental_authorization,
incremental_authorization_allowed: self.incremental_authorization_allowed,
authorization_count: self.authorization_count,
+ session_expiry: self.session_expiry,
}
}
@@ -811,6 +813,7 @@ impl DataModelExt for PaymentIntentNew {
request_incremental_authorization: storage_model.request_incremental_authorization,
incremental_authorization_allowed: storage_model.incremental_authorization_allowed,
authorization_count: storage_model.authorization_count,
+ session_expiry: storage_model.session_expiry,
}
}
}
@@ -859,6 +862,7 @@ impl DataModelExt for PaymentIntent {
request_incremental_authorization: self.request_incremental_authorization,
incremental_authorization_allowed: self.incremental_authorization_allowed,
authorization_count: self.authorization_count,
+ session_expiry: self.session_expiry,
}
}
@@ -903,6 +907,7 @@ impl DataModelExt for PaymentIntent {
request_incremental_authorization: storage_model.request_incremental_authorization,
incremental_authorization_allowed: storage_model.incremental_authorization_allowed,
authorization_count: storage_model.authorization_count,
+ session_expiry: storage_model.session_expiry,
}
}
}
@@ -985,6 +990,7 @@ impl DataModelExt for PaymentIntentUpdate {
metadata,
payment_confirm_source,
updated_by,
+ session_expiry,
} => DieselPaymentIntentUpdate::Update {
amount,
currency,
@@ -1003,6 +1009,7 @@ impl DataModelExt for PaymentIntentUpdate {
metadata,
payment_confirm_source,
updated_by,
+ session_expiry,
},
Self::PaymentAttemptAndAttemptCountUpdate {
active_attempt_id,
diff --git a/migrations/2023-11-24-112541_add_payment_config_business_profile/down.sql b/migrations/2023-11-24-112541_add_payment_config_business_profile/down.sql
new file mode 100644
index 00000000000..16705c2bf56
--- /dev/null
+++ b/migrations/2023-11-24-112541_add_payment_config_business_profile/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE business_profile DROP COLUMN IF EXISTS payment_link_config;
\ No newline at end of file
diff --git a/migrations/2023-11-24-112541_add_payment_config_business_profile/up.sql b/migrations/2023-11-24-112541_add_payment_config_business_profile/up.sql
new file mode 100644
index 00000000000..19fbedccbbf
--- /dev/null
+++ b/migrations/2023-11-24-112541_add_payment_config_business_profile/up.sql
@@ -0,0 +1,3 @@
+-- Your SQL goes here
+ALTER TABLE business_profile
+ADD COLUMN IF NOT EXISTS payment_link_config JSONB DEFAULT NULL;
\ No newline at end of file
diff --git a/migrations/2023-11-24-115538_add_profile_id_payment_link/down.sql b/migrations/2023-11-24-115538_add_profile_id_payment_link/down.sql
new file mode 100644
index 00000000000..4fa87f5f931
--- /dev/null
+++ b/migrations/2023-11-24-115538_add_profile_id_payment_link/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_link DROP COLUMN profile_id;
\ No newline at end of file
diff --git a/migrations/2023-11-24-115538_add_profile_id_payment_link/up.sql b/migrations/2023-11-24-115538_add_profile_id_payment_link/up.sql
new file mode 100644
index 00000000000..b48346c763e
--- /dev/null
+++ b/migrations/2023-11-24-115538_add_profile_id_payment_link/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE payment_link ADD COLUMN IF NOT EXISTS profile_id VARCHAR(64) DEFAULT NULL;
\ No newline at end of file
diff --git a/migrations/2023-12-06-112810_add_intent_fullfilment_time_payment_intent/down.sql b/migrations/2023-12-06-112810_add_intent_fullfilment_time_payment_intent/down.sql
new file mode 100644
index 00000000000..2801a68c67e
--- /dev/null
+++ b/migrations/2023-12-06-112810_add_intent_fullfilment_time_payment_intent/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_intent DROP COLUMN IF EXISTS session_expiry;
\ No newline at end of file
diff --git a/migrations/2023-12-06-112810_add_intent_fullfilment_time_payment_intent/up.sql b/migrations/2023-12-06-112810_add_intent_fullfilment_time_payment_intent/up.sql
new file mode 100644
index 00000000000..f2ee81e847d
--- /dev/null
+++ b/migrations/2023-12-06-112810_add_intent_fullfilment_time_payment_intent/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS session_expiry TIMESTAMP DEFAULT NULL;
\ No newline at end of file
diff --git a/migrations/2023-12-27-104559_business_profile_add_session_expiry/down.sql b/migrations/2023-12-27-104559_business_profile_add_session_expiry/down.sql
new file mode 100644
index 00000000000..cdc7fe5b81c
--- /dev/null
+++ b/migrations/2023-12-27-104559_business_profile_add_session_expiry/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE business_profile DROP COLUMN IF EXISTS session_expiry;
\ No newline at end of file
diff --git a/migrations/2023-12-27-104559_business_profile_add_session_expiry/up.sql b/migrations/2023-12-27-104559_business_profile_add_session_expiry/up.sql
new file mode 100644
index 00000000000..462dfd234ab
--- /dev/null
+++ b/migrations/2023-12-27-104559_business_profile_add_session_expiry/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE business_profile ADD COLUMN IF NOT EXISTS session_expiry BIGINT DEFAULT NULL;
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 36cc0cbc012..bf373220fde 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -4059,6 +4059,22 @@
}
}
},
+ "BusinessPaymentLinkConfig": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkConfigRequest"
+ },
+ {
+ "type": "object",
+ "properties": {
+ "domain_name": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ }
+ ]
+ },
"CaptureMethod": {
"type": "string",
"enum": [
@@ -6914,26 +6930,10 @@
"description": "The frm routing algorithm to be used for routing payments to desired FRM's",
"nullable": true
},
- "intent_fulfillment_time": {
- "type": "integer",
- "format": "int32",
- "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins",
- "example": 900,
- "nullable": true,
- "minimum": 0
- },
"organization_id": {
"type": "string",
"description": "The id of the organization to which the merchant belongs to",
"nullable": true
- },
- "payment_link_config": {
- "allOf": [
- {
- "$ref": "#/components/schemas/PaymentLinkConfig"
- }
- ],
- "nullable": true
}
}
},
@@ -7107,9 +7107,6 @@
},
"recon_status": {
"$ref": "#/components/schemas/ReconStatus"
- },
- "payment_link_config": {
- "nullable": true
}
}
},
@@ -7230,21 +7227,11 @@
"description": "The frm routing algorithm to be used for routing payments to desired FRM's",
"nullable": true
},
- "intent_fulfillment_time": {
- "type": "integer",
- "format": "int32",
- "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins",
- "nullable": true,
- "minimum": 0
- },
"default_profile": {
"type": "string",
"description": "The default business profile that must be used for creating merchant accounts and payments\nTo unset this field, pass an empty string",
"nullable": true,
"maxLength": 64
- },
- "payment_link_config": {
- "nullable": true
}
}
},
@@ -8597,6 +8584,21 @@
}
}
},
+ "PaymentCreatePaymentLinkConfig": {
+ "allOf": [
+ {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/PaymentLinkConfigRequest"
+ }
+ ],
+ "nullable": true
+ },
+ {
+ "type": "object"
+ }
+ ]
+ },
"PaymentExperience": {
"type": "string",
"enum": [
@@ -8661,35 +8663,51 @@
}
]
},
- "PaymentLinkColorSchema": {
+ "PaymentLinkConfig": {
"type": "object",
+ "required": [
+ "theme",
+ "logo",
+ "seller_name"
+ ],
"properties": {
- "background_primary_color": {
+ "theme": {
"type": "string",
- "nullable": true
+ "description": "custom theme for the payment link"
},
- "sdk_theme": {
+ "logo": {
"type": "string",
- "nullable": true
+ "description": "merchant display logo"
+ },
+ "seller_name": {
+ "type": "string",
+ "description": "Custom merchant name for payment link"
}
}
},
- "PaymentLinkConfig": {
+ "PaymentLinkConfigRequest": {
"type": "object",
"properties": {
- "merchant_logo": {
+ "theme": {
"type": "string",
- "example": "https://i.imgur.com/RfxPFQo.png",
+ "description": "custom theme for the payment link",
+ "example": "#4E6ADD",
"nullable": true,
"maxLength": 255
},
- "color_scheme": {
- "allOf": [
- {
- "$ref": "#/components/schemas/PaymentLinkColorSchema"
- }
- ],
- "nullable": true
+ "logo": {
+ "type": "string",
+ "description": "merchant display logo",
+ "example": "https://i.pinimg.com/736x/4d/83/5c/4d835ca8aafbbb15f84d07d926fda473.jpg",
+ "nullable": true,
+ "maxLength": 255
+ },
+ "seller_name": {
+ "type": "string",
+ "description": "Custom merchant name for payment link",
+ "example": "hyperswitch",
+ "nullable": true,
+ "maxLength": 255
}
}
},
@@ -8708,31 +8726,6 @@
}
}
},
- "PaymentLinkObject": {
- "type": "object",
- "required": [
- "payment_link_config"
- ],
- "properties": {
- "link_expiry": {
- "type": "string",
- "format": "date-time",
- "nullable": true
- },
- "merchant_custom_domain_name": {
- "type": "string",
- "nullable": true
- },
- "payment_link_config": {
- "$ref": "#/components/schemas/PaymentLinkConfig"
- },
- "custom_merchant_name": {
- "type": "string",
- "description": "Custom merchant name for payment link",
- "nullable": true
- }
- }
- },
"PaymentLinkResponse": {
"type": "object",
"required": [
@@ -8748,6 +8741,13 @@
}
}
},
+ "PaymentLinkStatus": {
+ "type": "string",
+ "enum": [
+ "Active",
+ "Expired"
+ ]
+ },
"PaymentListConstraints": {
"type": "object",
"properties": {
@@ -9814,10 +9814,17 @@
],
"nullable": true
},
- "payment_link_object": {
+ "payment_link": {
+ "type": "boolean",
+ "description": "Whether to get the payment link (if applicable)",
+ "default": false,
+ "example": true,
+ "nullable": true
+ },
+ "payment_link_config": {
"allOf": [
{
- "$ref": "#/components/schemas/PaymentLinkObject"
+ "$ref": "#/components/schemas/PaymentCreatePaymentLinkConfig"
}
],
"nullable": true
@@ -9848,6 +9855,14 @@
"description": "Request for an incremental authorization",
"nullable": true
},
+ "session_expiry": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins",
+ "example": 900,
+ "nullable": true,
+ "minimum": 0
+ },
"frm_metadata": {
"description": "additional data related to some frm connectors",
"nullable": true
@@ -10188,10 +10203,17 @@
],
"nullable": true
},
- "payment_link_object": {
+ "payment_link": {
+ "type": "boolean",
+ "description": "Whether to get the payment link (if applicable)",
+ "default": false,
+ "example": true,
+ "nullable": true
+ },
+ "payment_link_config": {
"allOf": [
{
- "$ref": "#/components/schemas/PaymentLinkObject"
+ "$ref": "#/components/schemas/PaymentCreatePaymentLinkConfig"
}
],
"nullable": true
@@ -10222,6 +10244,14 @@
"description": "Request for an incremental authorization",
"nullable": true
},
+ "session_expiry": {
+ "type": "integer",
+ "format": "int32",
+ "description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins",
+ "example": 900,
+ "nullable": true,
+ "minimum": 0
+ },
"frm_metadata": {
"description": "additional data related to some frm connectors",
"nullable": true
@@ -11866,7 +11896,7 @@
"type": "string",
"format": "date-time"
},
- "link_expiry": {
+ "expiry": {
"type": "string",
"format": "date-time",
"nullable": true
@@ -11876,7 +11906,7 @@
"nullable": true
},
"status": {
- "type": "string"
+ "$ref": "#/components/schemas/PaymentLinkStatus"
},
"currency": {
"allOf": [
|
fix
|
Payment link api contract change (#2975)
|
a97016fea41c3b74149d8eaa5c0271ec1347bc39
|
2024-05-08 18:25:45
|
Mani Chandra
|
feat(users): Create `user_key_store` table and `begin_totp` API (#4577)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index 84fdee38021..b823f9e5c96 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1430,6 +1430,12 @@ dependencies = [
"rustc-demangle",
]
+[[package]]
+name = "base32"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23ce669cd6c8588f79e15cf450314f9638f967fc5770ff1c7c1deb0925ea7cfa"
+
[[package]]
name = "base64"
version = "0.13.1"
@@ -1559,7 +1565,7 @@ dependencies = [
"arrayvec",
"cc",
"cfg-if 1.0.0",
- "constant_time_eq",
+ "constant_time_eq 0.3.0",
]
[[package]]
@@ -2044,6 +2050,12 @@ dependencies = [
"tiny-keccak",
]
+[[package]]
+name = "constant_time_eq"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "21a53c0a4d288377e7415b53dcfc3c04da5cdc2cc95c8d5ac178b58f0b861ad6"
+
[[package]]
name = "constant_time_eq"
version = "0.3.0"
@@ -5683,6 +5695,7 @@ dependencies = [
"thiserror",
"time",
"tokio 1.37.0",
+ "totp-rs",
"tracing-futures",
"unicode-segmentation",
"url",
@@ -7473,6 +7486,22 @@ dependencies = [
"tracing-futures",
]
+[[package]]
+name = "totp-rs"
+version = "5.5.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6c4ae9724c5888c0417d2396037ed3b60665925624766416e3e342b6ba5dbd3f"
+dependencies = [
+ "base32",
+ "constant_time_eq 0.2.6",
+ "hmac",
+ "rand",
+ "sha1",
+ "sha2",
+ "url",
+ "urlencoding",
+]
+
[[package]]
name = "tower"
version = "0.4.13"
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index dab9ace3ac2..1d91a47bf56 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -10,13 +10,14 @@ use crate::user::{
dashboard_metadata::{
GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest,
},
- AcceptInviteFromEmailRequest, AuthorizeResponse, ChangePasswordRequest, ConnectAccountRequest,
- CreateInternalUserRequest, DashboardEntryResponse, ForgotPasswordRequest,
- GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponse,
- InviteUserRequest, ListUsersResponse, ReInviteUserRequest, ResetPasswordRequest,
- RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse, SignUpRequest,
- SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse, TokenResponse,
- UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate, VerifyEmailRequest,
+ AcceptInviteFromEmailRequest, AuthorizeResponse, BeginTotpResponse, ChangePasswordRequest,
+ ConnectAccountRequest, CreateInternalUserRequest, DashboardEntryResponse,
+ ForgotPasswordRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest,
+ GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, ReInviteUserRequest,
+ ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignInResponse,
+ SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest, TokenOrPayloadResponse,
+ TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate,
+ VerifyEmailRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -72,7 +73,8 @@ common_utils::impl_misc_api_event_type!(
GetUserRoleDetailsRequest,
GetUserRoleDetailsResponse,
TokenResponse,
- UserFromEmailRequest
+ UserFromEmailRequest,
+ BeginTotpResponse
);
#[cfg(feature = "dummy_connector")]
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index b2128cc949c..0dde73d0545 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -236,8 +236,19 @@ pub enum TokenOrPayloadResponse<T> {
Token(TokenResponse),
Payload(T),
}
-
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UserFromEmailRequest {
pub token: Secret<String>,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct BeginTotpResponse {
+ pub secret: Option<TotpSecret>,
+}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct TotpSecret {
+ pub secret: Secret<String>,
+ pub totp_url: Secret<String>,
+ pub recovery_codes: Vec<Secret<String>>,
+}
diff --git a/crates/diesel_models/src/enums.rs b/crates/diesel_models/src/enums.rs
index 85a7e3d92df..d78a6b11489 100644
--- a/crates/diesel_models/src/enums.rs
+++ b/crates/diesel_models/src/enums.rs
@@ -18,8 +18,8 @@ pub mod diesel_exports {
DbRefundStatus as RefundStatus, DbRefundType as RefundType,
DbRequestIncrementalAuthorization as RequestIncrementalAuthorization,
DbRoleScope as RoleScope, DbRoutingAlgorithmKind as RoutingAlgorithmKind,
- DbTransactionType as TransactionType, DbUserStatus as UserStatus,
- DbWebhookDeliveryAttempt as WebhookDeliveryAttempt,
+ DbTotpStatus as TotpStatus, DbTransactionType as TransactionType,
+ DbUserStatus as UserStatus, DbWebhookDeliveryAttempt as WebhookDeliveryAttempt,
};
}
pub use common_enums::*;
@@ -350,3 +350,26 @@ pub enum DashboardMetadata {
IsChangePasswordRequired,
OnboardingSurvey,
}
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ PartialEq,
+ serde::Serialize,
+ serde::Deserialize,
+ strum::Display,
+ strum::EnumString,
+ frunk::LabelledGeneric,
+)]
+#[diesel_enum(storage_type = "db_enum")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum TotpStatus {
+ Set,
+ InProgress,
+ #[default]
+ NotSet,
+}
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs
index 24df19ff737..d7d10569f7f 100644
--- a/crates/diesel_models/src/lib.rs
+++ b/crates/diesel_models/src/lib.rs
@@ -44,6 +44,7 @@ pub mod routing_algorithm;
#[allow(unused_qualifications)]
pub mod schema;
pub mod user;
+pub mod user_key_store;
pub mod user_role;
use diesel_impl::{DieselArray, OptionalDieselArray};
diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs
index b839fcc9b63..335c2db916d 100644
--- a/crates/diesel_models/src/query.rs
+++ b/crates/diesel_models/src/query.rs
@@ -36,4 +36,5 @@ pub mod reverse_lookup;
pub mod role;
pub mod routing_algorithm;
pub mod user;
+pub mod user_key_store;
pub mod user_role;
diff --git a/crates/diesel_models/src/query/user_key_store.rs b/crates/diesel_models/src/query/user_key_store.rs
new file mode 100644
index 00000000000..42dfe223b1a
--- /dev/null
+++ b/crates/diesel_models/src/query/user_key_store.rs
@@ -0,0 +1,24 @@
+use diesel::{associations::HasTable, ExpressionMethods};
+
+use super::generics;
+use crate::{
+ schema::user_key_store::dsl,
+ user_key_store::{UserKeyStore, UserKeyStoreNew},
+ PgPooledConn, StorageResult,
+};
+
+impl UserKeyStoreNew {
+ pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<UserKeyStore> {
+ generics::generic_insert(conn, self).await
+ }
+}
+
+impl UserKeyStore {
+ pub async fn find_by_user_id(conn: &PgPooledConn, user_id: &str) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::user_id.eq(user_id.to_owned()),
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 70a227a310a..20296adb65c 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1149,6 +1149,18 @@ diesel::table! {
}
}
+diesel::table! {
+ use diesel::sql_types::*;
+ use crate::enums::diesel_exports::*;
+
+ user_key_store (user_id) {
+ #[max_length = 64]
+ user_id -> Varchar,
+ key -> Bytea,
+ created_at -> Timestamp,
+ }
+}
+
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -1192,6 +1204,9 @@ diesel::table! {
last_modified_at -> Timestamp,
#[max_length = 64]
preferred_merchant_id -> Nullable<Varchar>,
+ totp_status -> TotpStatus,
+ totp_secret -> Nullable<Bytea>,
+ totp_recovery_codes -> Nullable<Array<Nullable<Text>>>,
last_password_modified_at -> Nullable<Timestamp>,
}
}
@@ -1232,6 +1247,7 @@ diesel::allow_tables_to_appear_in_same_query!(
reverse_lookup,
roles,
routing_algorithm,
+ user_key_store,
user_roles,
users,
);
diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs
index 850619f8af6..6a040e41468 100644
--- a/crates/diesel_models/src/user.rs
+++ b/crates/diesel_models/src/user.rs
@@ -3,7 +3,9 @@ use diesel::{AsChangeset, Identifiable, Insertable, Queryable};
use masking::Secret;
use time::PrimitiveDateTime;
-use crate::schema::users;
+use crate::{
+ diesel_impl::OptionalDieselArray, encryption::Encryption, enums::TotpStatus, schema::users,
+};
pub mod dashboard_metadata;
@@ -20,6 +22,10 @@ pub struct User {
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub preferred_merchant_id: Option<String>,
+ pub totp_status: TotpStatus,
+ pub totp_secret: Option<Encryption>,
+ #[diesel(deserialize_as = OptionalDieselArray<Secret<String>>)]
+ pub totp_recovery_codes: Option<Vec<Secret<String>>>,
pub last_password_modified_at: Option<PrimitiveDateTime>,
}
@@ -36,6 +42,9 @@ pub struct UserNew {
pub created_at: Option<PrimitiveDateTime>,
pub last_modified_at: Option<PrimitiveDateTime>,
pub preferred_merchant_id: Option<String>,
+ pub totp_status: TotpStatus,
+ pub totp_secret: Option<Encryption>,
+ pub totp_recovery_codes: Option<Vec<Secret<String>>>,
pub last_password_modified_at: Option<PrimitiveDateTime>,
}
@@ -47,6 +56,9 @@ pub struct UserUpdateInternal {
is_verified: Option<bool>,
last_modified_at: PrimitiveDateTime,
preferred_merchant_id: Option<String>,
+ totp_status: Option<TotpStatus>,
+ totp_secret: Option<Encryption>,
+ totp_recovery_codes: Option<Vec<Secret<String>>>,
last_password_modified_at: Option<PrimitiveDateTime>,
}
@@ -58,6 +70,11 @@ pub enum UserUpdate {
is_verified: Option<bool>,
preferred_merchant_id: Option<String>,
},
+ TotpUpdate {
+ totp_status: Option<TotpStatus>,
+ totp_secret: Option<Encryption>,
+ totp_recovery_codes: Option<Vec<Secret<String>>>,
+ },
PasswordUpdate {
password: Option<Secret<String>>,
},
@@ -73,6 +90,9 @@ impl From<UserUpdate> for UserUpdateInternal {
is_verified: Some(true),
last_modified_at,
preferred_merchant_id: None,
+ totp_status: None,
+ totp_secret: None,
+ totp_recovery_codes: None,
last_password_modified_at: None,
},
UserUpdate::AccountUpdate {
@@ -85,6 +105,24 @@ impl From<UserUpdate> for UserUpdateInternal {
is_verified,
last_modified_at,
preferred_merchant_id,
+ totp_status: None,
+ totp_secret: None,
+ totp_recovery_codes: None,
+ last_password_modified_at: None,
+ },
+ UserUpdate::TotpUpdate {
+ totp_status,
+ totp_secret,
+ totp_recovery_codes,
+ } => Self {
+ name: None,
+ password: None,
+ is_verified: None,
+ last_modified_at,
+ preferred_merchant_id: None,
+ totp_status,
+ totp_secret,
+ totp_recovery_codes,
last_password_modified_at: None,
},
UserUpdate::PasswordUpdate { password } => Self {
@@ -94,6 +132,9 @@ impl From<UserUpdate> for UserUpdateInternal {
last_modified_at,
preferred_merchant_id: None,
last_password_modified_at: Some(last_modified_at),
+ totp_status: None,
+ totp_secret: None,
+ totp_recovery_codes: None,
},
}
}
diff --git a/crates/diesel_models/src/user_key_store.rs b/crates/diesel_models/src/user_key_store.rs
new file mode 100644
index 00000000000..a35b4d9d169
--- /dev/null
+++ b/crates/diesel_models/src/user_key_store.rs
@@ -0,0 +1,21 @@
+use diesel::{Identifiable, Insertable, Queryable};
+use time::PrimitiveDateTime;
+
+use crate::{encryption::Encryption, schema::user_key_store};
+
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Identifiable, Queryable)]
+#[diesel(table_name = user_key_store)]
+#[diesel(primary_key(user_id))]
+pub struct UserKeyStore {
+ pub user_id: String,
+ pub key: Encryption,
+ pub created_at: PrimitiveDateTime,
+}
+
+#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Insertable)]
+#[diesel(table_name = user_key_store)]
+pub struct UserKeyStoreNew {
+ pub user_id: String,
+ pub key: Encryption,
+ pub created_at: PrimitiveDateTime,
+}
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 7ff47b927d8..144d6f07988 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -126,6 +126,7 @@ isocountry = "0.3.2"
iso_currency = "0.4.4"
actix-http = "3.6.0"
events = { version = "0.1.0", path = "../events" }
+totp-rs = { version = "5.5.1", features = ["gen_secret", "otpauth"]}
[build-dependencies]
router_env = { version = "0.1.0", path = "../router_env", default-features = false }
diff --git a/crates/router/src/consts/user.rs b/crates/router/src/consts/user.rs
index f14610649f4..8d6aa6265d8 100644
--- a/crates/router/src/consts/user.rs
+++ b/crates/router/src/consts/user.rs
@@ -1,5 +1,14 @@
pub const MAX_NAME_LENGTH: usize = 70;
pub const MAX_COMPANY_NAME_LENGTH: usize = 70;
pub const BUSINESS_EMAIL: &str = "[email protected]";
+pub const RECOVERY_CODES_COUNT: usize = 8;
+pub const RECOVERY_CODE_LENGTH: usize = 8; // This is without counting the hyphen in between
+pub const TOTP_ISSUER_NAME: &str = "Hyperswitch";
+/// The number of digits composing the auth code.
+pub const TOTP_DIGITS: usize = 6;
+/// Duration in seconds of a step.
+pub const TOTP_VALIDITY_DURATION_IN_SECONDS: u64 = 30;
+/// Number of totps allowed as network delay. 1 would mean one totp before current totp and one totp after are valids.
+pub const TOTP_TOLERANCE: u8 = 1;
pub const MAX_PASSWORD_LENGTH: usize = 70;
pub const MIN_PASSWORD_LENGTH: usize = 8;
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index e51ad6120c9..e01ed4b1a23 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1,9 +1,13 @@
use api_models::user::{self as user_api, InviteMultipleUserResponse};
#[cfg(feature = "email")]
use diesel_models::user_role::UserRoleUpdate;
-use diesel_models::{enums::UserStatus, user as storage_user, user_role::UserRoleNew};
+use diesel_models::{
+ enums::{TotpStatus, UserStatus},
+ user as storage_user,
+ user_role::UserRoleNew,
+};
use error_stack::{report, ResultExt};
-use masking::ExposeInterface;
+use masking::{ExposeInterface, PeekInterface};
#[cfg(feature = "email")]
use router_env::env;
use router_env::logger;
@@ -1581,3 +1585,60 @@ pub async fn user_from_email(
};
auth::cookies::set_cookie_response(response, token)
}
+
+pub async fn begin_totp(
+ state: AppState,
+ user_token: auth::UserFromSinglePurposeToken,
+) -> UserResponse<user_api::BeginTotpResponse> {
+ let user_from_db: domain::UserFromStorage = state
+ .store
+ .find_user_by_id(&user_token.user_id)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into();
+
+ if user_from_db.get_totp_status() == TotpStatus::Set {
+ return Ok(ApplicationResponse::Json(user_api::BeginTotpResponse {
+ secret: None,
+ }));
+ }
+
+ let totp = utils::user::generate_default_totp(user_from_db.get_email(), None)?;
+ let recovery_codes = domain::RecoveryCodes::generate_new();
+
+ let key_store = user_from_db.get_or_create_key_store(&state).await?;
+
+ state
+ .store
+ .update_user_by_user_id(
+ user_from_db.get_user_id(),
+ storage_user::UserUpdate::TotpUpdate {
+ totp_status: Some(TotpStatus::InProgress),
+ totp_secret: Some(
+ // TODO: Impl conversion trait for User and move this there
+ domain::types::encrypt::<String, masking::WithType>(
+ totp.get_secret_base32().into(),
+ key_store.key.peek(),
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into(),
+ ),
+ totp_recovery_codes: Some(
+ recovery_codes
+ .get_hashed()
+ .change_context(UserErrors::InternalServerError)?,
+ ),
+ },
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ Ok(ApplicationResponse::Json(user_api::BeginTotpResponse {
+ secret: Some(user_api::TotpSecret {
+ secret: totp.get_secret_base32().into(),
+ totp_url: totp.get_url().into(),
+ recovery_codes: recovery_codes.into_inner(),
+ }),
+ }))
+}
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index ca9432fcba9..c34bcaa1e38 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -33,6 +33,7 @@ pub mod reverse_lookup;
pub mod role;
pub mod routing_algorithm;
pub mod user;
+pub mod user_key_store;
pub mod user_role;
use diesel_models::{
@@ -118,6 +119,7 @@ pub trait StorageInterface:
+ user::sample_data::BatchSampleDataInterface
+ health_check::HealthCheckDbInterface
+ role::RoleInterface
+ + user_key_store::UserKeyStoreInterface
+ authentication::AuthenticationInterface
+ 'static
{
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0aaa47365fc..4a9ab7fc8f6 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -32,6 +32,7 @@ use super::{
dashboard_metadata::DashboardMetadataInterface,
role::RoleInterface,
user::{sample_data::BatchSampleDataInterface, UserInterface},
+ user_key_store::UserKeyStoreInterface,
user_role::UserRoleInterface,
};
#[cfg(feature = "payouts")]
@@ -2743,3 +2744,26 @@ impl RoleInterface for KafkaStore {
self.diesel_store.list_all_roles(merchant_id, org_id).await
}
}
+
+#[async_trait::async_trait]
+impl UserKeyStoreInterface for KafkaStore {
+ async fn insert_user_key_store(
+ &self,
+ user_key_store: domain::UserKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ self.diesel_store
+ .insert_user_key_store(user_key_store, key)
+ .await
+ }
+
+ async fn get_user_key_store_by_user_id(
+ &self,
+ user_id: &str,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ self.diesel_store
+ .get_user_key_store_by_user_id(user_id, key)
+ .await
+ }
+}
diff --git a/crates/router/src/db/user.rs b/crates/router/src/db/user.rs
index 9ec7cf6fab4..200513ae8d0 100644
--- a/crates/router/src/db/user.rs
+++ b/crates/router/src/db/user.rs
@@ -162,6 +162,9 @@ impl UserInterface for MockDb {
created_at: user_data.created_at.unwrap_or(time_now),
last_modified_at: user_data.created_at.unwrap_or(time_now),
preferred_merchant_id: user_data.preferred_merchant_id,
+ totp_status: user_data.totp_status,
+ totp_secret: user_data.totp_secret,
+ totp_recovery_codes: user_data.totp_recovery_codes,
last_password_modified_at: user_data.last_password_modified_at,
};
users.push(user.clone());
@@ -229,6 +232,18 @@ impl UserInterface for MockDb {
.or(user.preferred_merchant_id.clone()),
..user.to_owned()
},
+ storage::UserUpdate::TotpUpdate {
+ totp_status,
+ totp_secret,
+ totp_recovery_codes,
+ } => storage::User {
+ totp_status: totp_status.unwrap_or(user.totp_status),
+ totp_secret: totp_secret.clone().or(user.totp_secret.clone()),
+ totp_recovery_codes: totp_recovery_codes
+ .clone()
+ .or(user.totp_recovery_codes.clone()),
+ ..user.to_owned()
+ },
storage::UserUpdate::PasswordUpdate { password } => storage::User {
password: password.clone().unwrap_or(user.password.clone()),
last_password_modified_at: Some(common_utils::date_time::now()),
@@ -272,6 +287,18 @@ impl UserInterface for MockDb {
.or(user.preferred_merchant_id.clone()),
..user.to_owned()
},
+ storage::UserUpdate::TotpUpdate {
+ totp_status,
+ totp_secret,
+ totp_recovery_codes,
+ } => storage::User {
+ totp_status: totp_status.unwrap_or(user.totp_status),
+ totp_secret: totp_secret.clone().or(user.totp_secret.clone()),
+ totp_recovery_codes: totp_recovery_codes
+ .clone()
+ .or(user.totp_recovery_codes.clone()),
+ ..user.to_owned()
+ },
storage::UserUpdate::PasswordUpdate { password } => storage::User {
password: password.clone().unwrap_or(user.password.clone()),
last_password_modified_at: Some(common_utils::date_time::now()),
diff --git a/crates/router/src/db/user_key_store.rs b/crates/router/src/db/user_key_store.rs
new file mode 100644
index 00000000000..e08d17d280e
--- /dev/null
+++ b/crates/router/src/db/user_key_store.rs
@@ -0,0 +1,121 @@
+use common_utils::errors::CustomResult;
+use error_stack::{report, ResultExt};
+use masking::Secret;
+use router_env::{instrument, tracing};
+use storage_impl::MockDb;
+
+use crate::{
+ connection,
+ core::errors,
+ services::Store,
+ types::domain::{
+ self,
+ behaviour::{Conversion, ReverseConversion},
+ },
+};
+
+#[async_trait::async_trait]
+pub trait UserKeyStoreInterface {
+ async fn insert_user_key_store(
+ &self,
+ user_key_store: domain::UserKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError>;
+
+ async fn get_user_key_store_by_user_id(
+ &self,
+ user_id: &str,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError>;
+}
+
+#[async_trait::async_trait]
+impl UserKeyStoreInterface for Store {
+ #[instrument(skip_all)]
+ async fn insert_user_key_store(
+ &self,
+ user_key_store: domain::UserKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ user_key_store
+ .construct_new()
+ .await
+ .change_context(errors::StorageError::EncryptionError)?
+ .insert(&conn)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[instrument(skip_all)]
+ async fn get_user_key_store_by_user_id(
+ &self,
+ user_id: &str,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+
+ diesel_models::user_key_store::UserKeyStore::find_by_user_id(&conn, user_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+}
+
+#[async_trait::async_trait]
+impl UserKeyStoreInterface for MockDb {
+ #[instrument(skip_all)]
+ async fn insert_user_key_store(
+ &self,
+ user_key_store: domain::UserKeyStore,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ let mut locked_user_key_store = self.user_key_store.lock().await;
+
+ if locked_user_key_store
+ .iter()
+ .any(|user_key| user_key.user_id == user_key_store.user_id)
+ {
+ Err(errors::StorageError::DuplicateValue {
+ entity: "user_key_store",
+ key: Some(user_key_store.user_id.clone()),
+ })?;
+ }
+
+ let user_key_store = Conversion::convert(user_key_store)
+ .await
+ .change_context(errors::StorageError::MockDbError)?;
+ locked_user_key_store.push(user_key_store.clone());
+
+ user_key_store
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+
+ #[instrument(skip_all)]
+ async fn get_user_key_store_by_user_id(
+ &self,
+ user_id: &str,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<domain::UserKeyStore, errors::StorageError> {
+ self.user_key_store
+ .lock()
+ .await
+ .iter()
+ .find(|user_key_store| user_key_store.user_id == user_id)
+ .cloned()
+ .ok_or(errors::StorageError::ValueNotFound(format!(
+ "No user_key_store is found for user_id={}",
+ user_id
+ )))?
+ .convert(key)
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 857da69d4b3..cff4fc67db3 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1197,7 +1197,8 @@ impl User {
web::resource("/data")
.route(web::get().to(get_multiple_dashboard_metadata))
.route(web::post().to(set_dashboard_metadata)),
- );
+ )
+ .service(web::resource("/totp/begin").route(web::get().to(totp_begin)));
#[cfg(feature = "email")]
{
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 5f8346a8f23..5bef68073f0 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -210,7 +210,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::VerifyEmail
| Flow::AcceptInviteFromEmail
| Flow::VerifyEmailRequest
- | Flow::UpdateUserAccountDetails => Self::User,
+ | Flow::UpdateUserAccountDetails
+ | Flow::TotpBegin => Self::User,
Flow::ListRoles
| Flow::GetRole
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index f990438b2f1..db12729d01a 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -612,3 +612,17 @@ pub async fn user_from_email(
))
.await
}
+
+pub async fn totp_begin(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+ let flow = Flow::TotpBegin;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ (),
+ |state, user, _, _| user_core::begin_totp(state, user),
+ &auth::SinglePurposeJWTAuth(common_enums::TokenPurpose::TOTP),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router/src/types/domain.rs b/crates/router/src/types/domain.rs
index e5f6b8c9660..d18ae0d0190 100644
--- a/crates/router/src/types/domain.rs
+++ b/crates/router/src/types/domain.rs
@@ -9,6 +9,7 @@ pub mod payments;
pub mod types;
#[cfg(feature = "olap")]
pub mod user;
+pub mod user_key_store;
pub use address::*;
pub use customer::*;
@@ -19,3 +20,4 @@ pub use merchant_key_store::*;
pub use payments::*;
#[cfg(feature = "olap")]
pub use user::*;
+pub use user_key_store::*;
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 7e1a1eee3e8..00881626c1c 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -6,7 +6,7 @@ use api_models::{
use common_enums::TokenPurpose;
use common_utils::{errors::CustomResult, pii};
use diesel_models::{
- enums::UserStatus,
+ enums::{TotpStatus, UserStatus},
organization as diesel_org,
organization::Organization,
user as storage_user,
@@ -15,6 +15,7 @@ use diesel_models::{
use error_stack::{report, ResultExt};
use masking::{ExposeInterface, PeekInterface, Secret};
use once_cell::sync::Lazy;
+use rand::distributions::{Alphanumeric, DistString};
use router_env::env;
use unicode_segmentation::UnicodeSegmentation;
@@ -26,7 +27,7 @@ use crate::{
},
db::StorageInterface,
routes::AppState,
- services::{authentication as auth, authentication::UserFromToken, authorization::info},
+ services::{self, authentication as auth, authentication::UserFromToken, authorization::info},
types::transformers::ForeignFrom,
utils::{self, user::password},
};
@@ -35,6 +36,8 @@ pub mod dashboard_metadata;
pub mod decision_manager;
pub use decision_manager::*;
+use super::{types as domain_types, UserKeyStore};
+
#[derive(Clone)]
pub struct UserName(Secret<String>);
@@ -863,6 +866,49 @@ impl UserFromStorage {
)
}
}
+
+ pub async fn get_or_create_key_store(&self, state: &AppState) -> UserResult<UserKeyStore> {
+ let master_key = state.store.get_master_key();
+ let key_store_result = state
+ .store
+ .get_user_key_store_by_user_id(self.get_user_id(), &master_key.to_vec().into())
+ .await;
+
+ if let Ok(key_store) = key_store_result {
+ Ok(key_store)
+ } else if key_store_result
+ .as_ref()
+ .map_err(|e| e.current_context().is_db_not_found())
+ .err()
+ .unwrap_or(false)
+ {
+ let key = services::generate_aes256_key()
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Unable to generate aes 256 key")?;
+
+ let key_store = UserKeyStore {
+ user_id: self.get_user_id().to_string(),
+ key: domain_types::encrypt(key.to_vec().into(), master_key)
+ .await
+ .change_context(UserErrors::InternalServerError)?,
+ created_at: common_utils::date_time::now(),
+ };
+ state
+ .store
+ .insert_user_key_store(key_store, &master_key.to_vec().into())
+ .await
+ .change_context(UserErrors::InternalServerError)
+ } else {
+ Err(key_store_result
+ .err()
+ .map(|e| e.change_context(UserErrors::InternalServerError))
+ .unwrap_or(UserErrors::InternalServerError.into()))
+ }
+ }
+
+ pub fn get_totp_status(&self) -> TotpStatus {
+ self.0.totp_status
+ }
}
impl From<info::ModuleInfo> for user_role_api::ModuleInfo {
@@ -1031,3 +1077,36 @@ impl RoleName {
self.0
}
}
+
+#[derive(serde::Serialize, serde::Deserialize, Debug)]
+pub struct RecoveryCodes(pub Vec<Secret<String>>);
+
+impl RecoveryCodes {
+ pub fn generate_new() -> Self {
+ let mut rand = rand::thread_rng();
+ let recovery_codes = (0..consts::user::RECOVERY_CODES_COUNT)
+ .map(|_| {
+ let code_part_1 =
+ Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2);
+ let code_part_2 =
+ Alphanumeric.sample_string(&mut rand, consts::user::RECOVERY_CODE_LENGTH / 2);
+
+ Secret::new(format!("{}-{}", code_part_1, code_part_2))
+ })
+ .collect::<Vec<_>>();
+
+ Self(recovery_codes)
+ }
+
+ pub fn get_hashed(&self) -> UserResult<Vec<Secret<String>>> {
+ self.0
+ .iter()
+ .cloned()
+ .map(password::generate_password_hash)
+ .collect::<Result<Vec<_>, _>>()
+ }
+
+ pub fn into_inner(self) -> Vec<Secret<String>> {
+ self.0
+ }
+}
diff --git a/crates/router/src/types/domain/user_key_store.rs b/crates/router/src/types/domain/user_key_store.rs
new file mode 100644
index 00000000000..4c1427d58dc
--- /dev/null
+++ b/crates/router/src/types/domain/user_key_store.rs
@@ -0,0 +1,59 @@
+use common_utils::{
+ crypto::{Encryptable, GcmAes256},
+ date_time,
+};
+use error_stack::ResultExt;
+use masking::{PeekInterface, Secret};
+use time::PrimitiveDateTime;
+
+use crate::{
+ errors::{CustomResult, ValidationError},
+ types::domain::types::TypeEncryption,
+};
+
+#[derive(Clone, Debug, serde::Serialize)]
+pub struct UserKeyStore {
+ pub user_id: String,
+ pub key: Encryptable<Secret<Vec<u8>>>,
+ pub created_at: PrimitiveDateTime,
+}
+
+#[async_trait::async_trait]
+impl super::behaviour::Conversion for UserKeyStore {
+ type DstType = diesel_models::user_key_store::UserKeyStore;
+ type NewDstType = diesel_models::user_key_store::UserKeyStoreNew;
+
+ async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
+ Ok(diesel_models::user_key_store::UserKeyStore {
+ key: self.key.into(),
+ user_id: self.user_id,
+ created_at: self.created_at,
+ })
+ }
+
+ async fn convert_back(
+ item: Self::DstType,
+ key: &Secret<Vec<u8>>,
+ ) -> CustomResult<Self, ValidationError>
+ where
+ Self: Sized,
+ {
+ Ok(Self {
+ key: Encryptable::decrypt(item.key, key.peek(), GcmAes256)
+ .await
+ .change_context(ValidationError::InvalidValue {
+ message: "Failed while decrypting customer data".to_string(),
+ })?,
+ user_id: item.user_id,
+ created_at: item.created_at,
+ })
+ }
+
+ async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
+ Ok(diesel_models::user_key_store::UserKeyStoreNew {
+ user_id: self.user_id,
+ key: self.key.into(),
+ created_at: date_time::now(),
+ })
+ }
+}
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 33e9aa6769c..4980958c9ac 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -1,12 +1,14 @@
use std::collections::HashMap;
use api_models::user as user_api;
-use common_utils::errors::CustomResult;
+use common_utils::{errors::CustomResult, pii};
use diesel_models::{enums::UserStatus, user_role::UserRole};
use error_stack::ResultExt;
-use masking::Secret;
+use masking::ExposeInterface;
+use totp_rs::{Algorithm, TOTP};
use crate::{
+ consts,
core::errors::{StorageError, UserErrors, UserResult},
routes::AppState,
services::{
@@ -74,7 +76,7 @@ pub async fn generate_jwt_auth_token(
state: &AppState,
user: &UserFromStorage,
user_role: &UserRole,
-) -> UserResult<Secret<String>> {
+) -> UserResult<masking::Secret<String>> {
let token = AuthToken::new_token(
user.get_user_id().to_string(),
user_role.merchant_id.clone(),
@@ -83,7 +85,7 @@ pub async fn generate_jwt_auth_token(
user_role.org_id.clone(),
)
.await?;
- Ok(Secret::new(token))
+ Ok(masking::Secret::new(token))
}
pub async fn generate_jwt_auth_token_with_custom_role_attributes(
@@ -92,7 +94,7 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes(
merchant_id: String,
org_id: String,
role_id: String,
-) -> UserResult<Secret<String>> {
+) -> UserResult<masking::Secret<String>> {
let token = AuthToken::new_token(
user.get_user_id().to_string(),
merchant_id,
@@ -101,14 +103,14 @@ pub async fn generate_jwt_auth_token_with_custom_role_attributes(
org_id,
)
.await?;
- Ok(Secret::new(token))
+ Ok(masking::Secret::new(token))
}
pub fn get_dashboard_entry_response(
state: &AppState,
user: UserFromStorage,
user_role: UserRole,
- token: Secret<String>,
+ token: masking::Secret<String>,
) -> UserResult<user_api::DashboardEntryResponse> {
let verification_days_left = get_verification_days_left(state, &user)?;
@@ -185,9 +187,31 @@ pub async fn get_user_from_db_by_email(
.map(UserFromStorage::from)
}
-pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> Secret<String> {
+pub fn get_token_from_signin_response(resp: &user_api::SignInResponse) -> masking::Secret<String> {
match resp {
user_api::SignInResponse::DashboardEntry(data) => data.token.clone(),
user_api::SignInResponse::MerchantSelect(data) => data.token.clone(),
}
}
+
+pub fn generate_default_totp(
+ email: pii::Email,
+ secret: Option<masking::Secret<String>>,
+) -> UserResult<TOTP> {
+ let secret = secret
+ .map(|sec| totp_rs::Secret::Encoded(sec.expose()))
+ .unwrap_or_else(totp_rs::Secret::generate_secret)
+ .to_bytes()
+ .change_context(UserErrors::InternalServerError)?;
+
+ TOTP::new(
+ Algorithm::SHA1,
+ consts::user::TOTP_DIGITS,
+ consts::user::TOTP_TOLERANCE,
+ consts::user::TOTP_VALIDITY_DURATION_IN_SECONDS,
+ secret,
+ Some(consts::user::TOTP_ISSUER_NAME.to_string()),
+ email.expose().expose(),
+ )
+ .change_context(UserErrors::InternalServerError)
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index b360d20fed1..b3252302413 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -396,6 +396,8 @@ pub enum Flow {
UpdateRole,
/// User email flow start
UserFromEmail,
+ /// Begin TOTP
+ TotpBegin,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index 3657201f878..0ada6513ff0 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -57,6 +57,7 @@ pub struct MockDb {
pub payouts: Arc<Mutex<Vec<store::payouts::Payouts>>>,
pub authentications: Arc<Mutex<Vec<store::authentication::Authentication>>>,
pub roles: Arc<Mutex<Vec<store::role::Role>>>,
+ pub user_key_store: Arc<Mutex<Vec<store::user_key_store::UserKeyStore>>>,
}
impl MockDb {
@@ -100,6 +101,7 @@ impl MockDb {
payouts: Default::default(),
authentications: Default::default(),
roles: Default::default(),
+ user_key_store: Default::default(),
})
}
}
diff --git a/migrations/2024-05-06-105026_user_key_store_table/down.sql b/migrations/2024-05-06-105026_user_key_store_table/down.sql
new file mode 100644
index 00000000000..63df9500997
--- /dev/null
+++ b/migrations/2024-05-06-105026_user_key_store_table/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+DROP TABLE IF EXISTS user_key_store;
diff --git a/migrations/2024-05-06-105026_user_key_store_table/up.sql b/migrations/2024-05-06-105026_user_key_store_table/up.sql
new file mode 100644
index 00000000000..48147e6f597
--- /dev/null
+++ b/migrations/2024-05-06-105026_user_key_store_table/up.sql
@@ -0,0 +1,6 @@
+-- Your SQL goes here
+CREATE TABLE IF NOT EXISTS user_key_store (
+ user_id VARCHAR(64) PRIMARY KEY,
+ key bytea NOT NULL,
+ created_at TIMESTAMP NOT NULL DEFAULT now()
+);
diff --git a/migrations/2024-05-07-080628_user_totp/down.sql b/migrations/2024-05-07-080628_user_totp/down.sql
new file mode 100644
index 00000000000..d8e5840e35c
--- /dev/null
+++ b/migrations/2024-05-07-080628_user_totp/down.sql
@@ -0,0 +1,6 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE users DROP COLUMN totp_status;
+ALTER TABLE users DROP COLUMN totp_secret;
+ALTER TABLE users DROP COLUMN totp_recovery_codes;
+
+DROP TYPE "TotpStatus";
diff --git a/migrations/2024-05-07-080628_user_totp/up.sql b/migrations/2024-05-07-080628_user_totp/up.sql
new file mode 100644
index 00000000000..770a3fbd4c5
--- /dev/null
+++ b/migrations/2024-05-07-080628_user_totp/up.sql
@@ -0,0 +1,10 @@
+-- Your SQL goes here
+CREATE TYPE "TotpStatus" AS ENUM (
+ 'set',
+ 'in_progress',
+ 'not_set'
+);
+
+ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_status "TotpStatus" DEFAULT 'not_set' NOT NULL;
+ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_secret bytea DEFAULT NULL;
+ALTER TABLE users ADD COLUMN IF NOT EXISTS totp_recovery_codes TEXT[] DEFAULT NULL;
|
feat
|
Create `user_key_store` table and `begin_totp` API (#4577)
|
6a2070172b8d845e6db36b7789defddf8ea4e1e9
|
2024-11-29 15:28:14
|
Shankar Singh C
|
fix(router): populate card network in the network transaction id based MIT flow (#6690)
| false
|
diff --git a/config/config.example.toml b/config/config.example.toml
index ba14ed881cf..76a38192909 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -787,6 +787,9 @@ check_token_status_url= "" # base url to check token status from token servic
[network_tokenization_supported_connectors]
connector_list = "cybersource" # Supported connectors for network tokenization
+[network_transaction_id_supported_connectors]
+connector_list = "stripe,adyen,cybersource" # Supported connectors for network transaction id
+
[grpc_client.dynamic_routing_client] # Dynamic Routing Client Configuration
host = "localhost" # Client Host
port = 7000 # Client Port
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index a859d08ac4a..c266b94bba6 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -176,6 +176,8 @@ bank_redirect.giropay.connector_list = "adyen,globalpay,multisafepay" # M
card.credit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
card.debit = { connector_list = "cybersource" } # Update Mandate supported payment method type and connector for card
+[network_transaction_id_supported_connectors]
+connector_list = "stripe,adyen,cybersource"
[payouts]
payout_eligibility = true # Defaults the eligibility of a payout method to true in case connector does not provide checks for payout eligibility
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 22fa8965b7a..2ea36e3e35e 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -620,7 +620,7 @@ impl
.as_ref()
.map(|card_network| match card_network.to_lowercase().as_str() {
"amex" => "internet",
- "discover" => "dipb",
+ "discover" => "internet",
"mastercard" => "spa",
"visa" => "internet",
_ => "internet",
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 8435f09e8f3..219a4d90519 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -4674,7 +4674,7 @@ pub async fn get_additional_payment_data(
api_models::payments::AdditionalPaymentData::Card(Box::new(
api_models::payments::AdditionalCardInfo {
card_issuer: card_info.card_issuer,
- card_network,
+ card_network: card_info.card_network,
bank_code: card_info.bank_code,
card_type: card_info.card_type,
card_issuing_country: card_info.card_issuing_country,
|
fix
|
populate card network in the network transaction id based MIT flow (#6690)
|
1dad7455c4ae8d26d52c44d90f5b8d815d85d205
|
2023-10-18 16:52:06
|
Arjun Karthik
|
refactor: refactor connector auth type failure to 4xx (#2616)
| false
|
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index 2d10e37c10b..03b59c55036 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -239,6 +239,8 @@ pub enum StripeErrorCode {
PaymentLinkNotFound,
#[error(error_type = StripeErrorType::HyperswitchError, code = "", message = "Resource Busy. Please try again later")]
LockTimeout,
+ #[error(error_type = StripeErrorType::InvalidRequestError, code = "", message = "Merchant connector account is configured with invalid {config}")]
+ InvalidConnectorConfiguration { config: String },
// [#216]: https://github.com/juspay/hyperswitch/issues/216
// Implement the remaining stripe error codes
@@ -590,6 +592,9 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
Self::PaymentMethodUnactivated
}
errors::ApiErrorResponse::ResourceBusy => Self::PaymentMethodUnactivated,
+ errors::ApiErrorResponse::InvalidConnectorConfiguration { config } => {
+ Self::InvalidConnectorConfiguration { config }
+ }
}
}
}
@@ -656,7 +661,8 @@ impl actix_web::ResponseError for StripeErrorCode {
| Self::FileProviderNotSupported
| Self::CurrencyNotSupported { .. }
| Self::DuplicateCustomer
- | Self::PaymentMethodUnactivated => StatusCode::BAD_REQUEST,
+ | Self::PaymentMethodUnactivated
+ | Self::InvalidConnectorConfiguration { .. } => StatusCode::BAD_REQUEST,
Self::RefundFailed
| Self::PayoutFailed
| Self::PaymentLinkNotFound
diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
index e967caaba88..b622e041915 100644
--- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
+++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
@@ -86,8 +86,8 @@ impl TryFrom<&Option<pii::SecretSerdeValue>> for BraintreeMeta {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.clone())
- .change_context(errors::ConnectorError::InvalidConfig {
- field_name: "merchant connector account metadata",
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
})?;
Ok(metadata)
}
@@ -109,8 +109,8 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsAuthorizeRouterData>>
) -> Result<Self, Self::Error> {
let metadata: BraintreeMeta =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
- .change_context(errors::ConnectorError::InvalidConfig {
- field_name: "merchant connector account metadata",
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
})?;
utils::validate_currency(
item.router_data.request.currency,
@@ -602,8 +602,8 @@ impl<F> TryFrom<BraintreeRouterData<&types::RefundsRouterData<F>>> for Braintree
) -> Result<Self, Self::Error> {
let metadata: BraintreeMeta =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
- .change_context(errors::ConnectorError::InvalidConfig {
- field_name: "merchant connector account metadata",
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
})?;
utils::validate_currency(
@@ -712,9 +712,7 @@ impl TryFrom<&types::RefundSyncRouterData> for BraintreeRSyncRequest {
let metadata: BraintreeMeta = utils::to_connector_meta_from_secret(
item.connector_meta_data.clone(),
)
- .change_context(errors::ConnectorError::InvalidConfig {
- field_name: "merchant connector account metadata",
- })?;
+ .change_context(errors::ConnectorError::InvalidConnectorConfig { config: "metadata" })?;
utils::validate_currency(
item.request.currency,
Some(metadata.merchant_config_currency),
@@ -1345,8 +1343,8 @@ impl TryFrom<&BraintreeRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
) -> Result<Self, Self::Error> {
let metadata: BraintreeMeta =
utils::to_connector_meta_from_secret(item.router_data.connector_meta_data.clone())
- .change_context(errors::ConnectorError::InvalidConfig {
- field_name: "merchant connector account metadata",
+ .change_context(errors::ConnectorError::InvalidConnectorConfig {
+ config: "metadata",
})?;
utils::validate_currency(
item.router_data.request.currency,
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 46aae8faeab..e6c318285b5 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -701,11 +701,10 @@ pub async fn create_payment_connector(
message: "The connector name is invalid".to_string(),
})
}
- errors::ConnectorError::InvalidConfig { field_name } => {
- err.change_context(errors::ApiErrorResponse::InvalidRequestData {
+ errors::ConnectorError::InvalidConnectorConfig { config: field_name } => err
+ .change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!("The {} is invalid", field_name),
- })
- }
+ }),
errors::ConnectorError::FailedToObtainAuthType => {
err.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "The auth type is invalid for the connector".to_string(),
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index 9d75904ef66..1c062b7035a 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -179,7 +179,7 @@ pub enum ConnectorError {
connector: &'static str,
},
#[error("Invalid Configuration")]
- InvalidConfig { field_name: &'static str },
+ InvalidConnectorConfig { config: &'static str },
}
#[derive(Debug, thiserror::Error)]
diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs
index e606771b372..d34cbf88aaa 100644
--- a/crates/router/src/core/errors/api_error_response.rs
+++ b/crates/router/src/core/errors/api_error_response.rs
@@ -236,6 +236,8 @@ pub enum ApiErrorResponse {
WebhookInvalidMerchantSecret,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")]
CurrencyNotSupported { message: String },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_24", message = "Merchant connector account is configured with invalid {config}")]
+ InvalidConnectorConfiguration { config: String },
}
impl PTError for ApiErrorResponse {
diff --git a/crates/router/src/core/errors/transformers.rs b/crates/router/src/core/errors/transformers.rs
index 19640a931e1..17aa6f3a207 100644
--- a/crates/router/src/core/errors/transformers.rs
+++ b/crates/router/src/core/errors/transformers.rs
@@ -267,6 +267,9 @@ impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorRespon
Self::PaymentLinkNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Payment Link does not exist in our records", None))
}
+ Self::InvalidConnectorConfiguration {config} => {
+ AER::BadRequest(ApiError::new("IR", 24, format!("Merchant connector account is configured with invalid {config}"), None))
+ }
}
}
}
diff --git a/crates/router/src/core/errors/utils.rs b/crates/router/src/core/errors/utils.rs
index 8a86be2036b..c3cdf95b87b 100644
--- a/crates/router/src/core/errors/utils.rs
+++ b/crates/router/src/core/errors/utils.rs
@@ -205,7 +205,48 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
errors::ApiErrorResponse::InvalidDataValue { field_name }
},
errors::ConnectorError::CurrencyNotSupported { message, connector} => errors::ApiErrorResponse::CurrencyNotSupported { message: format!("Credentials for the currency {message} are not configured with the connector {connector}/hyperswitch") },
- _ => errors::ApiErrorResponse::InternalServerError,
+ errors::ConnectorError::FailedToObtainAuthType => errors::ApiErrorResponse::InvalidConnectorConfiguration {config: "connector_account_details".to_string()},
+ errors::ConnectorError::InvalidConnectorConfig { config } => errors::ApiErrorResponse::InvalidConnectorConfiguration { config: config.to_string() },
+ errors::ConnectorError::FailedToObtainIntegrationUrl |
+ errors::ConnectorError::RequestEncodingFailed |
+ errors::ConnectorError::RequestEncodingFailedWithReason(_) |
+ errors::ConnectorError::ParsingFailed |
+ errors::ConnectorError::ResponseDeserializationFailed |
+ errors::ConnectorError::UnexpectedResponseError(_) |
+ errors::ConnectorError::RoutingRulesParsingError |
+ errors::ConnectorError::FailedToObtainPreferredConnector |
+ errors::ConnectorError::InvalidConnectorName |
+ errors::ConnectorError::InvalidWallet |
+ errors::ConnectorError::ResponseHandlingFailed |
+ errors::ConnectorError::FailedToObtainCertificate |
+ errors::ConnectorError::NoConnectorMetaData |
+ errors::ConnectorError::FailedToObtainCertificateKey |
+ errors::ConnectorError::CaptureMethodNotSupported |
+ errors::ConnectorError::MissingConnectorMandateID |
+ errors::ConnectorError::MissingConnectorTransactionID |
+ errors::ConnectorError::MissingConnectorRefundID |
+ errors::ConnectorError::MissingApplePayTokenData |
+ errors::ConnectorError::WebhooksNotImplemented |
+ errors::ConnectorError::WebhookBodyDecodingFailed |
+ errors::ConnectorError::WebhookSignatureNotFound |
+ errors::ConnectorError::WebhookSourceVerificationFailed |
+ errors::ConnectorError::WebhookVerificationSecretNotFound |
+ errors::ConnectorError::WebhookVerificationSecretInvalid |
+ errors::ConnectorError::WebhookReferenceIdNotFound |
+ errors::ConnectorError::WebhookEventTypeNotFound |
+ errors::ConnectorError::WebhookResourceObjectNotFound |
+ errors::ConnectorError::WebhookResponseEncodingFailed |
+ errors::ConnectorError::InvalidDateFormat |
+ errors::ConnectorError::DateFormattingFailed |
+ errors::ConnectorError::InvalidWalletToken |
+ errors::ConnectorError::MissingConnectorRelatedTransactionID { .. } |
+ errors::ConnectorError::FileValidationFailed { .. } |
+ errors::ConnectorError::MissingConnectorRedirectionPayload { .. } |
+ errors::ConnectorError::FailedAtConnector { .. } |
+ errors::ConnectorError::MissingPaymentMethodType |
+ errors::ConnectorError::InSufficientBalanceInPaymentMethod |
+ errors::ConnectorError::RequestTimeoutReceived |
+ errors::ConnectorError::ProcessingStepFailed(None) => errors::ApiErrorResponse::InternalServerError
};
err.change_context(error)
})
@@ -235,8 +276,64 @@ impl<T> ConnectorErrorExt<T> for error_stack::Result<T, errors::ConnectorError>
errors::ConnectorError::MissingRequiredField { field_name } => {
errors::ApiErrorResponse::MissingRequiredField { field_name }
}
- _ => {
- logger::error!(%error,"Verify flow failed");
+ errors::ConnectorError::FailedToObtainIntegrationUrl => {
+ errors::ApiErrorResponse::InvalidConnectorConfiguration {
+ config: "connector_account_details".to_string(),
+ }
+ }
+ errors::ConnectorError::InvalidConnectorConfig { config: field_name } => {
+ errors::ApiErrorResponse::InvalidConnectorConfiguration {
+ config: field_name.to_string(),
+ }
+ }
+ errors::ConnectorError::RequestEncodingFailed
+ | errors::ConnectorError::RequestEncodingFailedWithReason(_)
+ | errors::ConnectorError::ParsingFailed
+ | errors::ConnectorError::ResponseDeserializationFailed
+ | errors::ConnectorError::UnexpectedResponseError(_)
+ | errors::ConnectorError::RoutingRulesParsingError
+ | errors::ConnectorError::FailedToObtainPreferredConnector
+ | errors::ConnectorError::InvalidConnectorName
+ | errors::ConnectorError::InvalidWallet
+ | errors::ConnectorError::ResponseHandlingFailed
+ | errors::ConnectorError::MissingRequiredFields { .. }
+ | errors::ConnectorError::FailedToObtainAuthType
+ | errors::ConnectorError::FailedToObtainCertificate
+ | errors::ConnectorError::NoConnectorMetaData
+ | errors::ConnectorError::FailedToObtainCertificateKey
+ | errors::ConnectorError::NotImplemented(_)
+ | errors::ConnectorError::NotSupported { .. }
+ | errors::ConnectorError::FlowNotSupported { .. }
+ | errors::ConnectorError::CaptureMethodNotSupported
+ | errors::ConnectorError::MissingConnectorMandateID
+ | errors::ConnectorError::MissingConnectorTransactionID
+ | errors::ConnectorError::MissingConnectorRefundID
+ | errors::ConnectorError::MissingApplePayTokenData
+ | errors::ConnectorError::WebhooksNotImplemented
+ | errors::ConnectorError::WebhookBodyDecodingFailed
+ | errors::ConnectorError::WebhookSignatureNotFound
+ | errors::ConnectorError::WebhookSourceVerificationFailed
+ | errors::ConnectorError::WebhookVerificationSecretNotFound
+ | errors::ConnectorError::WebhookVerificationSecretInvalid
+ | errors::ConnectorError::WebhookReferenceIdNotFound
+ | errors::ConnectorError::WebhookEventTypeNotFound
+ | errors::ConnectorError::WebhookResourceObjectNotFound
+ | errors::ConnectorError::WebhookResponseEncodingFailed
+ | errors::ConnectorError::InvalidDateFormat
+ | errors::ConnectorError::DateFormattingFailed
+ | errors::ConnectorError::InvalidDataFormat { .. }
+ | errors::ConnectorError::MismatchedPaymentData
+ | errors::ConnectorError::InvalidWalletToken
+ | errors::ConnectorError::MissingConnectorRelatedTransactionID { .. }
+ | errors::ConnectorError::FileValidationFailed { .. }
+ | errors::ConnectorError::MissingConnectorRedirectionPayload { .. }
+ | errors::ConnectorError::FailedAtConnector { .. }
+ | errors::ConnectorError::MissingPaymentMethodType
+ | errors::ConnectorError::InSufficientBalanceInPaymentMethod
+ | errors::ConnectorError::RequestTimeoutReceived
+ | errors::ConnectorError::CurrencyNotSupported { .. }
+ | errors::ConnectorError::ProcessingStepFailed(None) => {
+ logger::error!(%error,"Setup Mandate flow failed");
errors::ApiErrorResponse::PaymentAuthorizationFailed { data: None }
}
};
|
refactor
|
refactor connector auth type failure to 4xx (#2616)
|
f76f3e2f54ca518928b6f0457f1338c63e78d7e7
|
2022-12-09 13:10:44
|
ItsMeShashank
|
feat(router): dynamically toggle KV for merchant and refactoring around it (#79)
| false
|
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 947610868a6..9ffac79673e 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -274,7 +274,7 @@ pub async fn create_payment_connector(
req: api::PaymentConnectorCreate,
merchant_id: &String,
) -> RouterResponse<api::PaymentConnectorCreate> {
- store
+ let _merchant_account = store
.find_merchant_account_by_merchant_id(merchant_id)
.await
.map_err(|error| {
@@ -332,6 +332,13 @@ pub async fn retrieve_payment_connector(
merchant_id: String,
merchant_connector_id: i32,
) -> RouterResponse<api::PaymentConnectorCreate> {
+ let _merchant_account = store
+ .find_merchant_account_by_merchant_id(&merchant_id)
+ .await
+ .map_err(|error| {
+ error.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
+ })?;
+
let mca = store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&merchant_id,
@@ -366,11 +373,13 @@ pub async fn update_payment_connector(
merchant_connector_id: i32,
req: api::PaymentConnectorCreate,
) -> RouterResponse<api::PaymentConnectorCreate> {
- db.find_merchant_account_by_merchant_id(merchant_id)
+ let _merchant_account = db
+ .find_merchant_account_by_merchant_id(merchant_id)
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
})?;
+
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
merchant_id,
@@ -430,6 +439,13 @@ pub async fn delete_payment_connector(
merchant_id: String,
merchant_connector_id: i32,
) -> RouterResponse<api::DeleteMcaResponse> {
+ let _merchant_account = db
+ .find_merchant_account_by_merchant_id(&merchant_id)
+ .await
+ .map_err(|error| {
+ error.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
+ })?;
+
let is_deleted = db
.delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&merchant_id,
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index cea9cd2996a..1c9f08b0bef 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -65,21 +65,22 @@ where
let operation: BoxedOperation<F, Req> = Box::new(operation);
- let (operation, merchant_id, payment_id, mandate_type) = operation
+ let (operation, validate_result) = operation
.to_validate_request()?
.validate_request(&req, &merchant_account)?;
- tracing::Span::current().record("payment_id", &format!("{:?}", payment_id));
+ tracing::Span::current().record("payment_id", &format!("{:?}", validate_result.payment_id));
let (operation, mut payment_data, customer_details) = operation
.to_get_tracker()?
.get_trackers(
state,
- &payment_id,
- merchant_id,
+ &validate_result.payment_id,
+ validate_result.merchant_id,
connector.connector_name,
&req,
- mandate_type,
+ validate_result.mandate_type,
+ validate_result.storage_scheme,
)
.await?;
@@ -89,7 +90,7 @@ where
&*state.store,
&mut payment_data,
customer_details,
- merchant_id,
+ validate_result.merchant_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
@@ -103,13 +104,20 @@ where
&payment_data.payment_attempt,
&payment_data.payment_method_data,
&payment_data.token,
+ validate_result.storage_scheme,
)
.await?;
payment_data.payment_method_data = payment_method_data;
let (operation, mut payment_data) = operation
.to_update_tracker()?
- .update_trackers(&*state.store, &payment_id, payment_data, customer.clone())
+ .update_trackers(
+ &*state.store,
+ &validate_result.payment_id,
+ payment_data,
+ customer.clone(),
+ validate_result.storage_scheme,
+ )
.await?;
operation
@@ -121,7 +129,7 @@ where
payment_data = call_connector_service(
state,
&merchant_account,
- &payment_id,
+ &validate_result.payment_id,
connector,
&operation,
payment_data,
@@ -295,13 +303,20 @@ where
customer,
payment_data,
call_connector_action,
+ merchant_account.storage_scheme,
)
.await;
let response = helpers::amap(res, |response| async {
let operation = helpers::response_operation::<F, Req>();
let payment_data = operation
.to_post_update_tracker()?
- .update_tracker(db, payment_id, payment_data, Some(response))
+ .update_tracker(
+ db,
+ payment_id,
+ payment_data,
+ Some(response),
+ merchant_account.storage_scheme,
+ )
.await?;
Ok(payment_data)
})
@@ -451,9 +466,10 @@ pub async fn list_payments(
) -> RouterResponse<api::PaymentListResponse> {
validate_payment_list_request(&constraints)?;
let merchant_id = &merchant.merchant_id;
- let payment_intent = filter_by_constraints(db, &constraints, merchant_id)
- .await
- .map_err(|err| err.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))?;
+ let payment_intent =
+ filter_by_constraints(db, &constraints, merchant_id, merchant.storage_scheme)
+ .await
+ .map_err(|err| err.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))?;
let data: Vec<api::PaymentsResponse> = payment_intent.into_iter().map(From::from).collect();
utils::when(
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 68787cc6a85..18e75a7de48 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -11,7 +11,10 @@ use crate::{
core::{errors::RouterResult, payments},
routes::AppState,
services,
- types::{self, api, storage},
+ types::{
+ self, api,
+ storage::{self, enums},
+ },
};
#[async_trait]
@@ -33,6 +36,7 @@ pub trait Feature<F, T> {
maybe_customer: &Option<storage::Customer>,
payment_data: PaymentData<F>,
call_connector_action: payments::CallConnectorAction,
+ storage_scheme: enums::MerchantStorageScheme,
) -> (RouterResult<Self>, PaymentData<F>)
where
Self: std::marker::Sized,
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 357051db0b1..7519d244fd2 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -60,6 +60,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData>
customer: &Option<storage::Customer>,
payment_data: PaymentData<api::Authorize>,
call_connector_action: payments::CallConnectorAction,
+ storage_scheme: enums::MerchantStorageScheme,
) -> (RouterResult<Self>, PaymentData<api::Authorize>)
where
dyn api::Connector: services::ConnectorIntegration<
@@ -75,6 +76,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData>
customer,
Some(true),
call_connector_action,
+ storage_scheme,
)
.await;
@@ -92,6 +94,7 @@ impl PaymentsAuthorizeRouterData {
maybe_customer: &Option<storage::Customer>,
confirm: Option<bool>,
call_connector_action: payments::CallConnectorAction,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentsAuthorizeRouterData>
where
dyn api::Connector + Sync: services::ConnectorIntegration<
diff --git a/crates/router/src/core/payments/flows/cancel_flow.rs b/crates/router/src/core/payments/flows/cancel_flow.rs
index 61d3b5a90f5..5b6b0f9ba6e 100644
--- a/crates/router/src/core/payments/flows/cancel_flow.rs
+++ b/crates/router/src/core/payments/flows/cancel_flow.rs
@@ -8,7 +8,11 @@ use crate::{
},
routes::AppState,
services,
- types::{self, api, storage, PaymentsCancelRouterData, PaymentsResponseData},
+ types::{
+ self, api,
+ storage::{self, enums},
+ PaymentsCancelRouterData, PaymentsResponseData,
+ },
};
#[async_trait]
@@ -41,6 +45,7 @@ impl Feature<api::Void, types::PaymentsCancelData>
customer: &Option<storage::Customer>,
payment_data: PaymentData<api::Void>,
call_connector_action: payments::CallConnectorAction,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> (RouterResult<Self>, PaymentData<api::Void>)
where
dyn api::Connector: services::ConnectorIntegration<
diff --git a/crates/router/src/core/payments/flows/capture_flow.rs b/crates/router/src/core/payments/flows/capture_flow.rs
index ef4681b1afd..0bda242bc7a 100644
--- a/crates/router/src/core/payments/flows/capture_flow.rs
+++ b/crates/router/src/core/payments/flows/capture_flow.rs
@@ -9,7 +9,9 @@ use crate::{
routes::AppState,
services,
types::{
- self, api, storage, PaymentsCaptureData, PaymentsCaptureRouterData, PaymentsResponseData,
+ self, api,
+ storage::{self, enums},
+ PaymentsCaptureData, PaymentsCaptureRouterData, PaymentsResponseData,
},
};
@@ -44,6 +46,7 @@ impl Feature<api::Capture, types::PaymentsCaptureData>
customer: &Option<storage::Customer>,
payment_data: PaymentData<api::Capture>,
call_connector_action: payments::CallConnectorAction,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> (RouterResult<Self>, PaymentData<api::Capture>)
where
dyn api::Connector: services::ConnectorIntegration<
diff --git a/crates/router/src/core/payments/flows/psync_flow.rs b/crates/router/src/core/payments/flows/psync_flow.rs
index 38d50228ea4..9b269340ed0 100644
--- a/crates/router/src/core/payments/flows/psync_flow.rs
+++ b/crates/router/src/core/payments/flows/psync_flow.rs
@@ -8,7 +8,11 @@ use crate::{
},
routes::AppState,
services,
- types::{self, api, storage, PaymentsResponseData, PaymentsSyncData, PaymentsSyncRouterData},
+ types::{
+ self, api,
+ storage::{self, enums},
+ PaymentsResponseData, PaymentsSyncData, PaymentsSyncRouterData,
+ },
};
#[async_trait]
@@ -43,6 +47,7 @@ impl Feature<api::PSync, types::PaymentsSyncData>
customer: &Option<storage::Customer>,
payment_data: PaymentData<api::PSync>,
call_connector_action: payments::CallConnectorAction,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> (RouterResult<Self>, PaymentData<api::PSync>)
where
dyn api::Connector: services::ConnectorIntegration<
diff --git a/crates/router/src/core/payments/flows/verfiy_flow.rs b/crates/router/src/core/payments/flows/verfiy_flow.rs
index fa0665cb87c..98f1e15fa7a 100644
--- a/crates/router/src/core/payments/flows/verfiy_flow.rs
+++ b/crates/router/src/core/payments/flows/verfiy_flow.rs
@@ -47,6 +47,7 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData
customer: &Option<storage::Customer>,
payment_data: PaymentData<api::Verify>,
call_connector_action: payments::CallConnectorAction,
+ storage_scheme: enums::MerchantStorageScheme,
) -> (RouterResult<Self>, PaymentData<api::Verify>)
where
dyn api::Connector: services::ConnectorIntegration<
@@ -62,6 +63,7 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData
customer,
Some(true),
call_connector_action,
+ storage_scheme,
)
.await;
@@ -77,6 +79,7 @@ impl types::VerifyRouterData {
maybe_customer: &Option<storage::Customer>,
confirm: Option<bool>,
call_connector_action: payments::CallConnectorAction,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<Self>
where
dyn api::Connector + Sync: services::ConnectorIntegration<
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 6c19bafa107..19f7f2e8abb 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -807,9 +807,10 @@ pub(super) async fn filter_by_constraints(
db: &dyn StorageInterface,
constraints: &api::PaymentListConstraints,
merchant_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage::PaymentIntent>, errors::StorageError> {
let result = db
- .filter_payment_intent_by_constraints(merchant_id, constraints)
+ .filter_payment_intent_by_constraints(merchant_id, constraints, storage_scheme)
.await?;
Ok(result)
}
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 6f1396148ac..8a24b41c9d3 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -68,18 +68,20 @@ pub trait Operation<F: Clone, T>: Send + std::fmt::Debug {
}
}
+pub struct ValidateResult<'a> {
+ pub merchant_id: &'a str,
+ pub payment_id: api::PaymentIdType,
+ pub mandate_type: Option<api::MandateTxnType>,
+ pub storage_scheme: enums::MerchantStorageScheme,
+}
+
#[allow(clippy::type_complexity)]
pub trait ValidateRequest<F, R> {
fn validate_request<'a, 'b>(
&'b self,
request: &R,
merchant_account: &'a storage::MerchantAccount,
- ) -> RouterResult<(
- BoxedOperation<'b, F, R>,
- &'a str,
- api::PaymentIdType,
- Option<api::MandateTxnType>,
- )>;
+ ) -> RouterResult<(BoxedOperation<'b, F, R>, ValidateResult<'a>)>;
}
#[async_trait]
@@ -93,6 +95,7 @@ pub trait GetTracker<F, D, R>: Send {
connector: types::Connector,
request: &R,
mandate_type: Option<api::MandateTxnType>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(BoxedOperation<'a, F, R>, D, Option<CustomerDetails>)>;
}
@@ -116,6 +119,7 @@ pub trait Domain<F: Clone, R>: Send + Sync {
payment_attempt: &storage::PaymentAttempt,
request: &Option<api::PaymentMethod>,
token: &Option<String>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(BoxedOperation<'a, F, R>, Option<api::PaymentMethod>)>;
async fn add_task_to_process_tracker<'a>(
@@ -135,6 +139,7 @@ pub trait UpdateTracker<F, D, R>: Send {
payment_id: &api::PaymentIdType,
payment_data: D,
customer: Option<Customer>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(BoxedOperation<'b, F, R>, D)>
where
F: 'b + Send;
@@ -148,6 +153,7 @@ pub trait PostUpdateTracker<F, D, R>: Send {
payment_id: &api::PaymentIdType,
payment_data: D,
response: Option<types::RouterData<F, R, PaymentsResponseData>>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<D>
where
F: 'b + Send;
@@ -192,6 +198,7 @@ where
payment_attempt: &storage::PaymentAttempt,
request: &Option<api::PaymentMethod>,
token: &Option<String>,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRequest>,
Option<api::PaymentMethod>,
@@ -280,6 +287,7 @@ where
payment_attempt: &storage::PaymentAttempt,
request: &Option<api::PaymentMethod>,
token: &Option<String>,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRetrieveRequest>,
Option<api::PaymentMethod>,
@@ -336,6 +344,7 @@ where
_payment_attempt: &storage::PaymentAttempt,
_request: &Option<api::PaymentMethod>,
_token: &Option<String>,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsCaptureRequest>,
Option<api::PaymentMethod>,
@@ -384,6 +393,7 @@ where
_payment_attempt: &storage::PaymentAttempt,
_request: &Option<api::PaymentMethod>,
_token: &Option<String>,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsCancelRequest>,
Option<api::PaymentMethod>,
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index efe2ee53d99..8ef176cc309 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -9,7 +9,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
- payments::{CustomerDetails, PaymentAddress, PaymentData},
+ payments::{operations, CustomerDetails, PaymentAddress, PaymentData},
},
db::StorageInterface,
routes::AppState,
@@ -36,6 +36,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
_connector: Connector,
request: &api::PaymentsCancelRequest,
_mandate_type: Option<api::MandateTxnType>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsCancelRequest>,
PaymentData<F>,
@@ -47,14 +48,18 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let payment_intent = db
- .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id)
+ .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id, storage_scheme)
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
})?;
let mut payment_attempt = db
- .find_payment_attempt_by_payment_id_merchant_id(&payment_id, merchant_id)
+ .find_payment_attempt_by_payment_id_merchant_id(
+ &payment_id,
+ merchant_id,
+ storage_scheme,
+ )
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
@@ -65,6 +70,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
&payment_attempt.payment_id,
&payment_attempt.merchant_id,
&payment_attempt.txn_id,
+ storage_scheme,
)
.await
.map_err(|error| {
@@ -116,6 +122,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for
_payment_id: &api::PaymentIdType,
mut payment_data: PaymentData<F>,
_customer: Option<Customer>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsCancelRequest>,
PaymentData<F>,
@@ -131,6 +138,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsCancelRequest> for
status: enums::AttemptStatus::VoidInitiated,
cancellation_reason,
},
+ storage_scheme,
)
.await
.map_err(|err| err.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))?;
@@ -147,15 +155,16 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCancelRequest> for Payment
merchant_account: &'a storage::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsCancelRequest>,
- &'a str,
- api::PaymentIdType,
- Option<api::MandateTxnType>,
+ operations::ValidateResult<'a>,
)> {
Ok((
Box::new(self),
- &merchant_account.merchant_id,
- api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
- None,
+ operations::ValidateResult {
+ merchant_id: &merchant_account.merchant_id,
+ payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
+ mandate_type: None,
+ storage_scheme: merchant_account.storage_scheme,
+ },
))
}
}
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 375e603ef80..6efc21c3fd5 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -8,11 +8,16 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
- payments::{self, helpers},
+ payments::{self, helpers, operations},
},
db::StorageInterface,
routes::AppState,
- types::{api, api::PaymentsCaptureRequest, storage, Connector},
+ types::{
+ api,
+ api::PaymentsCaptureRequest,
+ storage::{self, enums},
+ Connector,
+ },
utils::OptionExt,
};
@@ -33,6 +38,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu
_connector: Connector,
request: &PaymentsCaptureRequest,
_mandate_type: Option<api::MandateTxnType>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsCaptureRequest>,
payments::PaymentData<F>,
@@ -46,7 +52,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
payment_intent = db
- .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id)
+ .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id, storage_scheme)
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
@@ -57,7 +63,11 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu
helpers::validate_amount_to_capture(payment_intent.amount, request.amount_to_capture)?;
payment_attempt = db
- .find_payment_attempt_by_payment_id_merchant_id(&payment_id, merchant_id)
+ .find_payment_attempt_by_payment_id_merchant_id(
+ &payment_id,
+ merchant_id,
+ storage_scheme,
+ )
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
@@ -82,6 +92,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu
&payment_attempt.payment_id,
&payment_attempt.merchant_id,
&payment_attempt.txn_id,
+ storage_scheme,
)
.await
.map_err(|error| {
@@ -140,6 +151,7 @@ impl<F: Clone> UpdateTracker<F, payments::PaymentData<F>, api::PaymentsCaptureRe
_payment_id: &api::PaymentIdType,
payment_data: payments::PaymentData<F>,
_customer: Option<storage::Customer>,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsCaptureRequest>,
payments::PaymentData<F>,
@@ -159,9 +171,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCaptureRequest> for Paymen
merchant_account: &'a storage::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsCaptureRequest>,
- &'a str,
- api::PaymentIdType,
- Option<api::MandateTxnType>,
+ operations::ValidateResult<'a>,
)> {
let payment_id = request
.payment_id
@@ -170,9 +180,12 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCaptureRequest> for Paymen
Ok((
Box::new(self),
- &merchant_account.merchant_id,
- api::PaymentIdType::PaymentIntentId(payment_id.to_owned()),
- None,
+ operations::ValidateResult {
+ merchant_id: &merchant_account.merchant_id,
+ payment_id: api::PaymentIdType::PaymentIntentId(payment_id.to_owned()),
+ mandate_type: None,
+ storage_scheme: merchant_account.storage_scheme,
+ },
))
}
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index d56dab264c6..6bc12c40831 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -9,7 +9,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
- payments::{helpers, CustomerDetails, PaymentAddress, PaymentData},
+ payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
db::StorageInterface,
@@ -37,6 +37,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
_connector: Connector,
request: &api::PaymentsRequest,
mandate_type: Option<api::MandateTxnType>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRequest>,
PaymentData<F>,
@@ -54,7 +55,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.await?;
payment_intent = db
- .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id)
+ .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id, storage_scheme)
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
@@ -78,7 +79,11 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
})?;
payment_attempt = db
- .find_payment_attempt_by_payment_id_merchant_id(&payment_id, merchant_id)
+ .find_payment_attempt_by_payment_id_merchant_id(
+ &payment_id,
+ merchant_id,
+ storage_scheme,
+ )
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
@@ -95,6 +100,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
&payment_attempt.payment_id,
&payment_attempt.merchant_id,
&payment_attempt.txn_id,
+ storage_scheme,
)
.await
.map_err(|error| {
@@ -167,6 +173,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
_payment_id: &api::PaymentIdType,
mut payment_data: PaymentData<F>,
_customer: Option<storage::Customer>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
where
F: 'b + Send,
@@ -194,6 +201,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
payment_method,
browser_info,
},
+ storage_scheme,
)
.await
.map_err(|error| {
@@ -213,6 +221,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
shipping_address_id: shipping_address,
billing_address_id: billing_address,
},
+ storage_scheme,
)
.await
.map_err(|error| {
@@ -231,9 +240,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir
merchant_account: &'a storage::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRequest>,
- &'a str,
- api::PaymentIdType,
- Option<api::MandateTxnType>,
+ operations::ValidateResult<'a>,
)> {
let given_payment_id = match &request.payment_id {
Some(id_type) => Some(
@@ -256,9 +263,12 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir
Ok((
Box::new(self),
- &merchant_account.merchant_id,
- api::PaymentIdType::PaymentIntentId(payment_id),
- mandate_type,
+ operations::ValidateResult {
+ merchant_id: &merchant_account.merchant_id,
+ payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
+ mandate_type,
+ storage_scheme: merchant_account.storage_scheme,
+ },
))
}
}
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 7e6e2ffb1ab..bde66ba9c43 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -11,7 +11,7 @@ use crate::{
consts,
core::{
errors::{self, RouterResult, StorageErrorExt},
- payments::{self, helpers, CustomerDetails, PaymentAddress, PaymentData},
+ payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
db::StorageInterface,
@@ -40,6 +40,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
connector: types::Connector,
request: &api::PaymentsRequest,
mandate_type: Option<api::MandateTxnType>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRequest>,
PaymentData<F>,
@@ -79,15 +80,18 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
})?;
payment_attempt = match db
- .insert_payment_attempt(Self::make_payment_attempt(
- &payment_id,
- merchant_id,
- connector,
- money,
- payment_method_type,
- request,
- browser_info,
- ))
+ .insert_payment_attempt(
+ Self::make_payment_attempt(
+ &payment_id,
+ merchant_id,
+ connector,
+ money,
+ payment_method_type,
+ request,
+ browser_info,
+ ),
+ storage_scheme,
+ )
.await
{
Ok(payment_attempt) => Ok(payment_attempt),
@@ -95,25 +99,32 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
Err(err) => match err.current_context() {
errors::StorageError::DatabaseError(errors::DatabaseError::UniqueViolation) => {
is_update = true;
- db.find_payment_attempt_by_payment_id_merchant_id(&payment_id, merchant_id)
- .await
- .map_err(|error| {
- error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
- })
+ db.find_payment_attempt_by_payment_id_merchant_id(
+ &payment_id,
+ merchant_id,
+ storage_scheme,
+ )
+ .await
+ .map_err(|error| {
+ error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
+ })
}
_ => Err(err).change_context(errors::ApiErrorResponse::InternalServerError),
},
}?;
payment_intent = match db
- .insert_payment_intent(Self::make_payment_intent(
- &payment_id,
- merchant_id,
- &connector.to_string(),
- money,
- request,
- shipping_address.clone().map(|x| x.address_id),
- billing_address.clone().map(|x| x.address_id),
- ))
+ .insert_payment_intent(
+ Self::make_payment_intent(
+ &payment_id,
+ merchant_id,
+ &connector.to_string(),
+ money,
+ request,
+ shipping_address.clone().map(|x| x.address_id),
+ billing_address.clone().map(|x| x.address_id),
+ ),
+ storage_scheme,
+ )
.await
{
Ok(payment_intent) => Ok(payment_intent),
@@ -121,18 +132,25 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
Err(err) => match err.current_context() {
errors::StorageError::DatabaseError(errors::DatabaseError::UniqueViolation) => {
is_update = true;
- db.find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id)
- .await
- .map_err(|error| {
- error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
- })
+ db.find_payment_intent_by_payment_id_merchant_id(
+ &payment_id,
+ merchant_id,
+ storage_scheme,
+ )
+ .await
+ .map_err(|error| {
+ error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
+ })
}
_ => Err(err).change_context(errors::ApiErrorResponse::InternalServerError),
},
}?;
connector_response = match db
- .insert_connector_response(Self::make_connector_response(&payment_attempt))
+ .insert_connector_response(
+ Self::make_connector_response(&payment_attempt),
+ storage_scheme,
+ )
.await
{
Ok(connector_resp) => Ok(connector_resp),
@@ -195,6 +213,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
_payment_id: &api::PaymentIdType,
mut payment_data: PaymentData<F>,
_customer: Option<storage::Customer>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
where
F: 'b + Send,
@@ -225,6 +244,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
shipping_address_id: None,
billing_address_id: None,
},
+ storage_scheme,
)
.await
.map_err(|error| {
@@ -248,9 +268,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate
merchant_account: &'a storage::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRequest>,
- &'a str,
- api::PaymentIdType,
- Option<api::MandateTxnType>,
+ operations::ValidateResult<'a>,
)> {
let given_payment_id = match &request.payment_id {
Some(id_type) => Some(
@@ -281,9 +299,12 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate
Ok((
Box::new(self),
- &merchant_account.merchant_id,
- api::PaymentIdType::PaymentIntentId(payment_id),
- mandate_type,
+ operations::ValidateResult {
+ merchant_id: &merchant_account.merchant_id,
+ payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
+ mandate_type,
+ storage_scheme: merchant_account.storage_scheme,
+ },
))
}
}
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 b79cc73bcd4..cd2a5cd6925 100644
--- a/crates/router/src/core/payments/operations/payment_method_validate.rs
+++ b/crates/router/src/core/payments/operations/payment_method_validate.rs
@@ -12,7 +12,7 @@ use crate::{
consts,
core::{
errors::{self, RouterResult, StorageErrorExt},
- payments::{self, helpers, Operation, PaymentData},
+ payments::{self, helpers, operations, Operation, PaymentData},
utils as core_utils,
},
db::StorageInterface,
@@ -36,9 +36,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::VerifyRequest> for PaymentMethodVa
merchant_account: &'a types::storage::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::VerifyRequest>,
- &'a str,
- api::PaymentIdType,
- Option<api::MandateTxnType>,
+ operations::ValidateResult<'a>,
)> {
let request_merchant_id = request.merchant_id.as_deref();
helpers::validate_merchant_id(&merchant_account.merchant_id, request_merchant_id)
@@ -49,9 +47,12 @@ impl<F: Send + Clone> ValidateRequest<F, api::VerifyRequest> for PaymentMethodVa
Ok((
Box::new(self),
- &merchant_account.merchant_id,
- api::PaymentIdType::PaymentIntentId(validation_id),
- mandate_type,
+ operations::ValidateResult {
+ merchant_id: &merchant_account.merchant_id,
+ payment_id: api::PaymentIdType::PaymentIntentId(validation_id),
+ mandate_type,
+ storage_scheme: merchant_account.storage_scheme,
+ },
))
}
}
@@ -67,6 +68,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym
connector: types::Connector,
request: &api::VerifyRequest,
_mandate_type: Option<api::MandateTxnType>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::VerifyRequest>,
PaymentData<F>,
@@ -80,13 +82,16 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym
.change_context(errors::ApiErrorResponse::InternalServerError)?;
payment_attempt = match db
- .insert_payment_attempt(Self::make_payment_attempt(
- &payment_id,
- merchant_id,
- connector,
- request.payment_method,
- request,
- ))
+ .insert_payment_attempt(
+ Self::make_payment_attempt(
+ &payment_id,
+ merchant_id,
+ connector,
+ request.payment_method,
+ request,
+ ),
+ storage_scheme,
+ )
.await
{
Ok(payment_attempt) => Ok(payment_attempt),
@@ -96,12 +101,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym
}?;
payment_intent = match db
- .insert_payment_intent(Self::make_payment_intent(
- &payment_id,
- merchant_id,
- connector,
- request,
- ))
+ .insert_payment_intent(
+ Self::make_payment_intent(&payment_id, merchant_id, connector, request),
+ storage_scheme,
+ )
.await
{
Ok(payment_intent) => Ok(payment_intent),
@@ -111,7 +114,10 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::VerifyRequest> for Paym
}?;
connector_response = match db
- .insert_connector_response(PaymentCreate::make_connector_response(&payment_attempt))
+ .insert_connector_response(
+ PaymentCreate::make_connector_response(&payment_attempt),
+ storage_scheme,
+ )
.await
{
Ok(connector_resp) => Ok(connector_resp),
@@ -159,6 +165,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::VerifyRequest> for PaymentM
_payment_id: &api::PaymentIdType,
mut payment_data: PaymentData<F>,
_customer: Option<storage::Customer>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(BoxedOperation<'b, F, api::VerifyRequest>, PaymentData<F>)>
where
F: 'b + Send,
@@ -178,6 +185,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::VerifyRequest> for PaymentM
shipping_address_id: None,
billing_address_id: None,
},
+ storage_scheme,
)
.await
.map_err(|err| {
@@ -230,6 +238,7 @@ where
payment_attempt: &storage::PaymentAttempt,
request: &Option<api::PaymentMethod>,
token: &Option<String>,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::VerifyRequest>,
Option<api::PaymentMethod>,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index cb0f094e745..e14e13e9e34 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -36,6 +36,7 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorizeData
response: Option<
types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
@@ -44,7 +45,14 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsAuthorizeData
payment_data.mandate_id = payment_data
.mandate_id
.or_else(|| router_data.request.mandate_id.clone());
- Ok(payment_response_ut(db, payment_id, payment_data, Some(router_data)).await?)
+ Ok(payment_response_ut(
+ db,
+ payment_id,
+ payment_data,
+ Some(router_data),
+ storage_scheme,
+ )
+ .await?)
}
}
@@ -58,11 +66,12 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsSyncData> for
response: Option<
types::RouterData<F, types::PaymentsSyncData, types::PaymentsResponseData>,
>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
- Ok(payment_response_ut(db, payment_id, payment_data, response).await?)
+ Ok(payment_response_ut(db, payment_id, payment_data, response, storage_scheme).await?)
}
}
@@ -78,11 +87,12 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCaptureData>
response: Option<
types::RouterData<F, types::PaymentsCaptureData, types::PaymentsResponseData>,
>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
- Ok(payment_response_ut(db, payment_id, payment_data, response).await?)
+ Ok(payment_response_ut(db, payment_id, payment_data, response, storage_scheme).await?)
}
}
@@ -96,11 +106,12 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::PaymentsCancelData> f
response: Option<
types::RouterData<F, types::PaymentsCancelData, types::PaymentsResponseData>,
>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
- Ok(payment_response_ut(db, payment_id, payment_data, response).await?)
+ Ok(payment_response_ut(db, payment_id, payment_data, response, storage_scheme).await?)
}
}
@@ -114,11 +125,12 @@ impl<F: Clone> PostUpdateTracker<F, PaymentData<F>, types::VerifyRequestData> fo
response: Option<
types::RouterData<F, types::VerifyRequestData, types::PaymentsResponseData>,
>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentData<F>>
where
F: 'b + Send,
{
- Ok(payment_response_ut(db, payment_id, payment_data, response).await?)
+ Ok(payment_response_ut(db, payment_id, payment_data, response, storage_scheme).await?)
}
}
@@ -127,6 +139,7 @@ async fn payment_response_ut<F: Clone, T>(
_payment_id: &api::PaymentIdType,
mut payment_data: PaymentData<F>,
response: Option<types::RouterData<F, T, types::PaymentsResponseData>>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<PaymentData<F>> {
let router_data = response.ok_or(report!(errors::ApiErrorResponse::InternalServerError))?;
let mut connector_response_data = None;
@@ -156,7 +169,11 @@ async fn payment_response_ut<F: Clone, T>(
};
payment_data.payment_attempt = db
- .update_payment_attempt(payment_data.payment_attempt, payment_attempt_update)
+ .update_payment_attempt(
+ payment_data.payment_attempt,
+ payment_attempt_update,
+ storage_scheme,
+ )
.await
.map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))?;
@@ -180,11 +197,15 @@ async fn payment_response_ut<F: Clone, T>(
encoded_data: payment_data.connector_response.encoded_data.clone(),
};
- db.update_connector_response(payment_data.connector_response, connector_response_update)
- .await
- .map_err(|error| {
- error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
- })?
+ db.update_connector_response(
+ payment_data.connector_response,
+ connector_response_update,
+ storage_scheme,
+ )
+ .await
+ .map_err(|error| {
+ error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
+ })?
}
None => payment_data.connector_response,
};
@@ -201,7 +222,11 @@ async fn payment_response_ut<F: Clone, T>(
};
payment_data.payment_intent = db
- .update_payment_intent(payment_data.payment_intent, payment_intent_update)
+ .update_payment_intent(
+ payment_data.payment_intent,
+ payment_intent_update,
+ storage_scheme,
+ )
.await
.map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))?;
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index b08cbb76b40..dcb42902202 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -9,7 +9,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
- payments::{self, helpers, PaymentData},
+ payments::{self, helpers, operations, PaymentData},
},
db::StorageInterface,
routes::AppState,
@@ -38,6 +38,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
_connector: Connector,
request: &api::PaymentsSessionRequest,
_mandate_type: Option<api::MandateTxnType>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsSessionRequest>,
PaymentData<F>,
@@ -50,14 +51,18 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
let db = &*state.store;
let mut payment_attempt = db
- .find_payment_attempt_by_payment_id_merchant_id(&payment_id, merchant_id)
+ .find_payment_attempt_by_payment_id_merchant_id(
+ &payment_id,
+ merchant_id,
+ storage_scheme,
+ )
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
})?;
let mut payment_intent = db
- .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id)
+ .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id, storage_scheme)
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
@@ -81,6 +86,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
payment_intent.shipping_address_id.as_deref(),
)
.await?;
+
let billing_address = helpers::get_address_for_payment_request(
db,
None,
@@ -97,6 +103,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
&payment_intent.payment_id,
&payment_intent.merchant_id,
&payment_attempt.txn_id,
+ storage_scheme,
)
.await
.map_err(|error| {
@@ -140,6 +147,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for
_payment_id: &api::PaymentIdType,
payment_data: PaymentData<F>,
_customer: Option<storage::Customer>,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsSessionRequest>,
PaymentData<F>,
@@ -159,9 +167,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsSessionRequest> for Paymen
merchant_account: &'a storage::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsSessionRequest>,
- &'a str,
- api::PaymentIdType,
- Option<api::MandateTxnType>,
+ operations::ValidateResult<'a>,
)> {
//paymentid is already generated and should be sent in the request
let given_payment_id = request
@@ -171,9 +177,12 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsSessionRequest> for Paymen
Ok((
Box::new(self),
- &merchant_account.merchant_id,
- api::PaymentIdType::PaymentIntentId(given_payment_id),
- None,
+ operations::ValidateResult {
+ merchant_id: &merchant_account.merchant_id,
+ payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id),
+ mandate_type: None,
+ storage_scheme: merchant_account.storage_scheme,
+ },
))
}
}
@@ -217,6 +226,7 @@ where
_payment_attempt: &storage::PaymentAttempt,
_request: &Option<api::PaymentMethod>,
_token: &Option<String>,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsSessionRequest>,
Option<api::PaymentMethod>,
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 71afd4a6a2c..9e95f42b1fb 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -9,7 +9,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
- payments::{helpers, CustomerDetails, PaymentAddress, PaymentData},
+ payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
db::StorageInterface,
routes::AppState,
@@ -36,6 +36,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f
_connector: Connector,
_request: &api::PaymentsStartRequest,
_mandate_type: Option<api::MandateTxnType>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsStartRequest>,
PaymentData<F>,
@@ -49,14 +50,18 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
payment_intent = db
- .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id)
+ .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id, storage_scheme)
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
})?;
payment_attempt = db
- .find_payment_attempt_by_payment_id_merchant_id(&payment_id, merchant_id)
+ .find_payment_attempt_by_payment_id_merchant_id(
+ &payment_id,
+ merchant_id,
+ storage_scheme,
+ )
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
@@ -95,6 +100,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f
&payment_intent.payment_id,
&payment_intent.merchant_id,
&payment_attempt.txn_id,
+ storage_scheme,
)
.await
.map_err(|error| {
@@ -147,6 +153,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsStartRequest> for P
_payment_id: &api::PaymentIdType,
payment_data: PaymentData<F>,
_customer: Option<Customer>,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsStartRequest>,
PaymentData<F>,
@@ -166,9 +173,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsStartRequest> for PaymentS
merchant_account: &'a storage::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsStartRequest>,
- &'a str,
- api::PaymentIdType,
- Option<api::MandateTxnType>,
+ operations::ValidateResult<'a>,
)> {
let request_merchant_id = Some(&request.merchant_id[..]);
helpers::validate_merchant_id(&merchant_account.merchant_id, request_merchant_id)
@@ -181,9 +186,12 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsStartRequest> for PaymentS
Ok((
Box::new(self),
- &merchant_account.merchant_id,
- api::PaymentIdType::PaymentIntentId(payment_id),
- None,
+ operations::ValidateResult {
+ merchant_id: &merchant_account.merchant_id,
+ payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
+ mandate_type: None,
+ storage_scheme: merchant_account.storage_scheme,
+ },
))
}
}
@@ -227,6 +235,7 @@ where
payment_attempt: &storage::PaymentAttempt,
request: &Option<api::PaymentMethod>,
token: &Option<String>,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsStartRequest>,
Option<api::PaymentMethod>,
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index cdb9ef36382..3034f247681 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -9,11 +9,15 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, ApiErrorResponse, RouterResult, StorageErrorExt},
- payments::{helpers, CustomerDetails, PaymentAddress, PaymentData},
+ payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
db::StorageInterface,
routes::AppState,
- types::{api, storage, Connector},
+ types::{
+ api,
+ storage::{self, enums},
+ Connector,
+ },
utils::{self, OptionExt},
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
@@ -51,6 +55,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
_payment_id: &api::PaymentIdType,
payment_data: PaymentData<F>,
_customer: Option<storage::Customer>,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
where
F: 'b + Send,
@@ -67,6 +72,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest> fo
_payment_id: &api::PaymentIdType,
payment_data: PaymentData<F>,
_customer: Option<storage::Customer>,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRetrieveRequest>,
PaymentData<F>,
@@ -91,12 +97,21 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRetrieveRequest
_connector: Connector,
request: &api::PaymentsRetrieveRequest,
_mandate_type: Option<api::MandateTxnType>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRetrieveRequest>,
PaymentData<F>,
Option<CustomerDetails>,
)> {
- get_tracker_for_sync(payment_id, merchant_id, &*state.store, request, self).await
+ get_tracker_for_sync(
+ payment_id,
+ merchant_id,
+ &*state.store,
+ request,
+ self,
+ storage_scheme,
+ )
+ .await
}
}
@@ -110,6 +125,7 @@ async fn get_tracker_for_sync<
db: &dyn StorageInterface,
request: &api::PaymentsRetrieveRequest,
operation: Op,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRetrieveRequest>,
PaymentData<F>,
@@ -119,13 +135,13 @@ async fn get_tracker_for_sync<
payment_attempt = match payment_id {
api::PaymentIdType::PaymentIntentId(ref id) => {
- db.find_payment_attempt_by_payment_id_merchant_id(id, merchant_id)
+ db.find_payment_attempt_by_payment_id_merchant_id(id, merchant_id, storage_scheme)
}
api::PaymentIdType::ConnectorTransactionId(ref id) => {
- db.find_payment_attempt_by_merchant_id_connector_txn_id(merchant_id, id)
+ db.find_payment_attempt_by_merchant_id_connector_txn_id(merchant_id, id, storage_scheme)
}
api::PaymentIdType::PaymentTxnId(ref id) => {
- db.find_payment_attempt_by_merchant_id_txn_id(merchant_id, id)
+ db.find_payment_attempt_by_merchant_id_txn_id(merchant_id, id, storage_scheme)
}
}
.await
@@ -134,7 +150,7 @@ async fn get_tracker_for_sync<
let payment_id_str = payment_attempt.payment_id.clone();
payment_intent = db
- .find_payment_intent_by_payment_id_merchant_id(&payment_id_str, merchant_id)
+ .find_payment_intent_by_payment_id_merchant_id(&payment_id_str, merchant_id, storage_scheme)
.await
.map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))?;
@@ -143,6 +159,7 @@ async fn get_tracker_for_sync<
&payment_intent.payment_id,
&payment_intent.merchant_id,
&payment_attempt.txn_id,
+ storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -168,7 +185,7 @@ async fn get_tracker_for_sync<
)?;
let refunds = db
- .find_refund_by_payment_id_merchant_id(&payment_id_str, merchant_id)
+ .find_refund_by_payment_id_merchant_id(&payment_id_str, merchant_id, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
@@ -204,9 +221,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRetrieveRequest> for Payme
merchant_account: &'a storage::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRetrieveRequest>,
- &'a str,
- api::PaymentIdType,
- Option<api::MandateTxnType>,
+ operations::ValidateResult<'a>,
)> {
let request_merchant_id = request.merchant_id.as_deref();
helpers::validate_merchant_id(&merchant_account.merchant_id, request_merchant_id)
@@ -217,9 +232,12 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRetrieveRequest> for Payme
Ok((
Box::new(self),
- &merchant_account.merchant_id,
- request.resource_id.clone(),
- None,
+ operations::ValidateResult {
+ merchant_id: &merchant_account.merchant_id,
+ payment_id: request.resource_id.clone(),
+ mandate_type: None,
+ storage_scheme: merchant_account.storage_scheme,
+ },
))
}
}
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index b2aa0f98737..5d43e35c4e4 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -9,7 +9,7 @@ use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, Valida
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
- payments::{self, helpers, CustomerDetails, PaymentAddress, PaymentData},
+ payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
utils as core_utils,
},
db::StorageInterface,
@@ -36,6 +36,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
_connector: Connector,
request: &api::PaymentsRequest,
mandate_type: Option<api::MandateTxnType>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(
BoxedOperation<'a, F, api::PaymentsRequest>,
PaymentData<F>,
@@ -58,7 +59,11 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.await?;
payment_attempt = db
- .find_payment_attempt_by_payment_id_merchant_id(&payment_id, merchant_id)
+ .find_payment_attempt_by_payment_id_merchant_id(
+ &payment_id,
+ merchant_id,
+ storage_scheme,
+ )
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
@@ -78,7 +83,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
amount = request.amount.unwrap_or(payment_attempt.amount);
payment_intent = db
- .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id)
+ .find_payment_intent_by_payment_id_merchant_id(&payment_id, merchant_id, storage_scheme)
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
@@ -114,6 +119,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
&payment_intent.payment_id,
&payment_intent.merchant_id,
&payment_attempt.txn_id,
+ storage_scheme,
)
.await
.map_err(|error| {
@@ -172,6 +178,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
_payment_id: &api::PaymentIdType,
mut payment_data: PaymentData<F>,
customer: Option<storage::Customer>,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(BoxedOperation<'b, F, api::PaymentsRequest>, PaymentData<F>)>
where
F: 'b + Send,
@@ -200,6 +207,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
authentication_type: None,
payment_method,
},
+ storage_scheme,
)
.await
.map_err(|error| {
@@ -235,6 +243,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
shipping_address_id: shipping_address,
billing_address_id: billing_address,
},
+ storage_scheme,
)
.await
.map_err(|error| {
@@ -258,9 +267,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate
merchant_account: &'a storage::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRequest>,
- &'a str,
- api::PaymentIdType,
- Option<api::MandateTxnType>,
+ operations::ValidateResult<'a>,
)> {
let given_payment_id = match &request.payment_id {
Some(id_type) => Some(
@@ -291,9 +298,12 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate
Ok((
Box::new(self),
- &merchant_account.merchant_id,
- api::PaymentIdType::PaymentIntentId(payment_id),
- mandate_type,
+ operations::ValidateResult {
+ merchant_id: &merchant_account.merchant_id,
+ payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
+ mandate_type,
+ storage_scheme: merchant_account.storage_scheme,
+ },
))
}
}
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index c6d590265d3..de1c44a989f 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -38,6 +38,7 @@ pub async fn refund_create_core(
.find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&req.payment_id,
merchant_id,
+ merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?;
@@ -56,7 +57,11 @@ pub async fn refund_create_core(
)?;
payment_intent = db
- .find_payment_intent_by_payment_id_merchant_id(&req.payment_id, merchant_id)
+ .find_payment_intent_by_payment_id_merchant_id(
+ &req.payment_id,
+ merchant_id,
+ merchant_account.storage_scheme,
+ )
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
@@ -142,7 +147,11 @@ pub async fn trigger_refund_to_gateway(
let response = state
.store
- .update_refund(refund.to_owned(), refund_update)
+ .update_refund(
+ refund.to_owned(),
+ refund_update,
+ merchant_account.storage_scheme,
+ )
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(response)
@@ -162,13 +171,21 @@ pub async fn refund_retrieve_core(
merchant_id = &merchant_account.merchant_id;
refund = db
- .find_refund_by_merchant_id_refund_id(merchant_id, refund_id.as_str())
+ .find_refund_by_merchant_id_refund_id(
+ merchant_id,
+ refund_id.as_str(),
+ merchant_account.storage_scheme,
+ )
.await
.map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::RefundNotFound))?;
let payment_id = refund.payment_id.as_str();
payment_intent = db
- .find_payment_intent_by_payment_id_merchant_id(payment_id, merchant_id)
+ .find_payment_intent_by_payment_id_merchant_id(
+ payment_id,
+ merchant_id,
+ merchant_account.storage_scheme,
+ )
.await
.map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))?;
@@ -177,6 +194,7 @@ pub async fn refund_retrieve_core(
&refund.transaction_id,
payment_id,
merchant_id,
+ merchant_account.storage_scheme,
)
.await
.map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound))?;
@@ -251,7 +269,11 @@ pub async fn sync_refund_with_gateway(
let response = state
.store
- .update_refund(refund.to_owned(), refund_update)
+ .update_refund(
+ refund.to_owned(),
+ refund_update,
+ merchant_account.storage_scheme,
+ )
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
Ok(response)
@@ -266,7 +288,11 @@ pub async fn refund_update_core(
req: refunds::RefundRequest,
) -> RouterResponse<refunds::RefundResponse> {
let refund = db
- .find_refund_by_merchant_id_refund_id(&merchant_account.merchant_id, refund_id)
+ .find_refund_by_merchant_id_refund_id(
+ &merchant_account.merchant_id,
+ refund_id,
+ merchant_account.storage_scheme,
+ )
.await
.map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::RefundNotFound))?;
@@ -276,6 +302,7 @@ pub async fn refund_update_core(
storage::RefundUpdate::MetadataUpdate {
metadata: req.metadata,
},
+ merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
@@ -323,6 +350,7 @@ pub async fn validate_and_create_refund(
&payment_intent.payment_id,
&merchant_account.merchant_id,
&refund_id,
+ merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?
@@ -338,6 +366,7 @@ pub async fn validate_and_create_refund(
.find_refund_by_merchant_id_transaction_id(
&merchant_account.merchant_id,
connecter_transaction_id,
+ merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::RefundNotFound)
@@ -371,9 +400,12 @@ pub async fn validate_and_create_refund(
refund_amount,
);
- refund = db.insert_refund(refund_create_req).await.map_err(|error| {
- error.to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest)
- })?;
+ refund = db
+ .insert_refund(refund_create_req, merchant_account.storage_scheme)
+ .await
+ .map_err(|error| {
+ error.to_duplicate_response(errors::ApiErrorResponse::DuplicateRefundRequest)
+ })?;
schedule_refund_execution(
state,
refund,
@@ -548,11 +580,20 @@ pub async fn sync_refund_with_gateway_workflow(
refund_tracker.tracking_data
)
})?;
+
+ let merchant_account = db
+ .find_merchant_account_by_merchant_id(&refund_core.merchant_id)
+ .await
+ .map_err(|error| {
+ error.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
+ })?;
+
// FIXME we actually don't use this?
let _refund = db
.find_refund_by_internal_reference_id_merchant_id(
&refund_core.refund_internal_reference_id,
&refund_core.merchant_id,
+ merchant_account.storage_scheme,
)
.await
.map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::RefundNotFound))?;
@@ -592,43 +633,55 @@ pub async fn trigger_refund_execute_workflow(
refund_tracker.tracking_data
)
})?;
+
+ let merchant_account = db
+ .find_merchant_account_by_merchant_id(&refund_core.merchant_id)
+ .await
+ .map_err(|error| {
+ error.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
+ })?;
+
let refund = db
.find_refund_by_internal_reference_id_merchant_id(
&refund_core.refund_internal_reference_id,
&refund_core.merchant_id,
+ merchant_account.storage_scheme,
)
.await
.map_err(|error| error.to_not_found_response(errors::ApiErrorResponse::RefundNotFound))?;
match (&refund.sent_to_gateway, &refund.refund_status) {
//FIXME: Conversion should come from trait
(false, enums::RefundStatus::Pending) => {
+ let merchant_account = db
+ .find_merchant_account_by_merchant_id(&refund.merchant_id)
+ .await
+ .map_err(|error| {
+ error.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
+ })?;
+
let payment_attempt = db
.find_payment_attempt_by_transaction_id_payment_id_merchant_id(
&refund.transaction_id,
&refund_core.payment_id,
&refund.merchant_id,
+ merchant_account.storage_scheme,
)
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
})?;
+
let payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
&payment_attempt.payment_id,
&refund.merchant_id,
+ merchant_account.storage_scheme,
)
.await
.map_err(|error| {
error.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)
})?;
- let merchant_account = db
- .find_merchant_account_by_merchant_id(&refund.merchant_id)
- .await
- .map_err(|error| {
- error.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
- })?;
-
//trigger refund request to gateway
let updated_refund = trigger_refund_to_gateway(
state,
diff --git a/crates/router/src/core/refunds/validator.rs b/crates/router/src/core/refunds/validator.rs
index 586f6b09493..056a4ef058a 100644
--- a/crates/router/src/core/refunds/validator.rs
+++ b/crates/router/src/core/refunds/validator.rs
@@ -95,9 +95,10 @@ pub async fn validate_uniqueness_of_refund_id_against_merchant_id(
payment_id: &str,
merchant_id: &str,
refund_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<Option<storage::Refund>> {
let refund = db
- .find_refund_by_merchant_id_refund_id(merchant_id, refund_id)
+ .find_refund_by_merchant_id_refund_id(merchant_id, refund_id, storage_scheme)
.await;
logger::debug!(?refund);
match refund {
diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs
index 26ce838ee1f..522ac70a994 100644
--- a/crates/router/src/db/address.rs
+++ b/crates/router/src/db/address.rs
@@ -16,6 +16,7 @@ pub trait AddressInterface {
&self,
address: AddressNew,
) -> CustomResult<Address, errors::StorageError>;
+
async fn find_address(&self, address_id: &str) -> CustomResult<Address, errors::StorageError>;
}
diff --git a/crates/router/src/db/connector_response.rs b/crates/router/src/db/connector_response.rs
index 0cd8091ff6a..cc68e2b9ad0 100644
--- a/crates/router/src/db/connector_response.rs
+++ b/crates/router/src/db/connector_response.rs
@@ -2,7 +2,7 @@ use super::MockDb;
use crate::{
connection::pg_connection,
core::errors::{self, CustomResult},
- types::storage::{ConnectorResponse, ConnectorResponseNew, ConnectorResponseUpdate},
+ types::storage::{enums, ConnectorResponse, ConnectorResponseNew, ConnectorResponseUpdate},
};
#[async_trait::async_trait]
@@ -10,17 +10,22 @@ pub trait ConnectorResponseInterface {
async fn insert_connector_response(
&self,
connector_response: ConnectorResponseNew,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ConnectorResponse, errors::StorageError>;
+
async fn find_connector_response_by_payment_id_merchant_id_txn_id(
&self,
payment_id: &str,
merchant_id: &str,
txn_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ConnectorResponse, errors::StorageError>;
+
async fn update_connector_response(
&self,
this: ConnectorResponse,
payment_attempt: ConnectorResponseUpdate,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ConnectorResponse, errors::StorageError>;
}
@@ -29,6 +34,7 @@ impl ConnectorResponseInterface for super::Store {
async fn insert_connector_response(
&self,
connector_response: ConnectorResponseNew,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ConnectorResponse, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
connector_response.insert(&conn).await
@@ -39,6 +45,7 @@ impl ConnectorResponseInterface for super::Store {
payment_id: &str,
merchant_id: &str,
txn_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ConnectorResponse, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
ConnectorResponse::find_by_payment_id_and_merchant_id_transaction_id(
@@ -54,6 +61,7 @@ impl ConnectorResponseInterface for super::Store {
&self,
this: ConnectorResponse,
connector_response_update: ConnectorResponseUpdate,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ConnectorResponse, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
this.update(&conn, connector_response_update).await
@@ -65,6 +73,7 @@ impl ConnectorResponseInterface for MockDb {
async fn insert_connector_response(
&self,
new: ConnectorResponseNew,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ConnectorResponse, errors::StorageError> {
let mut connector_response = self.connector_response.lock().await;
let response = ConnectorResponse {
@@ -88,6 +97,7 @@ impl ConnectorResponseInterface for MockDb {
_payment_id: &str,
_merchant_id: &str,
_txn_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ConnectorResponse, errors::StorageError> {
todo!()
}
@@ -96,6 +106,7 @@ impl ConnectorResponseInterface for MockDb {
&self,
this: ConnectorResponse,
connector_response_update: ConnectorResponseUpdate,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ConnectorResponse, errors::StorageError> {
let mut connector_response = self.connector_response.lock().await;
let response = connector_response
diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs
index 3390c0e463d..435e9e88c30 100644
--- a/crates/router/src/db/merchant_account.rs
+++ b/crates/router/src/db/merchant_account.rs
@@ -5,7 +5,7 @@ use super::MockDb;
use crate::{
connection::pg_connection,
core::errors::{self, CustomResult, DatabaseError, StorageError},
- types::storage::{MerchantAccount, MerchantAccountNew, MerchantAccountUpdate},
+ types::storage::{enums, MerchantAccount, MerchantAccountNew, MerchantAccountUpdate},
};
#[async_trait::async_trait]
@@ -122,6 +122,7 @@ impl MerchantAccountInterface for MockDb {
sub_merchants_enabled: merchant_account.sub_merchants_enabled,
parent_merchant_id: merchant_account.parent_merchant_id,
publishable_key: merchant_account.publishable_key,
+ storage_scheme: enums::MerchantStorageScheme::PostgresOnly,
};
accounts.push(account.clone());
Ok(account)
diff --git a/crates/router/src/db/payment_attempt.rs b/crates/router/src/db/payment_attempt.rs
index 73c31c71f35..322891c6f01 100644
--- a/crates/router/src/db/payment_attempt.rs
+++ b/crates/router/src/db/payment_attempt.rs
@@ -1,7 +1,7 @@
use super::MockDb;
use crate::{
core::errors::{self, CustomResult},
- types::storage::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
+ types::storage::{enums, PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
};
#[async_trait::async_trait]
@@ -9,18 +9,21 @@ pub trait PaymentAttemptInterface {
async fn insert_payment_attempt(
&self,
payment_attempt: PaymentAttemptNew,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError>;
async fn update_payment_attempt(
&self,
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError>;
async fn find_payment_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
merchant_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError>;
async fn find_payment_attempt_by_transaction_id_payment_id_merchant_id(
@@ -28,24 +31,28 @@ pub trait PaymentAttemptInterface {
transaction_id: &str,
payment_id: &str,
merchant_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError>;
async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
merchant_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError>;
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
merchant_id: &str,
connector_txn_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError>;
async fn find_payment_attempt_by_merchant_id_txn_id(
&self,
merchant_id: &str,
txn_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError>;
}
@@ -56,7 +63,7 @@ mod storage {
connection::pg_connection,
core::errors::{self, CustomResult},
services::Store,
- types::storage::payment_attempt::*,
+ types::storage::{enums, payment_attempt::*},
};
#[async_trait::async_trait]
@@ -64,6 +71,7 @@ mod storage {
async fn insert_payment_attempt(
&self,
payment_attempt: PaymentAttemptNew,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
payment_attempt.insert_diesel(&conn).await
@@ -73,6 +81,7 @@ mod storage {
&self,
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
this.update(&conn, payment_attempt).await
@@ -82,6 +91,7 @@ mod storage {
&self,
payment_id: &str,
merchant_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
PaymentAttempt::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id).await
@@ -92,6 +102,7 @@ mod storage {
transaction_id: &str,
payment_id: &str,
merchant_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
PaymentAttempt::find_by_transaction_id_payment_id_merchant_id(
@@ -107,6 +118,7 @@ mod storage {
&self,
payment_id: &str,
merchant_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
PaymentAttempt::find_last_successful_attempt_by_payment_id_merchant_id(
@@ -121,6 +133,7 @@ mod storage {
&self,
merchant_id: &str,
connector_txn_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
// TODO: update logic to lookup all payment attempts for an intent
@@ -137,6 +150,7 @@ mod storage {
&self,
merchant_id: &str,
txn_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
@@ -151,6 +165,7 @@ impl PaymentAttemptInterface for MockDb {
&self,
_merchant_id: &str,
_txn_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
todo!()
}
@@ -159,6 +174,7 @@ impl PaymentAttemptInterface for MockDb {
&self,
_merchant_id: &str,
_connector_txn_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
todo!()
}
@@ -167,6 +183,7 @@ impl PaymentAttemptInterface for MockDb {
async fn insert_payment_attempt(
&self,
payment_attempt: PaymentAttemptNew,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let mut payment_attempts = self.payment_attempts.lock().await;
let id = payment_attempts.len() as i32;
@@ -211,6 +228,7 @@ impl PaymentAttemptInterface for MockDb {
&self,
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let mut payment_attempts = self.payment_attempts.lock().await;
@@ -228,6 +246,7 @@ impl PaymentAttemptInterface for MockDb {
&self,
_payment_id: &str,
_merchant_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
todo!()
}
@@ -237,6 +256,7 @@ impl PaymentAttemptInterface for MockDb {
_transaction_id: &str,
_payment_id: &str,
_merchant_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
todo!()
}
@@ -245,6 +265,7 @@ impl PaymentAttemptInterface for MockDb {
&self,
payment_id: &str,
merchant_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let payment_attempts = self.payment_attempts.lock().await;
@@ -280,69 +301,142 @@ mod storage {
async fn insert_payment_attempt(
&self,
payment_attempt: PaymentAttemptNew,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let key = format!(
- "{}_{}",
- payment_attempt.payment_id, payment_attempt.merchant_id
- );
- // 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_attempt = PaymentAttempt {
- id: 0i32,
- payment_id: payment_attempt.payment_id.clone(),
- merchant_id: payment_attempt.merchant_id.clone(),
- txn_id: payment_attempt.txn_id.clone(),
- status: payment_attempt.status,
- amount: payment_attempt.amount,
- currency: payment_attempt.currency,
- save_to_locker: payment_attempt.save_to_locker,
- connector: payment_attempt.connector.clone(),
- error_message: payment_attempt.error_message.clone(),
- offer_amount: payment_attempt.offer_amount,
- surcharge_amount: payment_attempt.surcharge_amount,
- tax_amount: payment_attempt.tax_amount,
- payment_method_id: payment_attempt.payment_method_id.clone(),
- payment_method: payment_attempt.payment_method,
- payment_flow: payment_attempt.payment_flow,
- redirect: payment_attempt.redirect,
- connector_transaction_id: payment_attempt.connector_transaction_id.clone(),
- capture_method: payment_attempt.capture_method,
- capture_on: payment_attempt.capture_on,
- confirm: payment_attempt.confirm,
- authentication_type: payment_attempt.authentication_type,
- created_at: payment_attempt.created_at.unwrap_or_else(date_time::now),
- modified_at: payment_attempt.created_at.unwrap_or_else(date_time::now),
- last_synced: payment_attempt.last_synced,
- amount_to_capture: payment_attempt.amount_to_capture,
- cancellation_reason: payment_attempt.cancellation_reason.clone(),
- mandate_id: payment_attempt.mandate_id.clone(),
- browser_info: payment_attempt.browser_info.clone(),
- };
- // TODO: Add a proper error for serialization failure
- let redis_value = serde_json::to_string(&created_attempt)
- .into_report()
- .change_context(errors::StorageError::KVError)?;
- match self
- .redis_conn
- .pool
- .hsetnx::<u8, &str, &str, &str>(&key, "pa", &redis_value)
- .await
- {
- Ok(0) => Err(errors::StorageError::DuplicateValue(format!(
- "Payment Attempt already exists for payment_id: {}",
- key
- )))
- .into_report(),
- Ok(1) => {
+ match storage_scheme {
+ enums::MerchantStorageScheme::PostgresOnly => {
+ let conn = pg_connection(&self.master_pool).await;
+ payment_attempt.insert_diesel(&conn).await
+ }
+
+ enums::MerchantStorageScheme::RedisKv => {
+ let key = format!(
+ "{}_{}",
+ payment_attempt.payment_id, payment_attempt.merchant_id
+ );
+ // 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_attempt = PaymentAttempt {
+ id: 0i32,
+ payment_id: payment_attempt.payment_id.clone(),
+ merchant_id: payment_attempt.merchant_id.clone(),
+ txn_id: payment_attempt.txn_id.clone(),
+ status: payment_attempt.status,
+ amount: payment_attempt.amount,
+ currency: payment_attempt.currency,
+ save_to_locker: payment_attempt.save_to_locker,
+ connector: payment_attempt.connector.clone(),
+ error_message: payment_attempt.error_message.clone(),
+ offer_amount: payment_attempt.offer_amount,
+ surcharge_amount: payment_attempt.surcharge_amount,
+ tax_amount: payment_attempt.tax_amount,
+ payment_method_id: payment_attempt.payment_method_id.clone(),
+ payment_method: payment_attempt.payment_method,
+ payment_flow: payment_attempt.payment_flow,
+ redirect: payment_attempt.redirect,
+ connector_transaction_id: payment_attempt.connector_transaction_id.clone(),
+ capture_method: payment_attempt.capture_method,
+ capture_on: payment_attempt.capture_on,
+ confirm: payment_attempt.confirm,
+ authentication_type: payment_attempt.authentication_type,
+ created_at: payment_attempt.created_at.unwrap_or_else(date_time::now),
+ modified_at: payment_attempt.created_at.unwrap_or_else(date_time::now),
+ last_synced: payment_attempt.last_synced,
+ amount_to_capture: payment_attempt.amount_to_capture,
+ cancellation_reason: payment_attempt.cancellation_reason.clone(),
+ mandate_id: payment_attempt.mandate_id.clone(),
+ browser_info: payment_attempt.browser_info.clone(),
+ };
+ // TODO: Add a proper error for serialization failure
+ let redis_value = serde_json::to_string(&created_attempt)
+ .into_report()
+ .change_context(errors::StorageError::KVError)?;
+ match self
+ .redis_conn
+ .pool
+ .hsetnx::<u8, &str, &str, &str>(&key, "pa", &redis_value)
+ .await
+ {
+ Ok(0) => Err(errors::StorageError::DuplicateValue(format!(
+ "Payment Attempt already exists for payment_id: {}",
+ key
+ )))
+ .into_report(),
+ Ok(1) => {
+ let conn = pg_connection(&self.master_pool).await;
+ let query = payment_attempt
+ .insert_diesel_query(&conn)
+ .await
+ .change_context(errors::StorageError::KVError)?;
+ let stream_name = self.drainer_stream(&PaymentAttempt::shard_key(
+ crate::utils::storage_partitioning::PartitionKey::MerchantIdPaymentId {
+ merchant_id: &created_attempt.merchant_id,
+ payment_id: &created_attempt.payment_id,
+ },
+ self.config.drainer_num_partitions,
+ ));
+ self.redis_conn
+ .stream_append_entry(
+ &stream_name,
+ &RedisEntryId::AutoGeneratedID,
+ query.to_field_value_pairs(),
+ )
+ .await
+ .change_context(errors::StorageError::KVError)?;
+ Ok(created_attempt)
+ }
+ Ok(i) => Err(errors::StorageError::KVError)
+ .into_report()
+ .attach_printable_lazy(|| {
+ format!("Invalid response for HSETNX: {}", i)
+ }),
+ Err(er) => Err(er)
+ .into_report()
+ .change_context(errors::StorageError::KVError),
+ }
+ }
+ }
+ }
+
+ async fn update_payment_attempt(
+ &self,
+ this: PaymentAttempt,
+ payment_attempt: PaymentAttemptUpdate,
+ storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<PaymentAttempt, errors::StorageError> {
+ match storage_scheme {
+ enums::MerchantStorageScheme::PostgresOnly => {
+ let conn = pg_connection(&self.master_pool).await;
+ this.update(&conn, payment_attempt).await
+ }
+
+ enums::MerchantStorageScheme::RedisKv => {
+ let key = format!("{}_{}", this.payment_id, this.merchant_id);
+
+ let updated_attempt = payment_attempt.clone().apply_changeset(this.clone());
+ // Check for database presence as well Maybe use a read replica here ?
+ // TODO: Add a proper error for serialization failure
+ let redis_value = serde_json::to_string(&updated_attempt)
+ .into_report()
+ .change_context(errors::StorageError::KVError)?;
+ let updated_attempt = self
+ .redis_conn
+ .pool
+ .hset::<u8, &str, (&str, String)>(&key, ("pa", redis_value))
+ .await
+ .map(|_| updated_attempt)
+ .into_report()
+ .change_context(errors::StorageError::KVError)?;
+
let conn = pg_connection(&self.master_pool).await;
- let query = payment_attempt
- .insert_diesel(&conn)
+ let query = this
+ .update_query(&conn, payment_attempt)
.await
.change_context(errors::StorageError::KVError)?;
let stream_name = self.drainer_stream(&PaymentAttempt::shard_key(
crate::utils::storage_partitioning::PartitionKey::MerchantIdPaymentId {
- merchant_id: &created_attempt.merchant_id,
- payment_id: &created_attempt.payment_id,
+ merchant_id: &updated_attempt.merchant_id,
+ payment_id: &updated_attempt.payment_id,
},
self.config.drainer_num_partitions,
));
@@ -354,80 +448,40 @@ mod storage {
)
.await
.change_context(errors::StorageError::KVError)?;
- Ok(created_attempt)
+ Ok(updated_attempt)
}
- Ok(i) => Err(errors::StorageError::KVError)
- .into_report()
- .attach_printable_lazy(|| format!("Invalid response for HSETNX: {}", i)),
- Err(er) => Err(er)
- .into_report()
- .change_context(errors::StorageError::KVError),
}
}
- async fn update_payment_attempt(
- &self,
- this: PaymentAttempt,
- payment_attempt: PaymentAttemptUpdate,
- ) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let key = format!("{}_{}", this.payment_id, this.merchant_id);
-
- let updated_attempt = payment_attempt.clone().apply_changeset(this.clone());
- // Check for database presence as well Maybe use a read replica here ?
- // TODO: Add a proper error for serialization failure
- let redis_value = serde_json::to_string(&updated_attempt)
- .into_report()
- .change_context(errors::StorageError::KVError)?;
- let updated_attempt = self
- .redis_conn
- .pool
- .hset::<u8, &str, (&str, String)>(&key, ("pa", redis_value))
- .await
- .map(|_| updated_attempt)
- .into_report()
- .change_context(errors::StorageError::KVError)?;
-
- let conn = pg_connection(&self.master_pool).await;
- let query = this
- .update(&conn, payment_attempt)
- .await
- .change_context(errors::StorageError::KVError)?;
- let stream_name = self.drainer_stream(&PaymentAttempt::shard_key(
- crate::utils::storage_partitioning::PartitionKey::MerchantIdPaymentId {
- merchant_id: &updated_attempt.merchant_id,
- payment_id: &updated_attempt.payment_id,
- },
- self.config.drainer_num_partitions,
- ));
- self.redis_conn
- .stream_append_entry(
- &stream_name,
- &RedisEntryId::AutoGeneratedID,
- query.to_field_value_pairs(),
- )
- .await
- .change_context(errors::StorageError::KVError)?;
- Ok(updated_attempt)
- }
-
async fn find_payment_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
merchant_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
- let key = format!("{}_{}", payment_id, merchant_id);
- self.redis_conn
- .pool
- .hget::<String, String, &str>(key, "pa")
- .await
- .into_report()
- .change_context(errors::StorageError::KVError)
- .and_then(|redis_resp| {
- serde_json::from_str::<PaymentAttempt>(&redis_resp)
+ match storage_scheme {
+ enums::MerchantStorageScheme::PostgresOnly => {
+ let conn = pg_connection(&self.master_pool).await;
+ PaymentAttempt::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id)
+ .await
+ }
+
+ enums::MerchantStorageScheme::RedisKv => {
+ let key = format!("{}_{}", payment_id, merchant_id);
+ self.redis_conn
+ .pool
+ .hget::<String, String, &str>(key, "pa")
+ .await
.into_report()
.change_context(errors::StorageError::KVError)
- })
- // Check for database presence as well Maybe use a read replica here ?
+ .and_then(|redis_resp| {
+ serde_json::from_str::<PaymentAttempt>(&redis_resp)
+ .into_report()
+ .change_context(errors::StorageError::KVError)
+ })
+ // Check for database presence as well Maybe use a read replica here ?
+ }
+ }
}
async fn find_payment_attempt_by_transaction_id_payment_id_merchant_id(
@@ -435,54 +489,92 @@ mod storage {
transaction_id: &str,
payment_id: &str,
merchant_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
// We assume that PaymentAttempt <=> PaymentIntent is a one-to-one relation for now
- self.find_payment_attempt_by_payment_id_merchant_id(payment_id, merchant_id)
- .await
- .and_then(|attempt| {
- if attempt.connector_transaction_id.as_deref() == Some(transaction_id) {
- Ok(attempt)
- } else {
- Err(errors::StorageError::ValueNotFound(format!(
- "Successful payment attempt does not exist for {}_{}",
- payment_id, merchant_id
- )))
- .into_report()
- }
- })
+ self.find_payment_attempt_by_payment_id_merchant_id(
+ payment_id,
+ merchant_id,
+ storage_scheme,
+ )
+ .await
+ .and_then(|attempt| {
+ if attempt.connector_transaction_id.as_deref() == Some(transaction_id) {
+ Ok(attempt)
+ } else {
+ Err(errors::StorageError::ValueNotFound(format!(
+ "Successful payment attempt does not exist for {}_{}",
+ payment_id, merchant_id
+ )))
+ .into_report()
+ }
+ })
}
async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
merchant_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
- self.find_payment_attempt_by_payment_id_merchant_id(payment_id, merchant_id)
- .await
- .and_then(|attempt| match attempt.status {
- enums::AttemptStatus::Charged => Ok(attempt),
- _ => Err(errors::StorageError::ValueNotFound(format!(
- "Successful payment attempt does not exist for {}_{}",
- payment_id, merchant_id
- )))
- .into_report(),
- })
+ self.find_payment_attempt_by_payment_id_merchant_id(
+ payment_id,
+ merchant_id,
+ storage_scheme,
+ )
+ .await
+ .and_then(|attempt| match attempt.status {
+ enums::AttemptStatus::Charged => Ok(attempt),
+ _ => Err(errors::StorageError::ValueNotFound(format!(
+ "Successful payment attempt does not exist for {}_{}",
+ payment_id, merchant_id
+ )))
+ .into_report(),
+ })
}
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
- _merchant_id: &str,
- _connector_txn_id: &str,
+ merchant_id: &str,
+ connector_txn_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
- Err(errors::StorageError::KVError).into_report()
+ match storage_scheme {
+ enums::MerchantStorageScheme::PostgresOnly => {
+ let conn = pg_connection(&self.master_pool).await;
+ // TODO: update logic to lookup all payment attempts for an intent
+ // and apply filter logic on top of them to get the desired one.
+ PaymentAttempt::find_by_merchant_id_connector_txn_id(
+ &conn,
+ merchant_id,
+ connector_txn_id,
+ )
+ .await
+ }
+
+ enums::MerchantStorageScheme::RedisKv => {
+ Err(errors::StorageError::KVError).into_report()
+ }
+ }
}
async fn find_payment_attempt_by_merchant_id_txn_id(
&self,
- _merchant_id: &str,
- _txn_id: &str,
+ merchant_id: &str,
+ txn_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
- Err(errors::StorageError::KVError).into_report()
+ match storage_scheme {
+ enums::MerchantStorageScheme::PostgresOnly => {
+ let conn = pg_connection(&self.master_pool).await;
+ PaymentAttempt::find_by_merchant_id_transaction_id(&conn, merchant_id, txn_id)
+ .await
+ }
+
+ enums::MerchantStorageScheme::RedisKv => {
+ Err(errors::StorageError::KVError).into_report()
+ }
+ }
}
}
}
diff --git a/crates/router/src/db/payment_intent.rs b/crates/router/src/db/payment_intent.rs
index bbb2c4f7765..71ea778b268 100644
--- a/crates/router/src/db/payment_intent.rs
+++ b/crates/router/src/db/payment_intent.rs
@@ -3,7 +3,7 @@ use crate::{
core::errors::{self, CustomResult},
types::{
api,
- storage::{PaymentIntent, PaymentIntentNew, PaymentIntentUpdate},
+ storage::{enums, PaymentIntent, PaymentIntentNew, PaymentIntentUpdate},
},
};
@@ -13,23 +13,27 @@ pub trait PaymentIntentInterface {
&self,
this: PaymentIntent,
payment_intent: PaymentIntentUpdate,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, errors::StorageError>;
async fn insert_payment_intent(
&self,
new: PaymentIntentNew,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, errors::StorageError>;
async fn find_payment_intent_by_payment_id_merchant_id(
&self,
payment_id: &str,
merchant_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, errors::StorageError>;
async fn filter_payment_intent_by_constraints(
&self,
merchant_id: &str,
pc: &api::PaymentListConstraints,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, errors::StorageError>;
}
@@ -45,7 +49,10 @@ mod storage {
connection::pg_connection,
core::errors::{self, CustomResult},
services::Store,
- types::{api, storage::payment_intent::*},
+ types::{
+ api,
+ storage::{enums, payment_intent::*},
+ },
utils::storage_partitioning::KvStorePartition,
};
@@ -54,56 +61,129 @@ mod storage {
async fn insert_payment_intent(
&self,
new: PaymentIntentNew,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, errors::StorageError> {
- let key = format!("{}_{}", new.payment_id, new.merchant_id);
- let created_intent = PaymentIntent {
- id: 0i32,
- payment_id: new.payment_id.clone(),
- merchant_id: new.merchant_id.clone(),
- status: new.status,
- amount: new.amount,
- currency: new.currency,
- amount_captured: new.amount_captured,
- customer_id: new.customer_id.clone(),
- description: new.description.clone(),
- return_url: new.return_url.clone(),
- metadata: new.metadata.clone(),
- connector_id: new.connector_id.clone(),
- shipping_address_id: new.shipping_address_id.clone(),
- billing_address_id: new.billing_address_id.clone(),
- statement_descriptor_name: new.statement_descriptor_name.clone(),
- statement_descriptor_suffix: new.statement_descriptor_suffix.clone(),
- created_at: new.created_at.unwrap_or_else(date_time::now),
- modified_at: new.created_at.unwrap_or_else(date_time::now),
- last_synced: new.last_synced,
- setup_future_usage: new.setup_future_usage,
- off_session: new.off_session,
- client_secret: new.client_secret.clone(),
- };
- // TODO: Add a proper error for serialization failure
- let redis_value = serde_json::to_string(&created_intent)
- .into_report()
- .change_context(errors::StorageError::KVError)?;
- match self
- .redis_conn
- .pool
- .hsetnx::<u8, &str, &str, &str>(&key, "pi", &redis_value)
- .await
- {
- Ok(0) => Err(errors::StorageError::DuplicateValue(format!(
- "Payment Intent already exists for payment_id: {key}"
- )))
- .into_report(),
- Ok(1) => {
+ match storage_scheme {
+ enums::MerchantStorageScheme::PostgresOnly => {
let conn = pg_connection(&self.master_pool).await;
- let query = new
- .insert_diesel(&conn)
+ new.insert_diesel(&conn).await
+ }
+
+ enums::MerchantStorageScheme::RedisKv => {
+ let key = format!("{}_{}", new.payment_id, new.merchant_id);
+ let created_intent = PaymentIntent {
+ id: 0i32,
+ payment_id: new.payment_id.clone(),
+ merchant_id: new.merchant_id.clone(),
+ status: new.status,
+ amount: new.amount,
+ currency: new.currency,
+ amount_captured: new.amount_captured,
+ customer_id: new.customer_id.clone(),
+ description: new.description.clone(),
+ return_url: new.return_url.clone(),
+ metadata: new.metadata.clone(),
+ connector_id: new.connector_id.clone(),
+ shipping_address_id: new.shipping_address_id.clone(),
+ billing_address_id: new.billing_address_id.clone(),
+ statement_descriptor_name: new.statement_descriptor_name.clone(),
+ statement_descriptor_suffix: new.statement_descriptor_suffix.clone(),
+ created_at: new.created_at.unwrap_or_else(date_time::now),
+ modified_at: new.created_at.unwrap_or_else(date_time::now),
+ last_synced: new.last_synced,
+ setup_future_usage: new.setup_future_usage,
+ off_session: new.off_session,
+ client_secret: new.client_secret.clone(),
+ };
+ // TODO: Add a proper error for serialization failure
+ let redis_value = serde_json::to_string(&created_intent)
+ .into_report()
+ .change_context(errors::StorageError::KVError)?;
+ match self
+ .redis_conn
+ .pool
+ .hsetnx::<u8, &str, &str, &str>(&key, "pi", &redis_value)
+ .await
+ {
+ Ok(0) => Err(errors::StorageError::DuplicateValue(format!(
+ "Payment Intent already exists for payment_id: {key}"
+ )))
+ .into_report(),
+ Ok(1) => {
+ let conn = pg_connection(&self.master_pool).await;
+ let query = new
+ .insert_diesel_query(&conn)
+ .await
+ .change_context(errors::StorageError::KVError)?;
+ let stream_name = self.drainer_stream(&PaymentIntent::shard_key(
+ crate::utils::storage_partitioning::PartitionKey::MerchantIdPaymentId {
+ merchant_id: &created_intent.merchant_id,
+ payment_id: &created_intent.payment_id,
+ },
+ self.config.drainer_num_partitions,
+ ));
+ self.redis_conn
+ .stream_append_entry(
+ &stream_name,
+ &RedisEntryId::AutoGeneratedID,
+ query.to_field_value_pairs(),
+ )
+ .await
+ .change_context(errors::StorageError::KVError)?;
+ Ok(created_intent)
+ }
+ Ok(i) => Err(errors::StorageError::KVError)
+ .into_report()
+ .attach_printable_lazy(|| {
+ format!("Invalid response for HSETNX: {}", i)
+ }),
+ Err(er) => Err(er)
+ .into_report()
+ .change_context(errors::StorageError::KVError),
+ }
+ }
+ }
+ }
+
+ async fn update_payment_intent(
+ &self,
+ this: PaymentIntent,
+ payment_intent: PaymentIntentUpdate,
+ storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<PaymentIntent, errors::StorageError> {
+ match storage_scheme {
+ enums::MerchantStorageScheme::PostgresOnly => {
+ let conn = pg_connection(&self.master_pool).await;
+ this.update(&conn, payment_intent).await
+ }
+
+ enums::MerchantStorageScheme::RedisKv => {
+ let key = format!("{}_{}", this.payment_id, this.merchant_id);
+
+ let updated_intent = payment_intent.clone().apply_changeset(this.clone());
+ // Check for database presence as well Maybe use a read replica here ?
+ // TODO: Add a proper error for serialization failure
+ let redis_value = serde_json::to_string(&updated_intent)
+ .into_report()
+ .change_context(errors::StorageError::KVError)?;
+ let updated_intent = self
+ .redis_conn
+ .pool
+ .hset::<u8, &str, (&str, String)>(&key, ("pi", redis_value))
+ .await
+ .map(|_| updated_intent)
+ .into_report()
+ .change_context(errors::StorageError::KVError)?;
+
+ let conn = pg_connection(&self.master_pool).await;
+ let query = this
+ .update_query(&conn, payment_intent)
.await
.change_context(errors::StorageError::KVError)?;
let stream_name = self.drainer_stream(&PaymentIntent::shard_key(
crate::utils::storage_partitioning::PartitionKey::MerchantIdPaymentId {
- merchant_id: &created_intent.merchant_id,
- payment_id: &created_intent.payment_id,
+ merchant_id: &updated_intent.merchant_id,
+ payment_id: &updated_intent.payment_id,
},
self.config.drainer_num_partitions,
));
@@ -115,94 +195,64 @@ mod storage {
)
.await
.change_context(errors::StorageError::KVError)?;
- Ok(created_intent)
+ Ok(updated_intent)
}
- Ok(i) => Err(errors::StorageError::KVError)
- .into_report()
- .attach_printable_lazy(|| format!("Invalid response for HSETNX: {}", i)),
- Err(er) => Err(er)
- .into_report()
- .change_context(errors::StorageError::KVError),
}
}
- async fn update_payment_intent(
- &self,
- this: PaymentIntent,
- payment_intent: PaymentIntentUpdate,
- ) -> CustomResult<PaymentIntent, errors::StorageError> {
- let key = format!("{}_{}", this.payment_id, this.merchant_id);
-
- let updated_intent = payment_intent.clone().apply_changeset(this.clone());
- // Check for database presence as well Maybe use a read replica here ?
- // TODO: Add a proper error for serialization failure
- let redis_value = serde_json::to_string(&updated_intent)
- .into_report()
- .change_context(errors::StorageError::KVError)?;
- let updated_intent = self
- .redis_conn
- .pool
- .hset::<u8, &str, (&str, String)>(&key, ("pi", redis_value))
- .await
- .map(|_| updated_intent)
- .into_report()
- .change_context(errors::StorageError::KVError)?;
-
- let conn = pg_connection(&self.master_pool).await;
- let query = this
- .update(&conn, payment_intent)
- .await
- .change_context(errors::StorageError::KVError)?;
- let stream_name = self.drainer_stream(&PaymentIntent::shard_key(
- crate::utils::storage_partitioning::PartitionKey::MerchantIdPaymentId {
- merchant_id: &updated_intent.merchant_id,
- payment_id: &updated_intent.payment_id,
- },
- self.config.drainer_num_partitions,
- ));
- self.redis_conn
- .stream_append_entry(
- &stream_name,
- &RedisEntryId::AutoGeneratedID,
- query.to_field_value_pairs(),
- )
- .await
- .change_context(errors::StorageError::KVError)?;
- Ok(updated_intent)
- }
-
async fn find_payment_intent_by_payment_id_merchant_id(
&self,
payment_id: &str,
merchant_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, errors::StorageError> {
- let key = format!("{}_{}", payment_id, merchant_id);
- self.redis_conn
- .pool
- .hget::<String, &str, &str>(&key, "pi")
- .await
- .map_err(|err| match err.kind() {
- RedisErrorKind::NotFound => errors::StorageError::ValueNotFound(format!(
- "Payment Intent does not exist for {}",
- key
- )),
- _ => errors::StorageError::KVError,
- })
- .into_report()
- .and_then(|redis_resp| {
- serde_json::from_str::<PaymentIntent>(&redis_resp)
+ match storage_scheme {
+ enums::MerchantStorageScheme::PostgresOnly => {
+ let conn = pg_connection(&self.master_pool).await;
+ PaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id)
+ .await
+ }
+
+ enums::MerchantStorageScheme::RedisKv => {
+ let key = format!("{}_{}", payment_id, merchant_id);
+ self.redis_conn
+ .pool
+ .hget::<String, &str, &str>(&key, "pi")
+ .await
+ .map_err(|err| match err.kind() {
+ RedisErrorKind::NotFound => errors::StorageError::ValueNotFound(
+ format!("Payment Intent does not exist for {}", key),
+ ),
+ _ => errors::StorageError::KVError,
+ })
.into_report()
- .change_context(errors::StorageError::KVError)
- })
- // Check for database presence as well Maybe use a read replica here ?
+ .and_then(|redis_resp| {
+ serde_json::from_str::<PaymentIntent>(&redis_resp)
+ .into_report()
+ .change_context(errors::StorageError::KVError)
+ })
+ // Check for database presence as well Maybe use a read replica here ?
+ }
+ }
}
+
async fn filter_payment_intent_by_constraints(
&self,
- _merchant_id: &str,
- _pc: &api::PaymentListConstraints,
+ merchant_id: &str,
+ pc: &api::PaymentListConstraints,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, errors::StorageError> {
- //TODO: Implement this
- Err(errors::StorageError::KVError.into())
+ match storage_scheme {
+ enums::MerchantStorageScheme::PostgresOnly => {
+ let conn = pg_connection(&self.master_pool).await;
+ PaymentIntent::filter_by_constraints(&conn, merchant_id, pc).await
+ }
+
+ enums::MerchantStorageScheme::RedisKv => {
+ //TODO: Implement this
+ Err(errors::StorageError::KVError.into())
+ }
+ }
}
}
}
@@ -214,7 +264,10 @@ mod storage {
connection::pg_connection,
core::errors::{self, CustomResult},
services::Store,
- types::{api, storage::payment_intent::*},
+ types::{
+ api,
+ storage::{enums, payment_intent::*},
+ },
};
#[async_trait::async_trait]
@@ -222,6 +275,7 @@ mod storage {
async fn insert_payment_intent(
&self,
new: PaymentIntentNew,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
new.insert_diesel(&conn).await
@@ -231,6 +285,7 @@ mod storage {
&self,
this: PaymentIntent,
payment_intent: PaymentIntentUpdate,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
this.update(&conn, payment_intent).await
@@ -240,6 +295,7 @@ mod storage {
&self,
payment_id: &str,
merchant_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
PaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id).await
@@ -249,6 +305,7 @@ mod storage {
&self,
merchant_id: &str,
pc: &api::PaymentListConstraints,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
PaymentIntent::filter_by_constraints(&conn, merchant_id, pc).await
@@ -262,6 +319,7 @@ impl PaymentIntentInterface for MockDb {
&self,
_merchant_id: &str,
_pc: &api::PaymentListConstraints,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, errors::StorageError> {
todo!()
}
@@ -270,6 +328,7 @@ impl PaymentIntentInterface for MockDb {
async fn insert_payment_intent(
&self,
new: PaymentIntentNew,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, errors::StorageError> {
let mut payment_intents = self.payment_intents.lock().await;
let time = common_utils::date_time::now();
@@ -305,6 +364,7 @@ impl PaymentIntentInterface for MockDb {
&self,
this: PaymentIntent,
update: PaymentIntentUpdate,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, errors::StorageError> {
let mut payment_intents = self.payment_intents.lock().await;
let payment_intent = payment_intents
@@ -319,6 +379,7 @@ impl PaymentIntentInterface for MockDb {
&self,
payment_id: &str,
merchant_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, errors::StorageError> {
let payment_intents = self.payment_intents.lock().await;
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index 9b03b5a3ff4..d1659caf339 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -4,7 +4,7 @@ use super::MockDb;
use crate::{
connection::pg_connection,
core::errors::{self, CustomResult, DatabaseError, StorageError},
- types::storage::{Refund, RefundNew, RefundUpdate},
+ types::storage::{enums, Refund, RefundNew, RefundUpdate},
};
#[async_trait::async_trait]
@@ -13,12 +13,14 @@ pub trait RefundInterface {
&self,
internal_reference_id: &str,
merchant_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Refund, errors::StorageError>;
async fn find_refund_by_payment_id_merchant_id(
&self,
payment_id: &str,
merchant_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<Refund>, errors::StorageError>;
// async fn find_refund_by_payment_id_merchant_id_refund_id(
@@ -32,21 +34,28 @@ pub trait RefundInterface {
&self,
merchant_id: &str,
refund_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Refund, errors::StorageError>;
async fn update_refund(
&self,
this: Refund,
refund: RefundUpdate,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Refund, errors::StorageError>;
async fn find_refund_by_merchant_id_transaction_id(
&self,
merchant_id: &str,
txn_id: &str,
+ storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<Refund>, errors::StorageError>;
- async fn insert_refund(&self, new: RefundNew) -> CustomResult<Refund, errors::StorageError>;
+ async fn insert_refund(
+ &self,
+ new: RefundNew,
+ storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<Refund, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -55,13 +64,18 @@ impl RefundInterface for super::Store {
&self,
internal_reference_id: &str,
merchant_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Refund, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
Refund::find_by_internal_reference_id_merchant_id(&conn, internal_reference_id, merchant_id)
.await
}
- async fn insert_refund(&self, new: RefundNew) -> CustomResult<Refund, errors::StorageError> {
+ async fn insert_refund(
+ &self,
+ new: RefundNew,
+ _storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<Refund, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
new.insert(&conn).await
}
@@ -69,6 +83,7 @@ impl RefundInterface for super::Store {
&self,
merchant_id: &str,
txn_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<Refund>, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
Refund::find_by_merchant_id_transaction_id(&conn, merchant_id, txn_id).await
@@ -78,6 +93,7 @@ impl RefundInterface for super::Store {
&self,
this: Refund,
refund: RefundUpdate,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Refund, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
this.update(&conn, refund).await
@@ -87,6 +103,7 @@ impl RefundInterface for super::Store {
&self,
merchant_id: &str,
refund_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Refund, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
Refund::find_by_merchant_id_refund_id(&conn, merchant_id, refund_id).await
@@ -107,6 +124,7 @@ impl RefundInterface for super::Store {
&self,
payment_id: &str,
merchant_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<Refund>, errors::StorageError> {
let conn = pg_connection(&self.master_pool).await;
Refund::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id).await
@@ -119,11 +137,16 @@ impl RefundInterface for MockDb {
&self,
_internal_reference_id: &str,
_merchant_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Refund, errors::StorageError> {
todo!()
}
- async fn insert_refund(&self, new: RefundNew) -> CustomResult<Refund, errors::StorageError> {
+ async fn insert_refund(
+ &self,
+ new: RefundNew,
+ _storage_scheme: enums::MerchantStorageScheme,
+ ) -> CustomResult<Refund, errors::StorageError> {
let mut refunds = self.refunds.lock().await;
let current_time = common_utils::date_time::now();
@@ -157,6 +180,7 @@ impl RefundInterface for MockDb {
&self,
merchant_id: &str,
txn_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<Refund>, errors::StorageError> {
let refunds = self.refunds.lock().await;
@@ -173,6 +197,7 @@ impl RefundInterface for MockDb {
&self,
_this: Refund,
_refund: RefundUpdate,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Refund, errors::StorageError> {
todo!()
}
@@ -181,6 +206,7 @@ impl RefundInterface for MockDb {
&self,
merchant_id: &str,
refund_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Refund, errors::StorageError> {
let refunds = self.refunds.lock().await;
@@ -195,6 +221,7 @@ impl RefundInterface for MockDb {
&self,
_payment_id: &str,
_merchant_id: &str,
+ _storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<Refund>, errors::StorageError> {
todo!()
}
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index 1cfd8cc072f..c6553349f9b 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -121,7 +121,6 @@ pub fn mk_app(
/// Unwrap used because without the value we can't start the server
pub async fn start_server(conf: Settings) -> BachResult<(Server, AppState)> {
logger::debug!(startup_config=?conf);
-
let server = conf.server.clone();
let state = routes::AppState::new(conf).await;
// Cloning to close connections before shutdown
diff --git a/crates/router/src/schema.rs b/crates/router/src/schema.rs
index 7dd78457a82..9808bb05de1 100644
--- a/crates/router/src/schema.rs
+++ b/crates/router/src/schema.rs
@@ -150,6 +150,7 @@ diesel::table! {
sub_merchants_enabled -> Nullable<Bool>,
parent_merchant_id -> Nullable<Varchar>,
publishable_key -> Nullable<Varchar>,
+ storage_scheme -> MerchantStorageScheme,
}
}
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index 044cea4f3d5..d94bd3bacfe 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -26,7 +26,11 @@ use crate::{
db::StorageInterface,
logger, routes,
routes::AppState,
- types::{self, api, storage, ErrorResponse, Response},
+ types::{
+ self, api,
+ storage::{self, enums},
+ ErrorResponse, Response,
+ },
utils::OptionExt,
};
@@ -556,6 +560,7 @@ pub async fn authenticate_merchant<'a>(
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: false,
publishable_key: None,
+ storage_scheme: enums::MerchantStorageScheme::PostgresOnly,
})
}
diff --git a/crates/router/src/types/storage/enums.rs b/crates/router/src/types/storage/enums.rs
index 0cb2224ade1..a44577fe06d 100644
--- a/crates/router/src/types/storage/enums.rs
+++ b/crates/router/src/types/storage/enums.rs
@@ -6,7 +6,8 @@ pub mod diesel_exports {
DbEventClass as EventClass, DbEventObjectType as EventObjectType, DbEventType as EventType,
DbFutureUsage as FutureUsage, DbIntentStatus as IntentStatus,
DbMandateStatus as MandateStatus, DbMandateType as MandateType,
- DbPaymentFlow as PaymentFlow, DbPaymentMethodIssuerCode as PaymentMethodIssuerCode,
+ DbMerchantStorageScheme as MerchantStorageScheme, DbPaymentFlow as PaymentFlow,
+ DbPaymentMethodIssuerCode as PaymentMethodIssuerCode,
DbPaymentMethodSubType as PaymentMethodSubType, DbPaymentMethodType as PaymentMethodType,
DbProcessTrackerStatus as ProcessTrackerStatus, DbRefundStatus as RefundStatus,
DbRefundType as RefundType, DbRoutingAlgorithm as RoutingAlgorithm,
@@ -362,6 +363,28 @@ pub enum FutureUsage {
OnSession,
}
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Default,
+ Eq,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+ router_derive::DieselEnum,
+)]
+#[router_derive::diesel_enum]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum MerchantStorageScheme {
+ #[default]
+ PostgresOnly,
+ RedisKv,
+}
+
#[derive(
Clone,
Copy,
diff --git a/crates/router/src/types/storage/merchant_account.rs b/crates/router/src/types/storage/merchant_account.rs
index 7954dfac126..b9dd43aa449 100644
--- a/crates/router/src/types/storage/merchant_account.rs
+++ b/crates/router/src/types/storage/merchant_account.rs
@@ -20,6 +20,7 @@ pub struct MerchantAccount {
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<String>,
pub publishable_key: Option<String>,
+ pub storage_scheme: enums::MerchantStorageScheme,
}
#[derive(Clone, Debug, Default, Insertable, router_derive::DebugAsDisplay)]
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index b2bb0bc5590..3694e40aa65 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -238,7 +238,12 @@ mod tests {
use uuid::Uuid;
use super::*;
- use crate::{configs::settings::Settings, db::StorageImpl, routes, types};
+ use crate::{
+ configs::settings::Settings,
+ db::StorageImpl,
+ routes,
+ types::{self, storage::enums},
+ };
#[actix_rt::test]
#[ignore]
@@ -259,7 +264,7 @@ mod tests {
let response = state
.store
- .insert_payment_attempt(payment_attempt)
+ .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
.await
.unwrap();
eprintln!("{:?}", response);
@@ -289,13 +294,17 @@ mod tests {
};
state
.store
- .insert_payment_attempt(payment_attempt)
+ .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
.await
.unwrap();
let response = state
.store
- .find_payment_attempt_by_payment_id_merchant_id(&payment_id, &merchant_id)
+ .find_payment_attempt_by_payment_id_merchant_id(
+ &payment_id,
+ &merchant_id,
+ enums::MerchantStorageScheme::PostgresOnly,
+ )
.await
.unwrap();
@@ -326,13 +335,17 @@ mod tests {
};
state
.store
- .insert_payment_attempt(payment_attempt)
+ .insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
.await
.unwrap();
let response = state
.store
- .find_payment_attempt_by_payment_id_merchant_id(&uuid, "1")
+ .find_payment_attempt_by_payment_id_merchant_id(
+ &uuid,
+ "1",
+ enums::MerchantStorageScheme::PostgresOnly,
+ )
.await
.unwrap();
// checking it after fetch
diff --git a/crates/router/src/types/storage/query/payment_attempt.rs b/crates/router/src/types/storage/query/payment_attempt.rs
index 00c018d8654..e7d17d0b314 100644
--- a/crates/router/src/types/storage/query/payment_attempt.rs
+++ b/crates/router/src/types/storage/query/payment_attempt.rs
@@ -8,7 +8,7 @@ use router_env::tracing::{self, instrument};
#[cfg(not(feature = "kv_store"))]
use super::generics::{self, ExecuteQuery};
#[cfg(feature = "kv_store")]
-use super::generics::{self, RawQuery, RawSqlQuery};
+use super::generics::{self, ExecuteQuery, RawQuery, RawSqlQuery};
use crate::{
connection::PgPooledConn,
core::errors::{self, CustomResult},
@@ -21,7 +21,6 @@ use crate::{
};
impl PaymentAttemptNew {
- #[cfg(not(feature = "kv_store"))]
#[instrument(skip(conn))]
pub async fn insert_diesel(
self,
@@ -32,7 +31,7 @@ impl PaymentAttemptNew {
#[cfg(feature = "kv_store")]
#[instrument(skip(conn))]
- pub async fn insert_diesel(
+ pub async fn insert_diesel_query(
self,
conn: &PgPooledConn,
) -> CustomResult<RawSqlQuery, errors::StorageError> {
@@ -41,7 +40,6 @@ impl PaymentAttemptNew {
}
impl PaymentAttempt {
- #[cfg(not(feature = "kv_store"))]
#[instrument(skip(conn))]
pub async fn update(
self,
@@ -68,7 +66,7 @@ impl PaymentAttempt {
#[cfg(feature = "kv_store")]
#[instrument(skip(conn))]
- pub async fn update(
+ pub async fn update_query(
self,
conn: &PgPooledConn,
payment_attempt: PaymentAttemptUpdate,
diff --git a/crates/router/src/types/storage/query/payment_intent.rs b/crates/router/src/types/storage/query/payment_intent.rs
index 2ca31e5f3ce..c6e17a0b119 100644
--- a/crates/router/src/types/storage/query/payment_intent.rs
+++ b/crates/router/src/types/storage/query/payment_intent.rs
@@ -6,7 +6,7 @@ use router_env::tracing::{self, instrument};
#[cfg(not(feature = "kv_store"))]
use super::generics::{self, ExecuteQuery};
#[cfg(feature = "kv_store")]
-use super::generics::{self, RawQuery, RawSqlQuery};
+use super::generics::{self, ExecuteQuery, RawQuery, RawSqlQuery};
use crate::{
connection::PgPooledConn,
core::errors::{self, CustomResult},
@@ -20,7 +20,6 @@ use crate::{
};
impl PaymentIntentNew {
- #[cfg(not(feature = "kv_store"))]
#[instrument(skip(conn))]
pub async fn insert_diesel(
self,
@@ -31,7 +30,7 @@ impl PaymentIntentNew {
#[cfg(feature = "kv_store")]
#[instrument(skip(conn))]
- pub async fn insert_diesel(
+ pub async fn insert_diesel_query(
self,
conn: &PgPooledConn,
) -> CustomResult<RawSqlQuery, errors::StorageError> {
@@ -40,7 +39,6 @@ impl PaymentIntentNew {
}
impl PaymentIntent {
- #[cfg(not(feature = "kv_store"))]
#[instrument(skip(conn))]
pub async fn update(
self,
@@ -67,7 +65,7 @@ impl PaymentIntent {
#[cfg(feature = "kv_store")]
#[instrument(skip(conn))]
- pub async fn update(
+ pub async fn update_query(
self,
conn: &PgPooledConn,
payment_intent: PaymentIntentUpdate,
diff --git a/migrations/2022-12-07-055441_add_use_kv_to_merchant_account/down.sql b/migrations/2022-12-07-055441_add_use_kv_to_merchant_account/down.sql
new file mode 100644
index 00000000000..14c5c102eca
--- /dev/null
+++ b/migrations/2022-12-07-055441_add_use_kv_to_merchant_account/down.sql
@@ -0,0 +1,5 @@
+-- This file should undo anything in `up.sql`
+
+ALTER TABLE merchant_account DROP COLUMN storage_scheme;
+
+DROP TYPE "MerchantStorageScheme";
diff --git a/migrations/2022-12-07-055441_add_use_kv_to_merchant_account/up.sql b/migrations/2022-12-07-055441_add_use_kv_to_merchant_account/up.sql
new file mode 100644
index 00000000000..356d8858e2b
--- /dev/null
+++ b/migrations/2022-12-07-055441_add_use_kv_to_merchant_account/up.sql
@@ -0,0 +1,8 @@
+-- Your SQL goes here
+
+CREATE TYPE "MerchantStorageScheme" AS ENUM (
+ 'postgres_only',
+ 'redis_kv'
+);
+
+ALTER TABLE merchant_account ADD COLUMN storage_scheme "MerchantStorageScheme" NOT NULL DEFAULT 'postgres_only';
|
feat
|
dynamically toggle KV for merchant and refactoring around it (#79)
|
0f7f3d9e74f0dad5112d6045089c8bfa12f4767f
|
2024-05-29 19:00:08
|
Apoorv Dixit
|
feat(users): add endpoint to check 2fa status (#4810)
| false
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index a472b3a76e6..c41f52a93ea 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -16,8 +16,9 @@ use crate::user::{
GetUserRoleDetailsResponse, InviteUserRequest, ListUsersResponse, ReInviteUserRequest,
RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest,
SignInResponse, SignUpRequest, SignUpWithMerchantIdRequest, SwitchMerchantIdRequest,
- TokenOrPayloadResponse, TokenResponse, UpdateUserAccountDetailsRequest, UserFromEmailRequest,
- UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
+ TokenOrPayloadResponse, TokenResponse, TwoFactorAuthStatusResponse,
+ UpdateUserAccountDetailsRequest, UserFromEmailRequest, UserMerchantCreate, VerifyEmailRequest,
+ VerifyRecoveryCodeRequest, VerifyTotpRequest,
};
impl ApiEventMetric for DashboardEntryResponse {
@@ -73,6 +74,7 @@ common_utils::impl_misc_api_event_type!(
GetUserRoleDetailsRequest,
GetUserRoleDetailsResponse,
TokenResponse,
+ TwoFactorAuthStatusResponse,
UserFromEmailRequest,
BeginTotpResponse,
VerifyRecoveryCodeRequest,
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 0c8678d2ef8..ee9498cfeee 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -235,6 +235,12 @@ pub struct TokenResponse {
pub token_type: TokenPurpose,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct TwoFactorAuthStatusResponse {
+ pub totp: bool,
+ pub recovery_code: bool,
+}
+
#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum TokenOrPayloadResponse<T> {
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 7b6e8ebd365..0da381bd493 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1874,3 +1874,16 @@ pub async fn terminate_two_factor_auth(
token,
)
}
+
+pub async fn check_two_factor_auth_status(
+ state: AppState,
+ user_token: auth::UserFromToken,
+) -> UserResponse<user_api::TwoFactorAuthStatusResponse> {
+ Ok(ApplicationResponse::Json(
+ user_api::TwoFactorAuthStatusResponse {
+ totp: tfa_utils::check_totp_in_redis(&state, &user_token.user_id).await?,
+ recovery_code: tfa_utils::check_recovery_code_in_redis(&state, &user_token.user_id)
+ .await?,
+ },
+ ))
+}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index b38479cd2b6..141e9f53af4 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1214,6 +1214,7 @@ impl User {
// Two factor auth routes
route = route.service(
web::scope("/2fa")
+ .service(web::resource("").route(web::get().to(check_two_factor_auth_status)))
.service(
web::scope("/totp")
.service(web::resource("/begin").route(web::get().to(totp_begin)))
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 9e53eb35473..417a4360c51 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -218,7 +218,8 @@ impl From<Flow> for ApiIdentifier {
| Flow::TotpUpdate
| Flow::RecoveryCodeVerify
| Flow::RecoveryCodesGenerate
- | Flow::TerminateTwoFactorAuth => Self::User,
+ | Flow::TerminateTwoFactorAuth
+ | Flow::TwoFactorAuthStatus => Self::User,
Flow::ListRoles
| Flow::GetRole
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index 5ba7ec8da25..f22e4aac521 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -735,3 +735,20 @@ pub async fn terminate_two_factor_auth(
))
.await
}
+
+pub async fn check_two_factor_auth_status(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+) -> HttpResponse {
+ let flow = Flow::TwoFactorAuthStatus;
+ Box::pin(api::server_wrap(
+ flow,
+ state.clone(),
+ &req,
+ (),
+ |state, user, _, _| user_core::check_two_factor_auth_status(state, user),
+ &auth::DashboardNoPermissionAuth,
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 1bfc20ff1ca..728f2ed206e 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -414,6 +414,8 @@ pub enum Flow {
RecoveryCodesGenerate,
// Terminate two factor authentication
TerminateTwoFactorAuth,
+ // Check 2FA status
+ TwoFactorAuthStatus,
/// List initial webhook delivery attempts
WebhookEventInitialDeliveryAttemptList,
/// List delivery attempts for a webhook event
|
feat
|
add endpoint to check 2fa status (#4810)
|
156a161f3eb0553dcfcc1f361e42ec7713f0fbb4
|
2024-09-19 23:19:47
|
Apoorv Dixit
|
fix(payments): add time range in list payment attempts query (#5959)
| false
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 5465d902388..3690bcf24db 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -18569,6 +18569,7 @@
},
"TimeRange": {
"type": "object",
+ "description": "A type representing a range of time for filtering, including a mandatory start time and an optional end time.",
"required": [
"start_time"
],
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index ff1a93454cc..2d0a7147570 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -22888,6 +22888,7 @@
},
"TimeRange": {
"type": "object",
+ "description": "A type representing a range of time for filtering, including a mandatory start time and an optional end time.",
"required": [
"start_time"
],
diff --git a/crates/analytics/src/disputes/metrics.rs b/crates/analytics/src/disputes/metrics.rs
index 401c606ccf9..dd1aa3c1bbd 100644
--- a/crates/analytics/src/disputes/metrics.rs
+++ b/crates/analytics/src/disputes/metrics.rs
@@ -4,15 +4,11 @@ mod total_dispute_lost_amount;
use std::collections::HashSet;
-use api_models::{
- analytics::{
- disputes::{
- DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier,
- },
- Granularity,
- },
- payments::TimeRange,
+use api_models::analytics::{
+ disputes::{DisputeDimensions, DisputeFilters, DisputeMetrics, DisputeMetricsBucketIdentifier},
+ Granularity,
};
+use common_utils::types::TimeRange;
use diesel_models::enums as storage_enums;
use time::PrimitiveDateTime;
diff --git a/crates/analytics/src/opensearch.rs b/crates/analytics/src/opensearch.rs
index 7486ab50a51..e0235c67bed 100644
--- a/crates/analytics/src/opensearch.rs
+++ b/crates/analytics/src/opensearch.rs
@@ -1,10 +1,12 @@
use api_models::{
analytics::search::SearchIndex,
errors::types::{ApiError, ApiErrorResponse},
- payments::TimeRange,
};
use aws_config::{self, meta::region::RegionProviderChain, Region};
-use common_utils::errors::{CustomResult, ErrorSwitch};
+use common_utils::{
+ errors::{CustomResult, ErrorSwitch},
+ types::TimeRange,
+};
use error_stack::ResultExt;
use hyperswitch_domain_models::errors::{StorageError, StorageResult};
use opensearch::{
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index 7abef472068..0379ec09547 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -1,5 +1,6 @@
use std::collections::HashSet;
+pub use common_utils::types::TimeRange;
use common_utils::{events::ApiEventMetric, pii::EmailStrategy, types::authentication::AuthInfo};
use masking::Secret;
@@ -14,8 +15,6 @@ use self::{
refunds::{RefundDimensions, RefundMetrics},
sdk_events::{SdkEventDimensions, SdkEventMetrics},
};
-pub use crate::payments::TimeRange;
-
pub mod active_payments;
pub mod api_event;
pub mod auth_events;
diff --git a/crates/api_models/src/analytics/search.rs b/crates/api_models/src/analytics/search.rs
index b962f60cae0..24dd0effcbb 100644
--- a/crates/api_models/src/analytics/search.rs
+++ b/crates/api_models/src/analytics/search.rs
@@ -1,9 +1,7 @@
-use common_utils::hashing::HashedString;
+use common_utils::{hashing::HashedString, types::TimeRange};
use masking::WithType;
use serde_json::Value;
-use crate::payments::TimeRange;
-
#[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)]
pub struct SearchFilters {
pub payment_method: Option<Vec<String>>,
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index 13966c464d5..41e958cb3f4 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -39,8 +39,6 @@ use crate::{
verifications::*,
};
-impl ApiEventMetric for TimeRange {}
-
impl ApiEventMetric for GetPaymentIntentFiltersRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::Analytics)
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 715bf3c3544..b0866cfb265 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -4204,7 +4204,7 @@ pub struct PaymentListFilterConstraints {
pub amount_filter: Option<AmountFilter>,
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
#[serde(flatten)]
- pub time_range: Option<TimeRange>,
+ pub time_range: Option<common_utils::types::TimeRange>,
/// The list of connectors to filter payments list
pub connector: Option<Vec<api_enums::Connector>>,
/// The list of currencies to filter payments list
@@ -4295,20 +4295,6 @@ pub enum SortBy {
Desc,
}
-#[derive(
- Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema,
-)]
-pub struct TimeRange {
- /// The start time to filter payments list or to get list of filters. To get list of filters start time is needed to be passed
- #[serde(with = "common_utils::custom_serde::iso8601")]
- #[serde(alias = "startTime")]
- pub start_time: PrimitiveDateTime,
- /// The end time to filter payments list or to get list of filters. If not passed the default time is now
- #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
- #[serde(alias = "endTime")]
- pub end_time: Option<PrimitiveDateTime>,
-}
-
#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)]
pub struct VerifyResponse {
pub verify_id: Option<id_type::PaymentId>,
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index 10771df4ccd..34e1bbe5449 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -704,7 +704,7 @@ pub struct PayoutListConstraints {
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
#[serde(flatten)]
#[schema(value_type = Option<TimeRange>)]
- pub time_range: Option<payments::TimeRange>,
+ pub time_range: Option<common_utils::types::TimeRange>,
}
#[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)]
@@ -732,7 +732,7 @@ pub struct PayoutListFilterConstraints {
/// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc).
#[serde(flatten)]
#[schema(value_type = Option<TimeRange>)]
- pub time_range: Option<payments::TimeRange>,
+ pub time_range: Option<common_utils::types::TimeRange>,
/// The list of connectors to filter payouts list
#[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))]
pub connector: Option<Vec<api_enums::PayoutConnectors>>,
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index edc0e75bdf2..237a903d80c 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -1,12 +1,12 @@
use std::collections::HashMap;
-use common_utils::pii;
pub use common_utils::types::{ChargeRefunds, MinorUnit};
+use common_utils::{pii, types::TimeRange};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use utoipa::ToSchema;
-use super::payments::{AmountFilter, TimeRange};
+use super::payments::AmountFilter;
use crate::{
admin::{self, MerchantConnectorInfo},
enums,
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs
index 16d0fd9b30a..2b1571617e8 100644
--- a/crates/common_utils/src/events.rs
+++ b/crates/common_utils/src/events.rs
@@ -1,7 +1,7 @@
use common_enums::{PaymentMethod, PaymentMethodType};
use serde::Serialize;
-use crate::id_type;
+use crate::{id_type, types::TimeRange};
pub trait ApiEventMetric {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
@@ -139,3 +139,5 @@ impl<T: ApiEventMetric> ApiEventMetric for &T {
T::get_api_event_type(self)
}
}
+
+impl ApiEventMetric for TimeRange {}
diff --git a/crates/common_utils/src/types.rs b/crates/common_utils/src/types.rs
index 6acf5000ced..2206744ef0b 100644
--- a/crates/common_utils/src/types.rs
+++ b/crates/common_utils/src/types.rs
@@ -28,6 +28,7 @@ use rust_decimal::{
};
use semver::Version;
use serde::{de::Visitor, Deserialize, Deserializer, Serialize};
+use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::{
@@ -582,6 +583,21 @@ impl StringMajorUnit {
}
}
+/// A type representing a range of time for filtering, including a mandatory start time and an optional end time.
+#[derive(
+ Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema,
+)]
+pub struct TimeRange {
+ /// The start time to filter payments list or to get list of filters. To get list of filters start time is needed to be passed
+ #[serde(with = "crate::custom_serde::iso8601")]
+ #[serde(alias = "startTime")]
+ pub start_time: PrimitiveDateTime,
+ /// The end time to filter payments list or to get list of filters. If not passed the default time is now
+ #[serde(default, with = "crate::custom_serde::iso8601::option")]
+ #[serde(alias = "endTime")]
+ pub end_time: Option<PrimitiveDateTime>,
+}
+
#[cfg(test)]
mod amount_conversion_tests {
#![allow(clippy::unwrap_used)]
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index fa80b0990d1..48941330ec6 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -351,6 +351,7 @@ impl PaymentAttempt {
payment_method: Option<Vec<enums::PaymentMethod>>,
payment_method_type: Option<Vec<enums::PaymentMethodType>>,
authentication_type: Option<Vec<enums::AuthenticationType>>,
+ time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
) -> StorageResult<i64> {
@@ -360,6 +361,14 @@ impl PaymentAttempt {
.filter(dsl::attempt_id.eq_any(active_attempt_ids.to_owned()))
.into_boxed();
+ if let Some(time_range) = time_range {
+ filter = filter.filter(dsl::created_at.ge(time_range.start_time));
+
+ if let Some(end_time) = time_range.end_time {
+ filter = filter.filter(dsl::created_at.le(end_time));
+ }
+ }
+
if let Some(connector) = connector {
filter = filter.filter(dsl::connector.eq_any(connector));
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 24a79e2905e..003509b2039 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -156,6 +156,7 @@ pub trait PaymentAttemptInterface {
payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>,
authentication_type: Option<Vec<storage_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
+ time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<id_type::ProfileId>>,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<i64, errors::StorageError>;
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index f5b719fe370..619ebcce68a 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -94,7 +94,7 @@ pub trait PaymentIntentInterface {
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, errors::StorageError>;
@@ -108,7 +108,7 @@ pub trait PaymentIntentInterface {
&self,
merchant_id: &id_type::MerchantId,
profile_id_list: Option<Vec<id_type::ProfileId>>,
- constraints: &api_models::payments::TimeRange,
+ constraints: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::StorageError>;
#[cfg(all(
@@ -1458,8 +1458,8 @@ impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchCo
}
}
-impl From<api_models::payments::TimeRange> for PaymentIntentFetchConstraints {
- fn from(value: api_models::payments::TimeRange) -> Self {
+impl From<common_utils::types::TimeRange> for PaymentIntentFetchConstraints {
+ fn from(value: common_utils::types::TimeRange) -> Self {
Self::List(Box::new(PaymentIntentListParams {
offset: 0,
starting_at: Some(value.start_time),
diff --git a/crates/hyperswitch_domain_models/src/payouts.rs b/crates/hyperswitch_domain_models/src/payouts.rs
index 952028fab30..8c6d751ebec 100644
--- a/crates/hyperswitch_domain_models/src/payouts.rs
+++ b/crates/hyperswitch_domain_models/src/payouts.rs
@@ -52,8 +52,8 @@ impl From<api_models::payouts::PayoutListConstraints> for PayoutFetchConstraints
}
}
-impl From<api_models::payments::TimeRange> for PayoutFetchConstraints {
- fn from(value: api_models::payments::TimeRange) -> Self {
+impl From<common_utils::types::TimeRange> for PayoutFetchConstraints {
+ fn from(value: common_utils::types::TimeRange) -> Self {
Self::List(Box::new(PayoutListParams {
offset: 0,
starting_at: Some(value.start_time),
diff --git a/crates/hyperswitch_domain_models/src/payouts/payouts.rs b/crates/hyperswitch_domain_models/src/payouts/payouts.rs
index 42037c3c2d9..eb43089e448 100644
--- a/crates/hyperswitch_domain_models/src/payouts/payouts.rs
+++ b/crates/hyperswitch_domain_models/src/payouts/payouts.rs
@@ -67,7 +67,7 @@ pub trait PayoutsInterface {
async fn filter_payouts_by_time_range_constraints(
&self,
_merchant_id: &id_type::MerchantId,
- _time_range: &api_models::payments::TimeRange,
+ _time_range: &common_utils::types::TimeRange,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, errors::StorageError>;
diff --git a/crates/hyperswitch_domain_models/src/refunds.rs b/crates/hyperswitch_domain_models/src/refunds.rs
index 3b3a79407d0..4016754510a 100644
--- a/crates/hyperswitch_domain_models/src/refunds.rs
+++ b/crates/hyperswitch_domain_models/src/refunds.rs
@@ -6,7 +6,7 @@ pub struct RefundListConstraints {
pub profile_id: Option<Vec<common_utils::id_type::ProfileId>>,
pub limit: Option<i64>,
pub offset: Option<i64>,
- pub time_range: Option<api_models::payments::TimeRange>,
+ pub time_range: Option<common_utils::types::TimeRange>,
pub amount_filter: Option<api_models::payments::AmountFilter>,
pub connector: Option<Vec<String>>,
pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index b626b7d4418..d1746a63dde 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -194,6 +194,7 @@ Never share your secret api keys. Keep them guarded and secure.
),
components(schemas(
common_utils::types::MinorUnit,
+ common_utils::types::TimeRange,
common_utils::link_utils::GenericLinkUiConfig,
common_utils::link_utils::EnabledPaymentMethod,
api_models::refunds::RefundRequest,
@@ -466,7 +467,6 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
api_models::refunds::RefundAggregateResponse,
- api_models::payments::TimeRange,
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 f12d6a7b567..b7771dc5e0a 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -119,6 +119,7 @@ Never share your secret api keys. Keep them guarded and secure.
),
components(schemas(
common_utils::types::MinorUnit,
+ common_utils::types::TimeRange,
common_utils::link_utils::GenericLinkUiConfig,
common_utils::link_utils::EnabledPaymentMethod,
api_models::refunds::RefundRequest,
@@ -392,7 +393,6 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::refunds::RefundListRequest,
api_models::refunds::RefundListResponse,
api_models::refunds::RefundAggregateResponse,
- api_models::payments::TimeRange,
api_models::payments::AmountFilter,
api_models::mandates::MandateRevokedResponse,
api_models::mandates::MandateResponse,
diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs
index ff5936fc296..30b73eb4c6a 100644
--- a/crates/router/src/core/disputes.rs
+++ b/crates/router/src/core/disputes.rs
@@ -516,7 +516,7 @@ pub async fn get_aggregates_for_disputes(
state: SessionState,
merchant: domain::MerchantAccount,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: api::TimeRange,
+ time_range: common_utils::types::TimeRange,
) -> RouterResponse<dispute_models::DisputesAggregateResponse> {
let db = state.store.as_ref();
let dispute_status_with_count = db
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 30d619efedc..b8255cfcfe5 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3108,6 +3108,7 @@ pub async fn apply_filters_on_payments(
constraints.payment_method_type,
constraints.authentication_type,
constraints.merchant_connector_id,
+ constraints.time_range,
pi_fetch_constraints.get_profile_id_list(),
merchant.storage_scheme,
)
@@ -3128,7 +3129,7 @@ pub async fn get_filters_for_payments(
state: SessionState,
merchant: domain::MerchantAccount,
merchant_key_store: domain::MerchantKeyStore,
- time_range: api::TimeRange,
+ time_range: common_utils::types::TimeRange,
) -> RouterResponse<api::PaymentListFilters> {
let db = state.store.as_ref();
let pi = db
@@ -3249,7 +3250,7 @@ pub async fn get_aggregates_for_payments(
state: SessionState,
merchant: domain::MerchantAccount,
profile_id_list: Option<Vec<id_type::ProfileId>>,
- time_range: api::TimeRange,
+ time_range: common_utils::types::TimeRange,
) -> RouterResponse<api::PaymentsAggregateResponse> {
let db = state.store.as_ref();
let intent_status_with_count = db
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index d0c0b2d3cde..c160acb50c2 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -996,7 +996,7 @@ pub async fn payouts_list_available_filters_core(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: api::TimeRange,
+ time_range: common_utils::types::TimeRange,
_locale: &str,
) -> RouterResponse<api::PayoutListFilters> {
let db = state.store.as_ref();
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 0f7abf44b14..118f4b81766 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -904,7 +904,7 @@ pub async fn refund_list(
pub async fn refund_filter_list(
state: SessionState,
merchant_account: domain::MerchantAccount,
- req: api_models::payments::TimeRange,
+ req: common_utils::types::TimeRange,
) -> RouterResponse<api_models::refunds::RefundListMetaData> {
let db = state.store;
let filter_list = db
@@ -1098,7 +1098,7 @@ pub async fn get_filters_for_refunds(
pub async fn get_aggregates_for_refunds(
state: SessionState,
merchant: domain::MerchantAccount,
- time_range: api::TimeRange,
+ time_range: common_utils::types::TimeRange,
) -> RouterResponse<api_models::refunds::RefundAggregateResponse> {
let db = state.store.as_ref();
let refund_status_with_count = db
diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs
index 1d45cfd405f..a44528fde43 100644
--- a/crates/router/src/db/dispute.rs
+++ b/crates/router/src/db/dispute.rs
@@ -52,7 +52,7 @@ pub trait DisputeInterface {
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::StorageError>;
}
@@ -141,7 +141,7 @@ impl DisputeInterface for Store {
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Dispute::get_dispute_status_with_count(
@@ -390,7 +390,7 @@ impl DisputeInterface for MockDb {
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
let locked_disputes = self.disputes.lock().await;
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 394c48c1cd8..9b51946c5c4 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -634,7 +634,7 @@ impl DisputeInterface for KafkaStore {
&self,
merchant_id: &id_type::MerchantId,
profile_id_list: Option<Vec<id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::StorageError> {
self.diesel_store
.get_dispute_status_with_count(merchant_id, profile_id_list, time_range)
@@ -1605,6 +1605,7 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
authentication_type: Option<Vec<common_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
+ time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<id_type::ProfileId>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::DataStorageError> {
@@ -1617,6 +1618,7 @@ impl PaymentAttemptInterface for KafkaStore {
payment_method_type,
authentication_type,
merchant_connector_id,
+ time_range,
profile_id_list,
storage_scheme,
)
@@ -1750,7 +1752,7 @@ impl PaymentIntentInterface for KafkaStore {
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::PaymentIntent>, errors::DataStorageError> {
@@ -1770,7 +1772,7 @@ impl PaymentIntentInterface for KafkaStore {
&self,
merchant_id: &id_type::MerchantId,
profile_id_list: Option<Vec<id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, errors::DataStorageError> {
self.diesel_store
.get_intent_status_with_count(merchant_id, profile_id_list, time_range)
@@ -2233,7 +2235,7 @@ impl PayoutsInterface for KafkaStore {
async fn filter_payouts_by_time_range_constraints(
&self,
merchant_id: &id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::Payouts>, errors::DataStorageError> {
self.diesel_store
@@ -2532,7 +2534,7 @@ impl RefundInterface for KafkaStore {
async fn filter_refund_by_meta_constraints(
&self,
merchant_id: &id_type::MerchantId,
- refund_details: &api_models::payments::TimeRange,
+ refund_details: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> {
self.diesel_store
@@ -2544,7 +2546,7 @@ impl RefundInterface for KafkaStore {
async fn get_refund_status_with_count(
&self,
merchant_id: &id_type::MerchantId,
- constraints: &api_models::payments::TimeRange,
+ constraints: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> {
self.diesel_store
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index 808f82b00a4..dbe7534ee28 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -80,7 +80,7 @@ pub trait RefundInterface {
async fn filter_refund_by_meta_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::payments::TimeRange,
+ refund_details: &common_utils::types::TimeRange,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError>;
@@ -88,7 +88,7 @@ pub trait RefundInterface {
async fn get_refund_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- constraints: &api_models::payments::TimeRange,
+ constraints: &common_utils::types::TimeRange,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError>;
@@ -817,7 +817,7 @@ mod storage {
async fn filter_refund_by_meta_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::payments::TimeRange,
+ refund_details: &common_utils::types::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -831,7 +831,7 @@ mod storage {
async fn get_refund_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- constraints: &api_models::payments::TimeRange,
+ constraints: &common_utils::types::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<(common_enums::RefundStatus, i64)>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -1135,7 +1135,7 @@ impl RefundInterface for MockDb {
async fn filter_refund_by_meta_constraints(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
- refund_details: &api_models::payments::TimeRange,
+ refund_details: &common_utils::types::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> {
let refunds = self.refunds.lock().await;
@@ -1182,7 +1182,7 @@ impl RefundInterface for MockDb {
async fn get_refund_status_with_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<(api_models::enums::RefundStatus, i64)>, errors::StorageError> {
let refunds = self.refunds.lock().await;
diff --git a/crates/router/src/routes/disputes.rs b/crates/router/src/routes/disputes.rs
index 5d8f7120f40..50a26ceae89 100644
--- a/crates/router/src/routes/disputes.rs
+++ b/crates/router/src/routes/disputes.rs
@@ -11,7 +11,7 @@ use super::app::AppState;
use crate::{
core::disputes,
services::{api, authentication as auth},
- types::api::{disputes as dispute_types, payments::TimeRange},
+ types::api::disputes as dispute_types,
};
/// Disputes - Retrieve Dispute
@@ -413,7 +413,7 @@ pub async fn delete_dispute_evidence(
pub async fn get_disputes_aggregate(
state: web::Data<AppState>,
req: HttpRequest,
- query_param: web::Query<TimeRange>,
+ query_param: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::DisputesAggregate;
let query_param = query_param.into_inner();
@@ -443,7 +443,7 @@ pub async fn get_disputes_aggregate(
pub async fn get_disputes_aggregate_profile(
state: web::Data<AppState>,
req: HttpRequest,
- query_param: web::Query<TimeRange>,
+ query_param: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::DisputesAggregate;
let query_param = query_param.into_inner();
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 82407976c6e..c8f4f5e4dd0 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -987,7 +987,7 @@ pub async fn profile_payments_list_by_filter(
pub async fn get_filters_for_payments(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
- payload: web::Json<payment_types::TimeRange>,
+ payload: web::Json<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsList;
let payload = payload.into_inner();
@@ -1065,7 +1065,7 @@ pub async fn get_payment_filters_profile(
pub async fn get_payments_aggregates(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
- payload: web::Query<payment_types::TimeRange>,
+ payload: web::Query<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsAggregate;
let payload = payload.into_inner();
@@ -1780,7 +1780,7 @@ impl GetLockingInput for payment_types::PaymentsManualUpdateRequest {
pub async fn get_payments_aggregates_profile(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
- payload: web::Query<payment_types::TimeRange>,
+ payload: web::Query<common_utils::types::TimeRange>,
) -> impl Responder {
let flow = Flow::PaymentsAggregate;
let payload = payload.into_inner();
diff --git a/crates/router/src/routes/payouts.rs b/crates/router/src/routes/payouts.rs
index 1b614330ebd..28b2afe2bee 100644
--- a/crates/router/src/routes/payouts.rs
+++ b/crates/router/src/routes/payouts.rs
@@ -8,8 +8,6 @@ use common_utils::consts;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
-#[cfg(feature = "olap")]
-use crate::types::api::payments as payment_types;
use crate::{
core::{api_locking, payouts::*},
headers::ACCEPT_LANGUAGE,
@@ -375,7 +373,7 @@ pub async fn payouts_list_by_filter_profile(
pub async fn payouts_list_available_filters_for_merchant(
state: web::Data<AppState>,
req: HttpRequest,
- json_payload: web::Json<payment_types::TimeRange>,
+ json_payload: web::Json<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::PayoutsFilter;
let payload = json_payload.into_inner();
@@ -408,7 +406,7 @@ pub async fn payouts_list_available_filters_for_merchant(
pub async fn payouts_list_available_filters_for_profile(
state: web::Data<AppState>,
req: HttpRequest,
- json_payload: web::Json<payment_types::TimeRange>,
+ json_payload: web::Json<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::PayoutsFilter;
let payload = json_payload.into_inner();
diff --git a/crates/router/src/routes/refunds.rs b/crates/router/src/routes/refunds.rs
index d21c351a927..40184c5fcfa 100644
--- a/crates/router/src/routes/refunds.rs
+++ b/crates/router/src/routes/refunds.rs
@@ -318,7 +318,7 @@ pub async fn refunds_list_profile(
pub async fn refunds_filter_list(
state: web::Data<AppState>,
req: HttpRequest,
- payload: web::Json<api_models::payments::TimeRange>,
+ payload: web::Json<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::RefundsList;
Box::pin(api::server_wrap(
@@ -426,7 +426,7 @@ pub async fn get_refunds_filters_profile(
pub async fn get_refunds_aggregates(
state: web::Data<AppState>,
req: HttpRequest,
- query_params: web::Query<api_models::payments::TimeRange>,
+ query_params: web::Query<common_utils::types::TimeRange>,
) -> HttpResponse {
let flow = Flow::RefundsAggregate;
let query_params = query_params.into_inner();
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 449d1c725c5..575725d4874 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -13,7 +13,7 @@ pub use api_models::payments::{
PaymentsRedirectionResponse, PaymentsRejectRequest, PaymentsRequest, PaymentsResponse,
PaymentsResponseForm, PaymentsRetrieveRequest, PaymentsSessionRequest, PaymentsSessionResponse,
PaymentsStartRequest, PgRedirectResponse, PhoneDetails, RedirectionResponse, SessionToken,
- TimeRange, UrlDetails, VerifyRequest, VerifyResponse, WalletData,
+ UrlDetails, VerifyRequest, VerifyResponse, WalletData,
};
use error_stack::ResultExt;
pub use hyperswitch_domain_models::router_flow_types::payments::{
diff --git a/crates/router/src/types/storage/dispute.rs b/crates/router/src/types/storage/dispute.rs
index 79b9a90343e..45f2073708b 100644
--- a/crates/router/src/types/storage/dispute.rs
+++ b/crates/router/src/types/storage/dispute.rs
@@ -19,7 +19,7 @@ pub trait DisputeDbExt: Sized {
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::enums::DisputeStatus, i64)>, errors::DatabaseError>;
}
@@ -84,7 +84,7 @@ impl DisputeDbExt for Dispute {
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::DisputeStatus, i64)>, errors::DatabaseError> {
let mut query = <Self as HasTable>::table()
.group_by(dsl::dispute_status)
diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs
index 8e0040abfae..350c1032261 100644
--- a/crates/router/src/types/storage/refund.rs
+++ b/crates/router/src/types/storage/refund.rs
@@ -29,7 +29,7 @@ pub trait RefundDbExt: Sized {
async fn filter_by_meta_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- refund_list_details: &api_models::payments::TimeRange,
+ refund_list_details: &common_utils::types::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError>;
async fn get_refunds_count(
@@ -41,7 +41,7 @@ pub trait RefundDbExt: Sized {
async fn get_refund_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError>;
}
@@ -158,7 +158,7 @@ impl RefundDbExt for Refund {
async fn filter_by_meta_constraints(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- refund_list_details: &api_models::payments::TimeRange,
+ refund_list_details: &common_utils::types::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError> {
let start_time = refund_list_details.start_time;
@@ -299,7 +299,7 @@ impl RefundDbExt for Refund {
async fn get_refund_status_with_count(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(RefundStatus, i64)>, errors::DatabaseError> {
let mut query = <Self as HasTable>::table()
.group_by(dsl::refund_status)
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index 1a4595bdbbe..7abde140991 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -52,6 +52,7 @@ impl PaymentAttemptInterface for MockDb {
_payment_method_type: Option<Vec<PaymentMethodType>>,
_authentication_type: Option<Vec<AuthenticationType>>,
_merchanat_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ _time_range: Option<common_utils::types::TimeRange>,
_profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<i64, StorageError> {
diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs
index 4cf8272650a..e0328871e33 100644
--- a/crates/storage_impl/src/mock_db/payment_intent.rs
+++ b/crates/storage_impl/src/mock_db/payment_intent.rs
@@ -41,7 +41,7 @@ impl PaymentIntentInterface for MockDb {
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
- _time_range: &api_models::payments::TimeRange,
+ _time_range: &common_utils::types::TimeRange,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
@@ -57,7 +57,7 @@ impl PaymentIntentInterface for MockDb {
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- _time_range: &api_models::payments::TimeRange,
+ _time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
diff --git a/crates/storage_impl/src/mock_db/payouts.rs b/crates/storage_impl/src/mock_db/payouts.rs
index 5f2cc8824e5..c72a08a1823 100644
--- a/crates/storage_impl/src/mock_db/payouts.rs
+++ b/crates/storage_impl/src/mock_db/payouts.rs
@@ -86,7 +86,7 @@ impl PayoutsInterface for MockDb {
async fn filter_payouts_by_time_range_constraints(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
- _time_range: &api_models::payments::TimeRange,
+ _time_range: &common_utils::types::TimeRange,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<Payouts>, StorageError> {
// TODO: Implement function for `MockDb`
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index d1df6861657..9974393e100 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -403,6 +403,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method_type: Option<Vec<PaymentMethodType>>,
authentication_type: Option<Vec<AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
@@ -426,6 +427,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
payment_method,
payment_method_type,
authentication_type,
+ time_range,
profile_id_list,
merchant_connector_id,
)
@@ -1289,6 +1291,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method_type: Option<Vec<PaymentMethodType>>,
authentication_type: Option<Vec<AuthenticationType>>,
merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
+ time_range: Option<common_utils::types::TimeRange>,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
@@ -1301,6 +1304,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_method_type,
authentication_type,
merchant_connector_id,
+ time_range,
profile_id_list,
storage_scheme,
)
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index cb58eac4b61..97fa5873cae 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -378,7 +378,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, StorageError> {
@@ -402,7 +402,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
self.router_store
.get_intent_status_with_count(merchant_id, profile_id_list, time_range)
@@ -747,7 +747,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, StorageError> {
@@ -773,7 +773,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
let conn = connection::pg_connection_read(self).await.switch()?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index b6e1c1ac35f..2a49b01458f 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -368,7 +368,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
async fn filter_payouts_by_time_range_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
self.router_store
@@ -772,7 +772,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
async fn filter_payouts_by_time_range_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
- time_range: &api_models::payments::TimeRange,
+ time_range: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
let payout_filters = (*time_range).into();
|
fix
|
add time range in list payment attempts query (#5959)
|
04e9734800a9011d9ae7bd43f75c90a75a9a9334
|
2024-02-27 17:45:33
|
Hrithikesh
|
fix(core): validate amount_to_capture in payment update (#3830)
| false
|
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 0eaf3c07ee6..0baba7035ce 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -677,8 +677,11 @@ pub fn validate_amount_to_capture_and_capture_method(
.unwrap_or(0);
let total_capturable_amount =
original_amount.map(|original_amount| original_amount + surcharge_amount);
+ let amount_to_capture = request
+ .amount_to_capture
+ .or(payment_attempt.and_then(|pa| pa.amount_to_capture));
if let Some((total_capturable_amount, amount_to_capture)) =
- total_capturable_amount.zip(request.amount_to_capture)
+ total_capturable_amount.zip(amount_to_capture)
{
utils::when(amount_to_capture != total_capturable_amount, || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Update/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Update/request.json
index 813d6dc24a4..44023297d13 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Update/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario23- Update Amount/Payments - Update/request.json
@@ -18,7 +18,8 @@
}
},
"raw_json_formatted": {
- "amount": 1000
+ "amount": 1000,
+ "amount_to_capture": 1000
}
},
"url": {
|
fix
|
validate amount_to_capture in payment update (#3830)
|
71bf627fbcdab6263e837fb851b77cefef833ea1
|
2024-09-13 12:10:14
|
awasthi21
|
feat(connector): [Fiuu] ADD Wasm Configs (#5874)
| false
|
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index 8c9091baf4e..fb4d92581ed 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -139,6 +139,7 @@ pub struct ConnectorTomlConfig {
pub gift_card: Option<Vec<Provider>>,
pub card_redirect: Option<Vec<Provider>>,
pub is_verifiable: Option<bool>,
+ pub real_time_payment: Option<Vec<Provider>>,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Deserialize, serde::Serialize, Clone)]
diff --git a/crates/connector_configs/toml/development.toml b/crates/connector_configs/toml/development.toml
index 4120e1d7db8..ef2cf56f31b 100644
--- a/crates/connector_configs/toml/development.toml
+++ b/crates/connector_configs/toml/development.toml
@@ -4069,6 +4069,10 @@ api_secret="Shared Secret"
payment_method_type = "CartesBancaires"
[[fiuu.debit]]
payment_method_type = "UnionPay"
+[[fiuu.real_time_payment]]
+ payment_method_type = "duit_now"
+[[fiuu.bank_redirect]]
+ payment_method_type = "online_banking_fpx"
[fiuu.connector_auth.SignatureKey]
api_key="Verify Key"
key1="Merchant ID"
diff --git a/crates/connector_configs/toml/production.toml b/crates/connector_configs/toml/production.toml
index ba2021b6cff..c7e55ca7a79 100644
--- a/crates/connector_configs/toml/production.toml
+++ b/crates/connector_configs/toml/production.toml
@@ -3053,6 +3053,10 @@ api_secret="Shared Secret"
payment_method_type = "CartesBancaires"
[[fiuu.debit]]
payment_method_type = "UnionPay"
+[[fiuu.real_time_payment]]
+ payment_method_type = "duit_now"
+[[fiuu.bank_redirect]]
+ payment_method_type = "online_banking_fpx"
[fiuu.connector_auth.SignatureKey]
api_key="Verify Key"
key1="Merchant ID"
diff --git a/crates/connector_configs/toml/sandbox.toml b/crates/connector_configs/toml/sandbox.toml
index 354ee78f57d..9d44f76970f 100644
--- a/crates/connector_configs/toml/sandbox.toml
+++ b/crates/connector_configs/toml/sandbox.toml
@@ -4062,6 +4062,10 @@ api_secret="Shared Secret"
payment_method_type = "CartesBancaires"
[[fiuu.debit]]
payment_method_type = "UnionPay"
+[[fiuu.real_time_payment]]
+ payment_method_type = "duit_now"
+[[fiuu.bank_redirect]]
+ payment_method_type = "online_banking_fpx"
[fiuu.connector_auth.SignatureKey]
api_key="Verify Key"
key1="Merchant ID"
|
feat
|
[Fiuu] ADD Wasm Configs (#5874)
|
c0bb117f247ad0fcc9603d6f8a8725e470439a73
|
2024-05-09 18:55:34
|
Gnanasundari24
|
ci(cypress): Fix card expiry for savecard flows (#4585)
| false
|
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00003-NoThreeDSAutoCapture.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00003-NoThreeDSAutoCapture.cy.js
index 2f7e0ccaea2..e25b074bc1e 100644
--- a/cypress-tests/cypress/e2e/ConnectorTest/00003-NoThreeDSAutoCapture.cy.js
+++ b/cypress-tests/cypress/e2e/ConnectorTest/00003-NoThreeDSAutoCapture.cy.js
@@ -24,7 +24,7 @@ describe("Card - NoThreeDS payment flow test", () => {
context("Card-NoThreeDS payment flow test Create and confirm", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "automatic", globalState);
});
@@ -33,7 +33,7 @@ describe("Card - NoThreeDS payment flow test", () => {
});
it("Confirm No 3DS", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.confirmCallTest(confirmBody, det, true, globalState);
});
@@ -47,7 +47,7 @@ describe("Card - NoThreeDS payment flow test", () => {
it("create+confirm-payment-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createConfirmPaymentTest(createConfirmPaymentBody, det, "no_three_ds", "automatic", globalState);
});
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00004-ThreeDSAutoCapture.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00004-ThreeDSAutoCapture.cy.js
index 43cab5e189f..662739e5196 100644
--- a/cypress-tests/cypress/e2e/ConnectorTest/00004-ThreeDSAutoCapture.cy.js
+++ b/cypress-tests/cypress/e2e/ConnectorTest/00004-ThreeDSAutoCapture.cy.js
@@ -25,7 +25,7 @@ describe("Card - ThreeDS payment flow test", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "three_ds", "automatic", globalState);
});
@@ -35,7 +35,7 @@ describe("Card - ThreeDS payment flow test", () => {
});
it("Confirm 3DS", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DS"];
cy.task('cli_log', "GLOBAL STATE -> " + JSON.stringify(globalState.data));
cy.confirmCallTest(confirmBody, det, true, globalState);
});
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00005-NoThreeDSManualCapture.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00005-NoThreeDSManualCapture.cy.js
index 095ab5381d0..a0af6897bef 100644
--- a/cypress-tests/cypress/e2e/ConnectorTest/00005-NoThreeDSManualCapture.cy.js
+++ b/cypress-tests/cypress/e2e/ConnectorTest/00005-NoThreeDSManualCapture.cy.js
@@ -27,7 +27,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
context("payment Create and Confirm", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "manual", globalState);
});
@@ -37,7 +37,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
it("confirm-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.confirmCallTest(confirmBody, det, true, globalState);
});
@@ -47,7 +47,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
});
it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 6500, det.paymentSuccessfulStatus, globalState);
});
@@ -61,7 +61,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
context("Payment Create+Confirm", () => {
it("create+confirm-payment-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.createConfirmPaymentTest(createConfirmPaymentBody, det, "no_three_ds", "manual", globalState);
});
@@ -71,7 +71,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
});
it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 6540, det.paymentSuccessfulStatus, globalState);
});
@@ -89,7 +89,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
context("payment Create and Payment Confirm", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "manual", globalState);
});
@@ -99,7 +99,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
it("confirm-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.confirmCallTest(confirmBody, det, true, globalState);
});
@@ -109,7 +109,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
});
it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.captureCallTest(captureBody, 100, det.paymentSuccessfulStatus, globalState);
});
@@ -121,7 +121,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
context("payment + Confirm", () => {
it("create+confirm-payment-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.createConfirmPaymentTest(createConfirmPaymentBody, det, "no_three_ds", "manual", globalState);
});
@@ -131,7 +131,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
});
it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 5000, det.paymentSuccessfulStatus, globalState);
});
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00006-VoidPayment.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00006-VoidPayment.cy.js
index a3808b4db16..61a27763134 100644
--- a/cypress-tests/cypress/e2e/ConnectorTest/00006-VoidPayment.cy.js
+++ b/cypress-tests/cypress/e2e/ConnectorTest/00006-VoidPayment.cy.js
@@ -23,7 +23,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
context("Card - void payment in Requires_capture state flow test", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "manual", globalState);
});
@@ -33,7 +33,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
it("confirm-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.confirmCallTest(confirmBody, det, true, globalState);
});
@@ -45,7 +45,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
context("Card - void payment in Requires_payment_method state flow test", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "manual", globalState);
});
@@ -60,7 +60,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
context("Card - void payment in Requires_payment_method state flow test", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "manual", globalState);
});
@@ -70,7 +70,7 @@ describe("Card - NoThreeDS Manual payment flow test", () => {
it("confirm-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.confirmCallTest(confirmBody, det, false, globalState);
});
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00007-SyncPayment.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00007-SyncPayment.cy.js
index b0ee171ec25..efdeeb8da2d 100644
--- a/cypress-tests/cypress/e2e/ConnectorTest/00007-SyncPayment.cy.js
+++ b/cypress-tests/cypress/e2e/ConnectorTest/00007-SyncPayment.cy.js
@@ -20,7 +20,7 @@ describe("Card - Sync payment flow test", () => {
cy.task('setGlobalState', globalState.data);
})
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "automatic", globalState);
});
@@ -30,7 +30,7 @@ describe("Card - Sync payment flow test", () => {
it("confirm-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.confirmCallTest(confirmBody, det, true, globalState);
});
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00008-RefundPayment.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00008-RefundPayment.cy.js
index 9449bf0d86f..d45aa6dfec9 100644
--- a/cypress-tests/cypress/e2e/ConnectorTest/00008-RefundPayment.cy.js
+++ b/cypress-tests/cypress/e2e/ConnectorTest/00008-RefundPayment.cy.js
@@ -29,7 +29,7 @@ describe("Card - Refund flow test", () => {
context("Card - Full Refund flow test for No-3DS", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "automatic", globalState);
});
@@ -39,7 +39,7 @@ describe("Card - Refund flow test", () => {
it("confirm-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.confirmCallTest(confirmBody, det, true, globalState);
});
@@ -49,7 +49,7 @@ describe("Card - Refund flow test", () => {
});
it("refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.refundCallTest(refundBody, 6500, det, globalState);
});
});
@@ -57,7 +57,7 @@ describe("Card - Refund flow test", () => {
context("Card - Partial Refund flow test for No-3DS", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "automatic", globalState);
});
@@ -67,7 +67,7 @@ describe("Card - Refund flow test", () => {
it("confirm-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.confirmCallTest(confirmBody, det, true, globalState);
});
@@ -77,12 +77,12 @@ describe("Card - Refund flow test", () => {
});
it("refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.refundCallTest(refundBody, 1200, det, globalState);
});
it("refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.refundCallTest(refundBody, 1200, det, globalState);
});
});
@@ -90,9 +90,9 @@ describe("Card - Refund flow test", () => {
context("Fully Refund Card-NoThreeDS payment flow test Create+Confirm", () => {
it("create+confirm-payment-call-test", () => {
- console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
- cy.createConfirmPaymentTest(createConfirmPaymentBody, det, "no_three_ds", "automatic", globalState);
+ console.log("confirm -> " + globalState.get("connectorId"));
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
+ cy.createConfirmPaymentTest( createConfirmPaymentBody, det,"no_three_ds", "automatic", globalState);
});
it("retrieve-payment-call-test", () => {
@@ -100,7 +100,7 @@ describe("Card - Refund flow test", () => {
});
it("refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.refundCallTest(refundBody, 6540, det, globalState);
});
@@ -109,9 +109,9 @@ describe("Card - Refund flow test", () => {
context("Partially Refund Card-NoThreeDS payment flow test Create+Confirm", () => {
it("create+confirm-payment-call-test", () => {
- console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
- cy.createConfirmPaymentTest(createConfirmPaymentBody, det, "no_three_ds", "automatic", globalState);
+ console.log("confirm -> " + globalState.get("connectorId"));
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
+ cy.createConfirmPaymentTest( createConfirmPaymentBody, det,"no_three_ds", "automatic", globalState);
});
it("retrieve-payment-call-test", () => {
@@ -119,17 +119,17 @@ describe("Card - Refund flow test", () => {
});
it("refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.refundCallTest(refundBody, 3000, det, globalState);
});
it("refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.refundCallTest(refundBody, 3000, det, globalState);
});
it("sync-refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.syncRefundCallTest(det, globalState);
});
@@ -138,7 +138,7 @@ describe("Card - Refund flow test", () => {
context("Card - Full Refund for fully captured No-3DS payment", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "manual", globalState);
});
@@ -148,7 +148,7 @@ describe("Card - Refund flow test", () => {
it("confirm-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.confirmCallTest(confirmBody, det, true, globalState);
});
@@ -158,7 +158,7 @@ describe("Card - Refund flow test", () => {
});
it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 6500, det.paymentSuccessfulStatus, globalState);
});
@@ -168,12 +168,12 @@ describe("Card - Refund flow test", () => {
});
it("refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.refundCallTest(refundBody, 6500, det, globalState);
});
it("sync-refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.syncRefundCallTest(det, globalState);
});
});
@@ -181,7 +181,7 @@ describe("Card - Refund flow test", () => {
context("Card - Partial Refund for fully captured No-3DS payment", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "manual", globalState);
});
@@ -191,7 +191,7 @@ describe("Card - Refund flow test", () => {
it("confirm-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.confirmCallTest(confirmBody, det, true, globalState);
});
@@ -201,7 +201,7 @@ describe("Card - Refund flow test", () => {
});
it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 6500, det.paymentSuccessfulStatus, globalState);
});
@@ -211,16 +211,16 @@ describe("Card - Refund flow test", () => {
});
it("refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.refundCallTest(refundBody, 5000, det, globalState);
});
it("refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.refundCallTest(refundBody, 500, det, globalState);
});
it("sync-refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.syncRefundCallTest(det, globalState);
});
it("list-refund-call-test", () => {
@@ -231,7 +231,7 @@ describe("Card - Refund flow test", () => {
context("Card - Full Refund for partially captured No-3DS payment", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "manual", globalState);
});
@@ -241,7 +241,7 @@ describe("Card - Refund flow test", () => {
it("confirm-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.confirmCallTest(confirmBody, det, true, globalState);
});
@@ -251,7 +251,7 @@ describe("Card - Refund flow test", () => {
});
it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 4000, det.paymentSuccessfulStatus, globalState);
});
@@ -261,12 +261,12 @@ describe("Card - Refund flow test", () => {
});
it("refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.refundCallTest(refundBody, 4000, det, globalState);
});
it("sync-refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.syncRefundCallTest(det, globalState);
});
});
@@ -274,7 +274,7 @@ describe("Card - Refund flow test", () => {
context("Card - partial Refund for partially captured No-3DS payment", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "manual", globalState);
});
@@ -284,7 +284,7 @@ describe("Card - Refund flow test", () => {
it("confirm-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.confirmCallTest(confirmBody, det, true, globalState);
});
@@ -294,7 +294,7 @@ describe("Card - Refund flow test", () => {
});
it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 4000, det.paymentSuccessfulStatus, globalState);
});
@@ -304,12 +304,12 @@ describe("Card - Refund flow test", () => {
});
it("refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.refundCallTest(refundBody, 3000, det, globalState);
});
it("sync-refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.syncRefundCallTest(det, globalState);
});
});
@@ -317,7 +317,7 @@ describe("Card - Refund flow test", () => {
context("Card - Full Refund for Create + Confirm Automatic CIT and MIT payment flow test", () => {
it("Confirm No 3DS CIT", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateMultiUseNo3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUseNo3DS"];
console.log("det -> " + det.card);
cy.citForMandatesCallTest(citConfirmBody, 7000, det, true, "automatic", "new_mandate", globalState);
});
@@ -331,13 +331,13 @@ describe("Card - Refund flow test", () => {
});
it("refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUseNo3DS"];
cy.refundCallTest(refundBody, 7000, det, globalState);
});
it("sync-refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
- cy.syncRefundCallTest(det, globalState);
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUseNo3DS"];
+ cy.syncRefundCallTest(det, globalState);
});
});
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00009-SyncRefund.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00009-SyncRefund.cy.js
index 35f473d8a6d..6bf9639da26 100644
--- a/cypress-tests/cypress/e2e/ConnectorTest/00009-SyncRefund.cy.js
+++ b/cypress-tests/cypress/e2e/ConnectorTest/00009-SyncRefund.cy.js
@@ -22,7 +22,7 @@ describe("Card - Sync Refund flow test", () => {
})
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "automatic", globalState);
});
@@ -32,7 +32,7 @@ describe("Card - Sync Refund flow test", () => {
it("confirm-call-test", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
console.log("det -> " + det.card);
cy.confirmCallTest(confirmBody, det, true, globalState);
});
@@ -42,12 +42,12 @@ describe("Card - Sync Refund flow test", () => {
});
it("refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.refundCallTest(refundBody, 6500, det, globalState);
});
it("sync-refund-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["No3DS"];
cy.syncRefundCallTest(det, globalState);
});
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00010-CreateSingleuseMandate.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00010-CreateSingleuseMandate.cy.js
index 04e17795036..bd795d8a38b 100644
--- a/cypress-tests/cypress/e2e/ConnectorTest/00010-CreateSingleuseMandate.cy.js
+++ b/cypress-tests/cypress/e2e/ConnectorTest/00010-CreateSingleuseMandate.cy.js
@@ -25,7 +25,7 @@ describe("Card - SingleUse Mandates flow test", () => {
it("Confirm No 3DS CIT", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateSingleUseNo3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateSingleUseNo3DS"];
console.log("det -> " + det.card);
cy.citForMandatesCallTest(citConfirmBody, 7000, det, true, "automatic", "new_mandate", globalState);
});
@@ -39,13 +39,13 @@ describe("Card - SingleUse Mandates flow test", () => {
it("Confirm No 3DS CIT", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateSingleUseNo3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateSingleUseNo3DS"];
console.log("det -> " + det.card);
cy.citForMandatesCallTest(citConfirmBody, 7000, det, true, "manual", "new_mandate", globalState);
});
it("cit-capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateSingleUseNo3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateSingleUseNo3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 7000, det.paymentSuccessfulStatus, globalState);
});
@@ -55,7 +55,7 @@ describe("Card - SingleUse Mandates flow test", () => {
});
it("mit-capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateSingleUseNo3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateSingleUseNo3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 7000, det.paymentSuccessfulStatus, globalState);
});
@@ -69,13 +69,13 @@ describe("Card - SingleUse Mandates flow test", () => {
it("Confirm No 3DS CIT", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateSingleUse3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateSingleUse3DS"];
console.log("det -> " + det.card);
cy.citForMandatesCallTest(citConfirmBody, 6500, det, true, "automatic", "new_mandate", globalState);
});
it("cit-capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateSingleUse3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateSingleUse3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 6500, det.paymentSuccessfulStatus, globalState);
});
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00011-CreateMultiuseMandate.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00011-CreateMultiuseMandate.cy.js
index 9990eeaadb5..474024a1bcb 100644
--- a/cypress-tests/cypress/e2e/ConnectorTest/00011-CreateMultiuseMandate.cy.js
+++ b/cypress-tests/cypress/e2e/ConnectorTest/00011-CreateMultiuseMandate.cy.js
@@ -26,7 +26,7 @@ describe("Card - MultiUse Mandates flow test", () => {
it("Confirm No 3DS CIT", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateMultiUseNo3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUseNo3DS"];
console.log("det -> " + det.card);
cy.citForMandatesCallTest(citConfirmBody, 7000, det, true, "automatic", "new_mandate", globalState);
});
@@ -43,13 +43,13 @@ describe("Card - MultiUse Mandates flow test", () => {
it("Confirm No 3DS CIT", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateMultiUseNo3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUseNo3DS"];
console.log("det -> " + det.card);
cy.citForMandatesCallTest(citConfirmBody, 7000, det, true, "manual", "new_mandate", globalState);
});
it("cit-capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateMultiUseNo3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUseNo3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 7000, det.paymentSuccessfulStatus, globalState);
});
@@ -59,7 +59,7 @@ describe("Card - MultiUse Mandates flow test", () => {
});
it("mit-capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateMultiUseNo3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUseNo3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 7000, det.paymentSuccessfulStatus, globalState);
});
@@ -69,7 +69,7 @@ describe("Card - MultiUse Mandates flow test", () => {
});
it("mit-capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateMultiUseNo3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUseNo3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 7000, det.paymentSuccessfulStatus, globalState);
});
@@ -79,13 +79,13 @@ describe("Card - MultiUse Mandates flow test", () => {
it("Confirm No 3DS CIT", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateMultiUse3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUse3DS"];
console.log("det -> " + det.card);
cy.citForMandatesCallTest(citConfirmBody, 6500, det, true, "automatic", "new_mandate", globalState);
});
it("cit-capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateMultiUse3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateMultiUse3DS"];
console.log("det -> " + det.card);
cy.captureCallTest(captureBody, 6500, det.paymentSuccessfulStatus, globalState);
});
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00012-ListAndRevokeMandate.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00012-ListAndRevokeMandate.cy.js
index fea2a94cbcc..8504f602cc5 100644
--- a/cypress-tests/cypress/e2e/ConnectorTest/00012-ListAndRevokeMandate.cy.js
+++ b/cypress-tests/cypress/e2e/ConnectorTest/00012-ListAndRevokeMandate.cy.js
@@ -25,7 +25,7 @@ describe("Card - SingleUse Mandates flow test", () => {
it("Confirm No 3DS CIT", () => {
console.log("confirm -> " + globalState.get("connectorId"));
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateSingleUseNo3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateSingleUseNo3DS"];
console.log("det -> " + det.card);
cy.citForMandatesCallTest(citConfirmBody, 7000, det, true, "automatic", "new_mandate", globalState);
});
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00013-SaveCardFlow.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00013-SaveCardFlow.cy.js
index 1aeb5199e73..f3e240aa88c 100644
--- a/cypress-tests/cypress/e2e/ConnectorTest/00013-SaveCardFlow.cy.js
+++ b/cypress-tests/cypress/e2e/ConnectorTest/00013-SaveCardFlow.cy.js
@@ -1,10 +1,11 @@
import captureBody from "../../fixtures/capture-flow-body.json";
import confirmBody from "../../fixtures/confirm-body.json";
+import createPaymentBody from "../../fixtures/create-payment-body.json";
import createConfirmPaymentBody from "../../fixtures/create-confirm-body.json";
import customerCreateBody from "../../fixtures/create-customer-body.json";
-import createPaymentBody from "../../fixtures/create-payment-body.json";
-import State from "../../utils/State";
+import SaveCardConfirmBody from "../../fixtures/save-card-confirm-body.json";
import getConnectorDetails from "../ConnectorUtils/utils";
+import State from "../../utils/State";
let globalState;
describe("Card - SaveCard payment flow test", () => {
@@ -17,110 +18,106 @@ describe("Card - SaveCard payment flow test", () => {
})
})
- after("flush global state", () => {
- console.log("flushing globalState -> " + JSON.stringify(globalState));
- cy.task('setGlobalState', globalState.data);
- })
-
-
- context("Save card for NoThreeDS automatic capture payment- Create+Confirm", () => {
- it("customer-create-call-test", () => {
- cy.createCustomerCallTest(customerCreateBody, globalState);
- });
-
- it("create+confirm-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["SaveCardUseNo3DS"];
- cy.createConfirmPaymentTest(createConfirmPaymentBody, det, "no_three_ds", "automatic", globalState);
- });
-
- it("retrieve-payment-call-test", () => {
- cy.retrievePaymentCallTest(globalState);
- });
-
- it("retrieve-customerPM-call-test", () => {
- cy.listCustomerPMCallTest(globalState);
- });
-
- it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
- cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "automatic", globalState);
- });
-
- it("confirm-save-card-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["SaveCardUseNo3DS"];
- cy.saveCardConfirmCallTest(confirmBody, det, globalState);
- });
-
- });
-
- context("Save card for NoThreeDS manual full capture payment- Create+Confirm", () => {
- it("customer-create-call-test", () => {
- cy.createCustomerCallTest(customerCreateBody, globalState);
- });
-
- it("create+confirm-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["SaveCardUseNo3DS"];
- cy.createConfirmPaymentTest(createConfirmPaymentBody, det, "no_three_ds", "automatic", globalState);
- });
-
- it("retrieve-payment-call-test", () => {
- cy.retrievePaymentCallTest(globalState);
- });
-
- it("retrieve-customerPM-call-test", () => {
- cy.listCustomerPMCallTest(globalState);
- });
-
- it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
- cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "manual", globalState);
- });
-
-
- it("confirm-save-card-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["SaveCardUseNo3DS"];
- cy.saveCardConfirmCallTest(confirmBody, det, globalState);
- });
-
- it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
- cy.captureCallTest(captureBody, 6500, det.paymentSuccessfulStatus, globalState);
- });
- });
-
- context("Save card for NoThreeDS manual partial capture payment- Create + Confirm", () => {
- it("customer-create-call-test", () => {
- cy.createCustomerCallTest(customerCreateBody, globalState);
- });
-
- it("create+confirm-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["SaveCardUseNo3DS"];
- cy.createConfirmPaymentTest(createConfirmPaymentBody, det, "no_three_ds", "automatic", globalState);
- });
-
- it("retrieve-payment-call-test", () => {
- cy.retrievePaymentCallTest(globalState);
- });
-
- it("retrieve-customerPM-call-test", () => {
- cy.listCustomerPMCallTest(globalState);
- });
-
- it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
- cy.createPaymentIntentTest(createPaymentBody, det, "no_three_ds", "manual", globalState);
- });
-
-
- it("confirm-save-card-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["SaveCardUseNo3DS"];
- cy.saveCardConfirmCallTest(confirmBody, det, globalState);
- });
-
- it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["No3DS"];
- cy.captureCallTest(captureBody, 5500, det.paymentSuccessfulStatus, globalState);
- });
- });
-
-});
\ No newline at end of file
+
+ context("Save card for NoThreeDS automatic capture payment- Create+Confirm", () => {
+ it("customer-create-call-test", () => {
+ cy.createCustomerCallTest(customerCreateBody, globalState);
+ });
+
+ it("create+confirm-payment-call-test", () => {
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DS"];
+ cy.createConfirmPaymentTest( createConfirmPaymentBody, det,"no_three_ds", "automatic", globalState);
+ });
+
+ it("retrieve-payment-call-test", () => {
+ cy.retrievePaymentCallTest(globalState);
+ });
+
+ it("retrieve-customerPM-call-test", () => {
+ cy.listCustomerPMCallTest(globalState);
+ });
+
+ it("create-payment-call-test", () => {
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DS"];
+ cy.createPaymentIntentTest( createPaymentBody, det, "no_three_ds", "automatic", globalState);
+ });
+
+ it ("confirm-save-card-payment-call-test", () => {
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DS"];
+ cy.saveCardConfirmCallTest(SaveCardConfirmBody,det,globalState);
+ });
+
+ });
+
+ context("Save card for NoThreeDS manual full capture payment- Create+Confirm", () => {
+ it("customer-create-call-test", () => {
+ cy.createCustomerCallTest(customerCreateBody, globalState);
+ });
+
+ it("create+confirm-payment-call-test", () => {
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DS"];
+ cy.createConfirmPaymentTest( createConfirmPaymentBody, det,"no_three_ds", "automatic", globalState);
+ });
+
+ it("retrieve-payment-call-test", () => {
+ cy.retrievePaymentCallTest(globalState);
+ });
+
+ it("retrieve-customerPM-call-test", () => {
+ cy.listCustomerPMCallTest(globalState);
+ });
+
+ it("create-payment-call-test", () => {
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DS"];
+ cy.createPaymentIntentTest( createPaymentBody, det, "no_three_ds", "manual", globalState);
+ });
+
+
+ it ("confirm-save-card-payment-call-test", () => {
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DS"];
+ cy.saveCardConfirmCallTest(SaveCardConfirmBody,det,globalState);
+ });
+
+ it("capture-call-test", () => {
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DS"];
+ cy.captureCallTest(captureBody, 6500, det.paymentSuccessfulStatus, globalState);
+ });
+
+
+ context("Save card for NoThreeDS manual partial capture payment- Create + Confirm", () => {
+ it("customer-create-call-test", () => {
+ cy.createCustomerCallTest(customerCreateBody, globalState);
+ });
+
+ it("create+confirm-payment-call-test", () => {
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DS"];
+ cy.createConfirmPaymentTest( createConfirmPaymentBody, det,"no_three_ds", "automatic", globalState);
+ });
+
+ it("retrieve-payment-call-test", () => {
+ cy.retrievePaymentCallTest(globalState);
+ });
+
+ it("retrieve-customerPM-call-test", () => {
+ cy.listCustomerPMCallTest(globalState);
+ });
+
+ it("create-payment-call-test", () => {
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DS"];
+ cy.createPaymentIntentTest( createPaymentBody, det, "no_three_ds", "manual", globalState);
+ });
+
+
+ it ("confirm-save-card-payment-call-test", () => {
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DS"];
+ cy.saveCardConfirmCallTest(SaveCardConfirmBody,det,globalState);
+ });
+
+ it("capture-call-test", () => {
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["SaveCardUseNo3DS"];
+ cy.captureCallTest(captureBody, 5500, det.paymentSuccessfulStatus, globalState);
+ });
+ });
+ });
+
+})
\ No newline at end of file
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00014-ZeroAuthMandate.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00014-ZeroAuthMandate.cy.js
index 0208ca595ce..23b9526f58b 100644
--- a/cypress-tests/cypress/e2e/ConnectorTest/00014-ZeroAuthMandate.cy.js
+++ b/cypress-tests/cypress/e2e/ConnectorTest/00014-ZeroAuthMandate.cy.js
@@ -23,7 +23,7 @@ describe("Card - SingleUse Mandates flow test", () => {
context("Card - NoThreeDS Create + Confirm Automatic CIT and Single use MIT payment flow test", () => {
it("Confirm No 3DS CIT", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateSingleUseNo3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateSingleUseNo3DS"];
cy.citForMandatesCallTest(citConfirmBody, 0, det, true, "automatic", "setup_mandate", globalState);
});
@@ -34,7 +34,7 @@ describe("Card - SingleUse Mandates flow test", () => {
context("Card - NoThreeDS Create + Confirm Automatic CIT and Multi use MIT payment flow test", () => {
it("Confirm No 3DS CIT", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["MandateSingleUseNo3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["MandateSingleUseNo3DS"];
cy.citForMandatesCallTest(citConfirmBody, 0, det, true, "automatic", "setup_mandate", globalState);
});
diff --git a/cypress-tests/cypress/e2e/ConnectorTest/00015-ThreeDSManualCapture.cy.js b/cypress-tests/cypress/e2e/ConnectorTest/00015-ThreeDSManualCapture.cy.js
index 9b3a29a92e0..fb308c7fbec 100644
--- a/cypress-tests/cypress/e2e/ConnectorTest/00015-ThreeDSManualCapture.cy.js
+++ b/cypress-tests/cypress/e2e/ConnectorTest/00015-ThreeDSManualCapture.cy.js
@@ -24,7 +24,7 @@ describe("Card - ThreeDS Manual payment flow test", () => {
context("Card - ThreeDS Manual Full Capture payment flow test", () => {
context("payment Create and Confirm", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "three_ds", "manual", globalState);
});
@@ -33,7 +33,7 @@ describe("Card - ThreeDS Manual payment flow test", () => {
});
it("confirm-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DS"];
cy.confirmCallTest(confirmBody, det, true, globalState);
});
@@ -47,7 +47,7 @@ describe("Card - ThreeDS Manual payment flow test", () => {
});
it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DS"];
cy.captureCallTest(captureBody, 6500, det.paymentSuccessfulStatus, globalState);
});
@@ -59,7 +59,7 @@ describe("Card - ThreeDS Manual payment flow test", () => {
context("Payment Create+Confirm", () => {
it("create+confirm-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DS"];
cy.createConfirmPaymentTest(createConfirmPaymentBody, det, "three_ds", "manual", globalState);
});
@@ -74,7 +74,7 @@ describe("Card - ThreeDS Manual payment flow test", () => {
});
it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DS"];
cy.captureCallTest(captureBody, 6540, det.paymentSuccessfulStatus, globalState);
});
@@ -89,7 +89,7 @@ describe("Card - ThreeDS Manual payment flow test", () => {
context("Card - ThreeDS Manual Partial Capture payment flow test - Create and Confirm", () => {
context("payment Create and Payment Confirm", () => {
it("create-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DS"];
cy.createPaymentIntentTest(createPaymentBody, det, "three_ds", "manual", globalState);
});
@@ -98,7 +98,7 @@ describe("Card - ThreeDS Manual payment flow test", () => {
});
it("confirm-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DS"];
cy.confirmCallTest(confirmBody, det, true, globalState);
});
@@ -112,7 +112,7 @@ describe("Card - ThreeDS Manual payment flow test", () => {
});
it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DS"];
cy.captureCallTest(captureBody, 100, det.paymentSuccessfulStatus, globalState);
});
@@ -123,7 +123,7 @@ describe("Card - ThreeDS Manual payment flow test", () => {
context("payment + Confirm", () => {
it("create+confirm-payment-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DS"];
cy.createConfirmPaymentTest(createConfirmPaymentBody, det, "three_ds", "manual", globalState);
});
@@ -137,7 +137,7 @@ describe("Card - ThreeDS Manual payment flow test", () => {
});
it("capture-call-test", () => {
- let det = getConnectorDetails(globalState.get("connectorId"))["3DS"];
+ let det = getConnectorDetails(globalState.get("connectorId"))["card_pm"]["3DS"];
cy.captureCallTest(captureBody, 5000, det.paymentSuccessfulStatus, globalState);
});
diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Adyen.js b/cypress-tests/cypress/e2e/ConnectorUtils/Adyen.js
index 68f3303e7fe..94ffe3009f6 100644
--- a/cypress-tests/cypress/e2e/ConnectorUtils/Adyen.js
+++ b/cypress-tests/cypress/e2e/ConnectorUtils/Adyen.js
@@ -16,6 +16,7 @@ const successfulThreeDSTestCardDetails = {
};
export const connectorDetails = {
+card_pm:{
"3DS": {
"card": successfulThreeDSTestCardDetails,
"currency": "USD",
@@ -109,4 +110,5 @@ export const connectorDetails = {
}
},
},
+}
};
\ No newline at end of file
diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/BankOfAmerica.js b/cypress-tests/cypress/e2e/ConnectorUtils/BankOfAmerica.js
index f89d7279ff7..d92b66e965f 100644
--- a/cypress-tests/cypress/e2e/ConnectorUtils/BankOfAmerica.js
+++ b/cypress-tests/cypress/e2e/ConnectorUtils/BankOfAmerica.js
@@ -16,6 +16,7 @@ const successfulThreeDSTestCardDetails = {
};
export const connectorDetails = {
+card_pm:{
"3DS": {
"card": successfulThreeDSTestCardDetails,
"currency": "USD",
@@ -109,5 +110,5 @@ export const connectorDetails = {
}
},
},
-
+}
};
\ No newline at end of file
diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Bluesnap.js b/cypress-tests/cypress/e2e/ConnectorUtils/Bluesnap.js
index 2b3f63529b1..540152eb6c3 100644
--- a/cypress-tests/cypress/e2e/ConnectorUtils/Bluesnap.js
+++ b/cypress-tests/cypress/e2e/ConnectorUtils/Bluesnap.js
@@ -15,6 +15,7 @@ const successfulThreeDSTestCardDetails = {
};
export const connectorDetails = {
+card_pm:{
"3DS": {
"card": successfulThreeDSTestCardDetails,
"currency": "USD",
@@ -108,4 +109,5 @@ export const connectorDetails = {
}
},
},
+ }
};
\ No newline at end of file
diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Cybersource.js b/cypress-tests/cypress/e2e/ConnectorUtils/Cybersource.js
index 53a936adb11..ec81ddc20c7 100644
--- a/cypress-tests/cypress/e2e/ConnectorUtils/Cybersource.js
+++ b/cypress-tests/cypress/e2e/ConnectorUtils/Cybersource.js
@@ -15,6 +15,7 @@ const successfulThreeDSTestCardDetails = {
};
export const connectorDetails = {
+card_pm:{
"3DS": {
"card": successfulThreeDSTestCardDetails,
"currency": "USD",
@@ -108,4 +109,5 @@ export const connectorDetails = {
}
},
},
+ }
};
\ No newline at end of file
diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Nmi.js b/cypress-tests/cypress/e2e/ConnectorUtils/Nmi.js
index 280778028b3..55d25a8ecf9 100644
--- a/cypress-tests/cypress/e2e/ConnectorUtils/Nmi.js
+++ b/cypress-tests/cypress/e2e/ConnectorUtils/Nmi.js
@@ -15,6 +15,7 @@ const successfulThreeDSTestCardDetails = {
};
export const connectorDetails = {
+card_pm:{
"3DS": {
"card": successfulThreeDSTestCardDetails,
"currency": "USD",
@@ -109,4 +110,5 @@ export const connectorDetails = {
}
},
},
+ }
};
\ No newline at end of file
diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Paypal.js b/cypress-tests/cypress/e2e/ConnectorUtils/Paypal.js
index 4a3bb998cf7..b0e876a7127 100644
--- a/cypress-tests/cypress/e2e/ConnectorUtils/Paypal.js
+++ b/cypress-tests/cypress/e2e/ConnectorUtils/Paypal.js
@@ -16,87 +16,91 @@ const successfulThreeDSTestCardDetails = {
};
export const connectorDetails = {
- "3DS": {
- "card": successfulThreeDSTestCardDetails,
- "currency": "USD",
- "paymentSuccessfulStatus": "processing",
- "paymentSyncStatus": "processing",
- "customer_acceptance": null,
- "setup_future_usage": "on_session",
-
- },
- "No3DS": {
- "card": successfulNo3DSCardDetails,
- "currency": "USD",
- "paymentSuccessfulStatus": "processing",
- "paymentSyncStatus": "processing",
- "customer_acceptance": null,
- "setup_future_usage": "on_session",
-
- },
- "MandateSingleUse3DS": {
- "card": successfulThreeDSTestCardDetails,
- "currency": "USD",
- "paymentSuccessfulStatus": "requires_customer_action",
- "paymentSyncStatus": "processing",
- "mandate_type": {
- "single_use": {
- "amount": 8000,
- "currency": "USD"
- }
- }
- },
- "MandateSingleUseNo3DS": {
- "card": successfulNo3DSCardDetails,
- "currency": "USD",
- "paymentSuccessfulStatus": "succeeded",
- "paymentSyncStatus": "succeeded",
- "mandate_type": {
- "single_use": {
- "amount": 8000,
- "currency": "USD"
+ card_pm:{
+ "3DS": {
+ "card": successfulThreeDSTestCardDetails,
+ "currency": "USD",
+ "paymentSuccessfulStatus": "requires_customer_action",
+ "paymentSyncStatus": "processing",
+ "customer_acceptance":null,
+ "setup_future_usage": "on_session",
+
+ },
+ "No3DS": {
+ "card": successfulNo3DSCardDetails,
+ "currency": "USD",
+ "paymentSuccessfulStatus": "processing",
+ "paymentSyncStatus": "processing",
+ "customer_acceptance":null,
+ "setup_future_usage": "on_session",
+
+ },
+ "MandateSingleUse3DS": {
+ "card": successfulThreeDSTestCardDetails,
+ "currency": "USD",
+ "paymentSuccessfulStatus": "requires_customer_action",
+ "paymentSyncStatus": "processing",
+ "mandate_type": {
+ "single_use": {
+ "amount": 8000,
+ "currency": "USD"
+ }
}
- }
- },
- "MandateMultiUseNo3DS": {
- "card": successfulNo3DSCardDetails,
- "currency": "USD",
- "paymentSuccessfulStatus": "succeeded",
- "paymentSyncStatus": "succeeded",
- "mandate_type": {
- "multi_use": {
- "amount": 8000,
- "currency": "USD"
+ },
+ "MandateSingleUseNo3DS": {
+ "card": successfulNo3DSCardDetails,
+ "currency": "USD",
+ "paymentSuccessfulStatus": "succeeded",
+ "paymentSyncStatus": "succeeded",
+ "mandate_type": {
+ "single_use": {
+ "amount": 8000,
+ "currency": "USD"
+ }
}
- }
- },
- "MandateMultiUse3DS": {
- "card": successfulThreeDSTestCardDetails,
- "currency": "USD",
- "paymentSuccessfulStatus": "requires_customer_action",
- "paymentSyncStatus": "processing",
- "mandate_type": {
- "multi_use": {
- "amount": 8000,
- "currency": "USD"
+ },
+ "MandateMultiUseNo3DS": {
+ "card": successfulNo3DSCardDetails,
+ "currency": "USD",
+ "paymentSuccessfulStatus": "succeeded",
+ "paymentSyncStatus": "succeeded",
+ "mandate_type": {
+ "multi_use": {
+ "amount": 8000,
+ "currency": "USD"
+ }
}
- }
- },
- "SaveCardUseNo3DS": {
- "card": successfulNo3DSCardDetails,
- "currency": "USD",
- "paymentSuccessfulStatus": "processing",
- "paymentSyncStatus": "succeeded",
- "refundStatus": "succeeded",
- "refundSyncStatus": "succeeded",
- "setup_future_usage": "on_session",
- "customer_acceptance": {
- "acceptance_type": "offline",
- "accepted_at": "1963-05-03T04:07:52.723Z",
- "online": {
- "ip_address": "127.0.0.1",
- "user_agent": "amet irure esse"
+ },
+ "MandateMultiUse3DS": {
+ "card": successfulThreeDSTestCardDetails,
+ "currency": "USD",
+ "paymentSuccessfulStatus": "requires_customer_action",
+ "paymentSyncStatus": "processing",
+ "mandate_type": {
+ "multi_use": {
+ "amount": 8000,
+ "currency": "USD"
+ }
}
},
+ "SaveCardUseNo3DS": {
+ "card": successfulNo3DSCardDetails,
+ "currency":"USD",
+ "paymentSuccessfulStatus": "processing",
+ "paymentSyncStatus": "succeeded",
+ "refundStatus": "succeeded",
+ "refundSyncStatus": "succeeded",
+ "setup_future_usage": "on_session",
+ "customer_acceptance": {
+ "acceptance_type": "offline",
+ "accepted_at": "1963-05-03T04:07:52.723Z",
+ "online": {
+ "ip_address": "127.0.0.1",
+ "user_agent": "amet irure esse"
+ }
+ },
+ },
},
-};
\ No newline at end of file
+};
+
+
diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Stripe.js b/cypress-tests/cypress/e2e/ConnectorUtils/Stripe.js
index 43c136a87d2..fb0683db2ad 100644
--- a/cypress-tests/cypress/e2e/ConnectorUtils/Stripe.js
+++ b/cypress-tests/cypress/e2e/ConnectorUtils/Stripe.js
@@ -18,6 +18,7 @@ const successfulThreeDSTestCardDetails = {
};
export const connectorDetails = {
+card_pm:{
"3DS": {
"card": successfulThreeDSTestCardDetails,
"currency": "USD",
@@ -111,4 +112,5 @@ export const connectorDetails = {
}
},
},
+}
};
\ No newline at end of file
diff --git a/cypress-tests/cypress/e2e/ConnectorUtils/Trustpay.js b/cypress-tests/cypress/e2e/ConnectorUtils/Trustpay.js
index 596da099406..71d0348c5ee 100644
--- a/cypress-tests/cypress/e2e/ConnectorUtils/Trustpay.js
+++ b/cypress-tests/cypress/e2e/ConnectorUtils/Trustpay.js
@@ -15,6 +15,7 @@ const successfulThreeDSTestCardDetails = {
};
export const connectorDetails = {
+card_pm:{
"3DS": {
"card": successfulThreeDSTestCardDetails,
"currency": "USD",
@@ -108,4 +109,5 @@ export const connectorDetails = {
}
},
},
-};
\ No newline at end of file
+}
+}
\ No newline at end of file
diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js
index 3caed6e0771..e6acee36649 100644
--- a/cypress-tests/cypress/support/commands.js
+++ b/cypress-tests/cypress/support/commands.js
@@ -295,12 +295,12 @@ Cypress.Commands.add("createConfirmPaymentTest", (createConfirmPaymentBody, deta
});
// This is consequent saved card payment confirm call test(Using payment token)
-Cypress.Commands.add("saveCardConfirmCallTest", (confirmBody, det, globalState) => {
+Cypress.Commands.add("saveCardConfirmCallTest", (SaveCardConfirmBody,det,globalState) => {
const paymentIntentID = globalState.get("paymentID");
- confirmBody.card_cvc = det.card.card_cvc;
- confirmBody.payment_token = globalState.get("paymentToken");
- confirmBody.client_secret = globalState.get("clientSecret");
- console.log("configured connector ->" + globalState.get("connectorId"));
+ SaveCardConfirmBody.card_cvc = det.card_cvc;
+ SaveCardConfirmBody.payment_token = globalState.get("paymentToken");
+ SaveCardConfirmBody.client_secret = globalState.get("clientSecret");
+ console.log("conf conn ->" + globalState.get("connectorId"));
cy.request({
method: "POST",
url: `${globalState.get("baseUrl")}/payments/${paymentIntentID}/confirm`,
@@ -308,7 +308,7 @@ Cypress.Commands.add("saveCardConfirmCallTest", (confirmBody, det, globalState)
"Content-Type": "application/json",
"api-key": globalState.get("publishableKey"),
},
- body: confirmBody,
+ body: SaveCardConfirmBody,
})
.then((response) => {
logRequestId(response.headers['x-request-id']);
@@ -731,5 +731,8 @@ Cypress.Commands.add("listRefundCallTest", (requestBody, globalState) => {
expect(response.headers["content-type"]).to.include("application/json");
expect(response.body.data).to.be.an('array').and.not.empty;
+
+ });
});
-});
+
+
|
ci
|
Fix card expiry for savecard flows (#4585)
|
4311f2ce5ea16c8850fb657462912b99bf0ad8fc
|
2023-08-11 08:13:06
|
github-actions
|
chore(version): v1.20.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9cbd09907aa..512c20af90e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,33 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.20.0 (2023-08-11)
+
+### Features
+
+- **connector:** [PayMe] Implement preprocessing flow for cards ([#1904](https://github.com/juspay/hyperswitch/pull/1904)) ([`38b9c07`](https://github.com/juspay/hyperswitch/commit/38b9c077b7cd9563aaf3f39876670df7484f519d))
+- **router:** Add webhook source verification support for multiple mca of the same connector ([#1897](https://github.com/juspay/hyperswitch/pull/1897)) ([`3554fec`](https://github.com/juspay/hyperswitch/commit/3554fec1c1ab6084480600c73fbefe39085723e0))
+
+### Bug Fixes
+
+- **connector:**
+ - [STAX] Add currency filter for payments through Stax ([#1911](https://github.com/juspay/hyperswitch/pull/1911)) ([`5bc7592`](https://github.com/juspay/hyperswitch/commit/5bc7592af3c8587a402809c050e58b257b7af8bf))
+ - [Paypal] send valid error_reason in all the error responses ([#1914](https://github.com/juspay/hyperswitch/pull/1914)) ([`3df9441`](https://github.com/juspay/hyperswitch/commit/3df944196f710587eee32be871eaef1d764b694a))
+- **payment_methods:** Delete token when a payment reaches terminal state ([#1818](https://github.com/juspay/hyperswitch/pull/1818)) ([`07020d0`](https://github.com/juspay/hyperswitch/commit/07020d01b5d08d9ba5a146d62fbb8c23c6a6d3c2))
+
+### Refactors
+
+- **storage:** Add a separate crate to represent store implementations ([#1853](https://github.com/juspay/hyperswitch/pull/1853)) ([`32b731d`](https://github.com/juspay/hyperswitch/commit/32b731d9591ff4921b7d80556c7ebe050b53121f))
+
+### Miscellaneous Tasks
+
+- **webhooks:** Ignore payment not found in webhooks ([#1886](https://github.com/juspay/hyperswitch/pull/1886)) ([`29f068b`](https://github.com/juspay/hyperswitch/commit/29f068b20581fca280be9a1a98524368d635191f))
+
+**Full Changelog:** [`v1.19.0...v1.20.0`](https://github.com/juspay/hyperswitch/compare/v1.19.0...v1.20.0)
+
+- - -
+
+
## 1.19.0 (2023-08-10)
### Features
|
chore
|
v1.20.0
|
3ddfe53838c6b039dc5f669ccd23d3035521d691
|
2024-09-24 19:48:39
|
Mani Chandra
|
feat(users): Add entity type filter in list users and list roles API (#5997)
| false
|
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index 81b38198cfc..eb09abd471c 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -2,12 +2,12 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
role::{
- CreateRoleRequest, GetRoleRequest, ListRolesAtEntityLevelRequest, ListRolesResponse,
- RoleInfoResponseNew, RoleInfoWithGroupsResponse, RoleInfoWithPermissionsResponse,
- UpdateRoleRequest,
+ CreateRoleRequest, GetRoleRequest, ListRolesAtEntityLevelRequest, ListRolesRequest,
+ ListRolesResponse, RoleInfoResponseNew, RoleInfoWithGroupsResponse,
+ RoleInfoWithPermissionsResponse, UpdateRoleRequest,
},
AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest,
- MerchantSelectRequest, UpdateUserRoleRequest,
+ ListUsersInEntityRequest, MerchantSelectRequest, UpdateUserRoleRequest,
};
common_utils::impl_api_event_type!(
@@ -25,6 +25,8 @@ common_utils::impl_api_event_type!(
ListRolesResponse,
ListRolesAtEntityLevelRequest,
RoleInfoResponseNew,
- RoleInfoWithGroupsResponse
+ RoleInfoWithGroupsResponse,
+ ListUsersInEntityRequest,
+ ListRolesRequest
)
);
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 8e1a0483c07..f2743d6a311 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -159,3 +159,8 @@ pub struct Entity {
pub entity_id: String,
pub entity_type: common_enums::EntityType,
}
+
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct ListUsersInEntityRequest {
+ pub entity_type: Option<common_enums::EntityType>,
+}
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index 828dfeb20f8..be467421e65 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -35,6 +35,11 @@ pub struct RoleInfoWithGroupsResponse {
pub role_scope: RoleScope,
}
+#[derive(Debug, serde::Deserialize, serde::Serialize)]
+pub struct ListRolesRequest {
+ pub entity_type: Option<EntityType>,
+}
+
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoResponseNew {
pub role_id: String,
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index d42f71695a5..fd9c8c89031 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -673,6 +673,7 @@ pub async fn delete_user_role(
pub async fn list_users_in_lineage(
state: SessionState,
user_from_token: auth::UserFromToken,
+ request: user_role_api::ListUsersInEntityRequest,
) -> UserResponse<Vec<user_role_api::ListUsersInEntityResponse>> {
let requestor_role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
&state,
@@ -683,51 +684,55 @@ pub async fn list_users_in_lineage(
.await
.change_context(UserErrors::InternalServerError)?;
- let user_roles_set: HashSet<_> = match requestor_role_info.get_entity_type() {
- EntityType::Organization => state
- .store
- .list_user_roles_by_org_id(ListUserRolesByOrgIdPayload {
- user_id: None,
- org_id: &user_from_token.org_id,
- merchant_id: None,
- profile_id: None,
- version: None,
- })
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .collect(),
- EntityType::Merchant => state
- .store
- .list_user_roles_by_org_id(ListUserRolesByOrgIdPayload {
- user_id: None,
- org_id: &user_from_token.org_id,
- merchant_id: Some(&user_from_token.merchant_id),
- profile_id: None,
- version: None,
- })
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .collect(),
+ let user_roles_set: HashSet<_> = match utils::user_role::get_min_entity(
+ requestor_role_info.get_entity_type(),
+ request.entity_type,
+ )? {
+ EntityType::Organization => {
+ utils::user_role::fetch_user_roles_by_payload(
+ &state,
+ ListUserRolesByOrgIdPayload {
+ user_id: None,
+ org_id: &user_from_token.org_id,
+ merchant_id: None,
+ profile_id: None,
+ version: None,
+ },
+ request.entity_type,
+ )
+ .await?
+ }
+ EntityType::Merchant => {
+ utils::user_role::fetch_user_roles_by_payload(
+ &state,
+ ListUserRolesByOrgIdPayload {
+ user_id: None,
+ org_id: &user_from_token.org_id,
+ merchant_id: Some(&user_from_token.merchant_id),
+ profile_id: None,
+ version: None,
+ },
+ request.entity_type,
+ )
+ .await?
+ }
EntityType::Profile => {
let Some(profile_id) = user_from_token.profile_id.as_ref() else {
return Err(UserErrors::JwtProfileIdMissing.into());
};
- state
- .store
- .list_user_roles_by_org_id(ListUserRolesByOrgIdPayload {
+ utils::user_role::fetch_user_roles_by_payload(
+ &state,
+ ListUserRolesByOrgIdPayload {
user_id: None,
org_id: &user_from_token.org_id,
merchant_id: Some(&user_from_token.merchant_id),
profile_id: Some(profile_id),
version: None,
- })
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .collect()
+ },
+ request.entity_type,
+ )
+ .await?
}
EntityType::Internal => HashSet::new(),
};
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index 571ae7f995d..ffc18214c20 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -217,6 +217,7 @@ pub async fn update_role(
pub async fn list_roles_with_info(
state: SessionState,
user_from_token: UserFromToken,
+ request: role_api::ListRolesRequest,
) -> UserResponse<Vec<role_api::RoleInfoResponseNew>> {
let user_role_info = user_from_token
.get_role_info_from_db(&state)
@@ -229,49 +230,57 @@ pub async fn list_roles_with_info(
.collect::<Vec<_>>();
let user_role_entity = user_role_info.get_entity_type();
- let custom_roles = match user_role_entity {
- EntityType::Organization => state
- .store
- .list_roles_for_org_by_parameters(&user_from_token.org_id, None, None, None)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to get roles")?,
- EntityType::Merchant => state
- .store
- .list_roles_for_org_by_parameters(
- &user_from_token.org_id,
- Some(&user_from_token.merchant_id),
- None,
- None,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Failed to get roles")?,
- // TODO: Populate this from Db function when support for profile id and profile level custom roles is added
- EntityType::Profile => Vec::new(),
- EntityType::Internal => {
- return Err(UserErrors::InvalidRoleOperationWithMessage(
- "Internal roles are not allowed for this operation".to_string(),
- )
- .into());
- }
- };
+ let custom_roles =
+ match utils::user_role::get_min_entity(user_role_entity, request.entity_type)? {
+ EntityType::Organization => state
+ .store
+ .list_roles_for_org_by_parameters(
+ &user_from_token.org_id,
+ None,
+ request.entity_type,
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get roles")?,
+ EntityType::Merchant => state
+ .store
+ .list_roles_for_org_by_parameters(
+ &user_from_token.org_id,
+ Some(&user_from_token.merchant_id),
+ request.entity_type,
+ None,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)
+ .attach_printable("Failed to get roles")?,
+ // TODO: Populate this from Db function when support for profile id and profile level custom roles is added
+ EntityType::Profile => Vec::new(),
+ EntityType::Internal => {
+ return Err(UserErrors::InvalidRoleOperationWithMessage(
+ "Internal roles are not allowed for this operation".to_string(),
+ )
+ .into());
+ }
+ };
role_info_vec.extend(custom_roles.into_iter().map(roles::RoleInfo::from));
+
let list_role_info_response = role_info_vec
.into_iter()
.filter_map(|role_info| {
- if user_role_entity >= role_info.get_entity_type() {
- Some(role_api::RoleInfoResponseNew {
- role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
- groups: role_info.get_permission_groups().to_vec(),
- entity_type: role_info.get_entity_type(),
- scope: role_info.get_scope(),
- })
- } else {
- None
- }
+ let is_lower_entity = user_role_entity >= role_info.get_entity_type();
+ let request_filter = request.entity_type.map_or(true, |entity_type| {
+ entity_type == role_info.get_entity_type()
+ });
+
+ (is_lower_entity && request_filter).then_some(role_api::RoleInfoResponseNew {
+ role_id: role_info.get_role_id().to_string(),
+ role_name: role_info.get_role_name().to_string(),
+ groups: role_info.get_permission_groups().to_vec(),
+ entity_type: role_info.get_entity_type(),
+ scope: role_info.get_scope(),
+ })
})
.collect::<Vec<_>>();
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index b1260b5d7ad..922e7612b14 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -291,16 +291,20 @@ pub async fn get_role_information(
.await
}
-pub async fn list_users_in_lineage(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+pub async fn list_users_in_lineage(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<user_role_api::ListUsersInEntityRequest>,
+) -> HttpResponse {
let flow = Flow::ListUsersInLineage;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
- (),
- |state, user_from_token, _, _| {
- user_role_core::list_users_in_lineage(state, user_from_token)
+ query.into_inner(),
+ |state, user_from_token, request, _| {
+ user_role_core::list_users_in_lineage(state, user_from_token, request)
},
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
@@ -308,15 +312,21 @@ pub async fn list_users_in_lineage(state: web::Data<AppState>, req: HttpRequest)
.await
}
-pub async fn list_roles_with_info(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+pub async fn list_roles_with_info(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<role_api::ListRolesRequest>,
+) -> HttpResponse {
let flow = Flow::ListRolesV2;
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
- (),
- |state, user_from_token, _, _| role_core::list_roles_with_info(state, user_from_token),
+ query.into_inner(),
+ |state, user_from_token, request, _| {
+ role_core::list_roles_with_info(state, user_from_token, request)
+ },
&auth::JWTAuth {
permission: Permission::UsersRead,
minimum_entity_level: EntityType::Profile,
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index b4008bd0008..9141b91bdd6 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -14,7 +14,7 @@ use storage_impl::errors::StorageError;
use crate::{
consts,
core::errors::{UserErrors, UserResult},
- db::user_role::ListUserRolesByUserIdPayload,
+ db::user_role::{ListUserRolesByOrgIdPayload, ListUserRolesByUserIdPayload},
routes::SessionState,
services::authorization::{self as authz, permissions::Permission, roles},
types::domain,
@@ -398,3 +398,61 @@ pub async fn get_single_merchant_id_and_profile_id(
Ok((merchant_id, profile_id))
}
+
+pub async fn fetch_user_roles_by_payload(
+ state: &SessionState,
+ payload: ListUserRolesByOrgIdPayload<'_>,
+ request_entity_type: Option<EntityType>,
+) -> UserResult<HashSet<UserRole>> {
+ Ok(state
+ .store
+ .list_user_roles_by_org_id(payload)
+ .await
+ .change_context(UserErrors::InternalServerError)?
+ .into_iter()
+ .filter_map(|user_role| {
+ let (_entity_id, entity_type) = user_role.get_entity_id_and_type()?;
+ request_entity_type
+ .map_or(true, |req_entity_type| entity_type == req_entity_type)
+ .then_some(user_role)
+ })
+ .collect::<HashSet<_>>())
+}
+
+pub fn get_min_entity(
+ user_entity: EntityType,
+ filter_entity: Option<EntityType>,
+) -> UserResult<EntityType> {
+ match (user_entity, filter_entity) {
+ (EntityType::Organization, None)
+ | (EntityType::Organization, Some(EntityType::Organization)) => {
+ Ok(EntityType::Organization)
+ }
+
+ (EntityType::Merchant, None)
+ | (EntityType::Organization, Some(EntityType::Merchant))
+ | (EntityType::Merchant, Some(EntityType::Merchant)) => Ok(EntityType::Merchant),
+
+ (EntityType::Profile, None)
+ | (EntityType::Organization, Some(EntityType::Profile))
+ | (EntityType::Merchant, Some(EntityType::Profile))
+ | (EntityType::Profile, Some(EntityType::Profile)) => Ok(EntityType::Profile),
+
+ (EntityType::Internal, _) => Ok(EntityType::Internal),
+
+ (EntityType::Organization, Some(EntityType::Internal))
+ | (EntityType::Merchant, Some(EntityType::Internal))
+ | (EntityType::Profile, Some(EntityType::Internal)) => {
+ Err(UserErrors::InvalidRoleOperation.into())
+ }
+
+ (EntityType::Merchant, Some(EntityType::Organization))
+ | (EntityType::Profile, Some(EntityType::Organization))
+ | (EntityType::Profile, Some(EntityType::Merchant)) => {
+ Err(report!(UserErrors::InvalidRoleOperation)).attach_printable(format!(
+ "{} level user requesting data for {:?} level",
+ user_entity, filter_entity
+ ))
+ }
+ }
+}
|
feat
|
Add entity type filter in list users and list roles API (#5997)
|
b6249f226116a7cc96e602a8910e8b186eecda5b
|
2024-12-26 05:56:24
|
github-actions
|
chore(version): 2024.12.26.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eb5af00abb1..8c2aef45774 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,26 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.12.26.0
+
+### Features
+
+- **router:** Add endpoint for listing connector features ([#6612](https://github.com/juspay/hyperswitch/pull/6612)) ([`a423ff5`](https://github.com/juspay/hyperswitch/commit/a423ff53d3523508ba6c584134e32f3f1bb4f0c0))
+
+### Bug Fixes
+
+- **cors:** Expose all headers set by application in `access-control-expose-headers` header value ([#6877](https://github.com/juspay/hyperswitch/pull/6877)) ([`9c3547f`](https://github.com/juspay/hyperswitch/commit/9c3547fa8dd5930613380014025add33ccd5db4a))
+- **payments_list:** Handle same payment/attempt ids for different merchants ([#6917](https://github.com/juspay/hyperswitch/pull/6917)) ([`2e472e3`](https://github.com/juspay/hyperswitch/commit/2e472e3fee0c33b3ce8affc520db7a512ed41b2f))
+- **wasm:** Remove chasenet from jpmorgan wasm as ChaseNet doesn’t exist in PMT ([#6927](https://github.com/juspay/hyperswitch/pull/6927)) ([`5e4eded`](https://github.com/juspay/hyperswitch/commit/5e4eded8fa13c9cb4a1d648ab5c133e86522c29c))
+
+### Refactors
+
+- **core:** Remove merchant return url from `router_data` ([#6895](https://github.com/juspay/hyperswitch/pull/6895)) ([`c5717a8`](https://github.com/juspay/hyperswitch/commit/c5717a8147899e0c690e234dbf9b4fd425a7bb71))
+
+**Full Changelog:** [`2024.12.24.0...2024.12.26.0`](https://github.com/juspay/hyperswitch/compare/2024.12.24.0...2024.12.26.0)
+
+- - -
+
## 2024.12.24.0
### Features
|
chore
|
2024.12.26.0
|
49d5ad7b3c24fc9c9847b473fda370398e3c7e38
|
2023-06-17 13:06:26
|
Mani Chandra
|
feat: add new error response for 403 (#1330)
| false
|
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index bb0fe46b7ee..00460d4cce8 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -367,6 +367,7 @@ impl From<errors::ApiErrorResponse> for StripeErrorCode {
errors::ApiErrorResponse::Unauthorized
| errors::ApiErrorResponse::InvalidJwtToken
| errors::ApiErrorResponse::GenericUnauthorized { .. }
+ | errors::ApiErrorResponse::AccessForbidden
| 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 cd637e96c42..9387719d369 100644
--- a/crates/router/src/core/errors/api_error_response.rs
+++ b/crates/router/src/core/errors/api_error_response.rs
@@ -89,6 +89,8 @@ pub enum ApiErrorResponse {
FlowNotSupported { flow: String, connector: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_21", message = "Missing required params")]
MissingRequiredFields { field_names: Vec<&'static str> },
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_22", message = "Access forbidden. Not authorized to access this resource")]
+ AccessForbidden,
#[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "{code}: {message}", ignore = "status_code")]
ExternalConnectorError {
code: String,
@@ -243,8 +245,9 @@ impl actix_web::ResponseError for ApiErrorResponse {
Self::ExternalConnectorError { status_code, .. } => {
StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)
}
+ Self::AccessForbidden => StatusCode::FORBIDDEN, // 403
Self::InvalidRequestUrl | Self::WebhookResourceNotFound => StatusCode::NOT_FOUND, // 404
- Self::InvalidHttpMethod => StatusCode::METHOD_NOT_ALLOWED, // 405
+ Self::InvalidHttpMethod => StatusCode::METHOD_NOT_ALLOWED, // 405
Self::MissingRequiredField { .. }
| Self::MissingRequiredFields { .. }
| Self::InvalidDataValue { .. }
@@ -415,6 +418,7 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::MissingRequiredFields { field_names } => AER::BadRequest(
ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })),
),
+ Self::AccessForbidden => AER::ForbiddenCommonResource(ApiError::new("IR", 22, "Access forbidden. Not authorized to access this resource", None)),
Self::ExternalConnectorError {
code,
message,
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 88680aece5f..d6e9350e0ff 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -241,7 +241,7 @@ where
}
#[derive(Debug)]
-pub struct JWTAuth;
+pub(crate) struct JWTAuth;
#[derive(serde::Deserialize)]
struct JwtAuthPayloadFetchUnit {
@@ -315,19 +315,6 @@ impl ClientSecretFetch for api_models::cards_info::CardsInfoRequest {
}
}
-pub fn jwt_auth_or<'a, T: AuthInfo, A: AppStateInfo>(
- default_auth: &'a dyn AuthenticateAndFetch<T, A>,
- headers: &HeaderMap,
-) -> Box<&'a dyn AuthenticateAndFetch<T, A>>
-where
- JWTAuth: AuthenticateAndFetch<T, A>,
-{
- if is_jwt_auth(headers) {
- return Box::new(&JWTAuth);
- }
- Box::new(default_auth)
-}
-
pub fn get_auth_type_and_flow<A: AppStateInfo + Sync>(
headers: &HeaderMap,
) -> RouterResult<(
|
feat
|
add new error response for 403 (#1330)
|
776ed9a2eb0e5ad8125112fe01bb3ea4b34195bc
|
2025-01-20 18:53:35
|
Kashif
|
refactor(payment-link): use shouldRemoveBeforeUnloadEvents flag for handling removal of beforeunload events through SDK (#7072)
| false
|
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
index d45a72b5e55..bc851bbeb19 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
@@ -27,7 +27,12 @@ function initializeSDK() {
// @ts-ignore
hyper = window.Hyper(pub_key, {
isPreloadEnabled: false,
+ // TODO: Remove in next deployment
shouldUseTopRedirection: true,
+ redirectionFlags: {
+ shouldRemoveBeforeUnloadEvents: true,
+ shouldUseTopRedirection: true,
+ }
});
// @ts-ignore
widgets = hyper.widgets({
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js
index 4bddc6904be..290df7d1203 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js
+++ b/crates/router/src/core/payment_link/payment_link_initiate/secure_payment_link_initiator.js
@@ -48,7 +48,12 @@ if (!isFramed) {
// @ts-ignore
hyper = window.Hyper(pub_key, {
isPreloadEnabled: false,
+ // TODO: Remove in next deployment
shouldUseTopRedirection: true,
+ redirectionFlags: {
+ shouldRemoveBeforeUnloadEvents: true,
+ shouldUseTopRedirection: true,
+ }
});
// @ts-ignore
widgets = hyper.widgets({
|
refactor
|
use shouldRemoveBeforeUnloadEvents flag for handling removal of beforeunload events through SDK (#7072)
|
b66f91034beab4078f360ecbb3607b55df556eae
|
2024-08-29 19:33:02
|
Pa1NarK
|
ci(cypress): add auto-retry tests to routing (#5713)
| false
|
diff --git a/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js b/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js
new file mode 100644
index 00000000000..024c5356fe2
--- /dev/null
+++ b/cypress-tests/cypress/e2e/RoutingTest/00003-Retries.cy.js
@@ -0,0 +1,626 @@
+import * as fixtures from "../../fixtures/imports";
+import State from "../../utils/State";
+import * as utils from "../RoutingUtils/Utils";
+
+let globalState;
+
+describe("Auto Retries & Step Up 3DS", () => {
+ context("Login", () => {
+ before("seed global state", () => {
+ cy.task("getGlobalState").then((state) => {
+ globalState = new State(state);
+ });
+ });
+
+ afterEach("flush global state", () => {
+ cy.task("setGlobalState", globalState.data);
+ });
+
+ it("Create JWT token", () => {
+ let data = utils.getConnectorDetails("common")["jwt"];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+
+ cy.createJWTToken(req_data, res_data, globalState);
+ });
+
+ it("List MCA", () => {
+ cy.ListMcaByMid(globalState);
+ });
+
+ it("API key create call", () => {
+ cy.apiKeyCreateTest(fixtures.apiKeyCreateBody, globalState);
+ });
+
+ it("Customer create call", () => {
+ cy.createCustomerCallTest(fixtures.customerCreateBody, globalState);
+ });
+
+ it("Retrieve Merchant", () => {
+ cy.merchantRetrieveCall(globalState);
+ });
+ });
+
+ context("Auto Retries", () => {
+ context("[Config: enable] Auto retries", () => {
+ it("Enable auto retries", () => {
+ cy.autoRetryConfig(fixtures.configs.gsm, globalState, "true");
+ });
+
+ context("Max auto retries", () => {
+ context("Adyen -> Stripe auto retries", () => {
+ context("Enable routing configs", () => {
+ before("seed global state", () => {
+ cy.task("getGlobalState").then((state) => {
+ globalState = new State(state);
+ });
+ });
+
+ afterEach("flush global state", () => {
+ cy.task("setGlobalState", globalState.data);
+ });
+
+ it("Add routing config", () => {
+ let data = utils.getConnectorDetails("common")["routing"];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+
+ let routing_data = [
+ {
+ connector: "adyen",
+ merchant_connector_id: globalState.get("adyenMcaId"),
+ },
+ {
+ connector: "stripe",
+ merchant_connector_id: globalState.get("stripeMcaId"),
+ },
+ {
+ connector: "bluesnap",
+ merchant_connector_id: globalState.get("bluesnapMcaId"),
+ },
+ ];
+ cy.addRoutingConfig(
+ fixtures.routingConfigBody,
+ req_data,
+ res_data,
+ "priority",
+ routing_data,
+ globalState
+ );
+ });
+
+ it("Activate routing config", () => {
+ let data = utils.getConnectorDetails("common")["routing"];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.activateRoutingConfig(req_data, res_data, globalState);
+ });
+ });
+
+ context("Max auto retries = 2", () => {
+ const max_auto_retries = 2;
+ it("Update max auto retries", () => {
+ cy.setMaxAutoRetries(
+ fixtures.configs.max_auto_retries,
+ globalState,
+ `${max_auto_retries}`
+ );
+ });
+
+ context("Make payment", () => {
+ it("Payment create call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "PaymentIntent"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.createPaymentIntentTest(
+ fixtures.createPaymentBody,
+ req_data,
+ res_data,
+ "no_three_ds",
+ "automatic",
+ globalState
+ );
+ });
+
+ it("Payment confirm call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "BluesnapConfirm"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.confirmCallTest(
+ fixtures.confirmBody,
+ req_data,
+ res_data,
+ true,
+ globalState
+ );
+ });
+
+ it("Payment retrieve call", () => {
+ cy.retrievePaymentCallTest(
+ globalState,
+ true,
+ max_auto_retries + 1
+ );
+ });
+ });
+ });
+
+ context("Max auto retries = 1", () => {
+ const max_auto_retries = 1;
+ it("Update max auto retries", () => {
+ cy.setMaxAutoRetries(
+ fixtures.configs.max_auto_retries,
+ globalState,
+ `${max_auto_retries}`
+ );
+ });
+
+ context("Make payment", () => {
+ it("Payment create call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "PaymentIntent"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.createPaymentIntentTest(
+ fixtures.createPaymentBody,
+ req_data,
+ res_data,
+ "no_three_ds",
+ "automatic",
+ globalState
+ );
+ });
+
+ it("Payment confirm call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "StripeConfirmSuccess"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.confirmCallTest(
+ fixtures.confirmBody,
+ req_data,
+ res_data,
+ true,
+ globalState
+ );
+ });
+
+ it("Payment retrieve call", () => {
+ cy.retrievePaymentCallTest(
+ globalState,
+ true,
+ max_auto_retries + 1
+ );
+ });
+ });
+ });
+ context("Max auto retries = 0", () => {
+ const max_auto_retries = 0;
+ it("Update max auto retries", () => {
+ cy.setMaxAutoRetries(
+ fixtures.configs.max_auto_retries,
+ globalState,
+ `${max_auto_retries}`
+ );
+ });
+
+ context("Make payment", () => {
+ it("Payment create call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "PaymentIntent"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.createPaymentIntentTest(
+ fixtures.createPaymentBody,
+ req_data,
+ res_data,
+ "no_three_ds",
+ "automatic",
+ globalState
+ );
+ });
+
+ it("Payment confirm call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "AdyenConfirmFail"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.confirmCallTest(
+ fixtures.confirmBody,
+ req_data,
+ res_data,
+ true,
+ globalState
+ );
+ });
+
+ it("Payment retrieve call", () => {
+ cy.retrievePaymentCallTest(
+ globalState,
+ true,
+ max_auto_retries + 1
+ );
+ });
+ });
+ });
+ });
+
+ context("Stripe -> Adyen auto retries", () => {
+ context("Enable routing configs", () => {
+ before("seed global state", () => {
+ cy.task("getGlobalState").then((state) => {
+ globalState = new State(state);
+ });
+ });
+
+ afterEach("flush global state", () => {
+ cy.task("setGlobalState", globalState.data);
+ });
+
+ it("Add routing config", () => {
+ let data = utils.getConnectorDetails("common")["routing"];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+
+ let routing_data = [
+ {
+ connector: "stripe",
+ merchant_connector_id: globalState.get("stripeMcaId"),
+ },
+ {
+ connector: "adyen",
+ merchant_connector_id: globalState.get("adyenMcaId"),
+ },
+ {
+ connector: "bluesnap",
+ merchant_connector_id: globalState.get("bluesnapMcaId"),
+ },
+ ];
+ cy.addRoutingConfig(
+ fixtures.routingConfigBody,
+ req_data,
+ res_data,
+ "priority",
+ routing_data,
+ globalState
+ );
+ });
+
+ it("Activate routing config", () => {
+ let data = utils.getConnectorDetails("common")["routing"];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.activateRoutingConfig(req_data, res_data, globalState);
+ });
+ });
+
+ context("Max auto retries = 2", () => {
+ const max_auto_retries = 2;
+ it("Update max auto retries", () => {
+ cy.setMaxAutoRetries(
+ fixtures.configs.max_auto_retries,
+ globalState,
+ `${max_auto_retries}`
+ );
+ });
+
+ context("Make payment", () => {
+ it("Payment create call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "PaymentIntent"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.createPaymentIntentTest(
+ fixtures.createPaymentBody,
+ req_data,
+ res_data,
+ "no_three_ds",
+ "automatic",
+ globalState
+ );
+ });
+
+ it("Payment confirm call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "BluesnapConfirm"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.confirmCallTest(
+ fixtures.confirmBody,
+ req_data,
+ res_data,
+ true,
+ globalState
+ );
+ });
+
+ it("Payment retrieve call", () => {
+ cy.retrievePaymentCallTest(
+ globalState,
+ true,
+ max_auto_retries + 1
+ );
+ });
+ });
+ });
+
+ context("Max auto retries = 1", () => {
+ const max_auto_retries = 1;
+ it("Update max auto retries", () => {
+ cy.setMaxAutoRetries(
+ fixtures.configs.max_auto_retries,
+ globalState,
+ `${max_auto_retries}`
+ );
+ });
+
+ context("Make payment", () => {
+ it("Payment create call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "PaymentIntent"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.createPaymentIntentTest(
+ fixtures.createPaymentBody,
+ req_data,
+ res_data,
+ "no_three_ds",
+ "automatic",
+ globalState
+ );
+ });
+
+ it("Payment confirm call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "AdyenConfirm"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.confirmCallTest(
+ fixtures.confirmBody,
+ req_data,
+ res_data,
+ true,
+ globalState
+ );
+ });
+
+ it("Payment retrieve call", () => {
+ cy.retrievePaymentCallTest(
+ globalState,
+ true,
+ max_auto_retries + 1
+ );
+ });
+ });
+ });
+
+ context("Max auto retries = 0", () => {
+ const max_auto_retries = 0;
+ it("Update max auto retries", () => {
+ cy.setMaxAutoRetries(
+ fixtures.configs.max_auto_retries,
+ globalState,
+ `${max_auto_retries}`
+ );
+ });
+
+ context("Make payment", () => {
+ it("Payment create call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "PaymentIntent"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.createPaymentIntentTest(
+ fixtures.createPaymentBody,
+ req_data,
+ res_data,
+ "no_three_ds",
+ "automatic",
+ globalState
+ );
+ });
+
+ it("Payment confirm call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "StripeConfirmFail"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.confirmCallTest(
+ fixtures.confirmBody,
+ req_data,
+ res_data,
+ true,
+ globalState
+ );
+ });
+
+ it("Payment retrieve call", () => {
+ cy.retrievePaymentCallTest(
+ globalState,
+ true,
+ max_auto_retries + 1
+ );
+ });
+ });
+ });
+ });
+ });
+
+ context("Step up 3DS", () => {
+ context("[Config: set] GSM", () => {
+ it("[Config: enable] Step up GSM", () => {
+ cy.updateGsmConfig(fixtures.gsmBody.gsm_update, globalState, true);
+ });
+
+ it("[Config: enable] Step up for Stripe", () => {
+ cy.stepUp(fixtures.configs.step_up, globalState, '["stripe"]');
+ });
+ });
+
+ context("Make Payment", () => {
+ const max_auto_retries = 1;
+ it("Update max auto retries", () => {
+ cy.setMaxAutoRetries(
+ fixtures.configs.max_auto_retries,
+ globalState,
+ `${max_auto_retries}`
+ );
+ });
+
+ it("Payment create call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "PaymentIntent"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.createPaymentIntentTest(
+ fixtures.createPaymentBody,
+ req_data,
+ res_data,
+ "no_three_ds",
+ "automatic",
+ globalState
+ );
+ });
+
+ it("Payment confirm call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "StripeConfirm3DS"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.confirmCallTest(
+ fixtures.confirmBody,
+ req_data,
+ res_data,
+ true,
+ globalState
+ );
+ });
+
+ it("Payment retrieve call", () => {
+ cy.retrievePaymentCallTest(globalState, true, max_auto_retries + 1);
+ });
+ });
+ });
+ });
+
+ context("[Config: disable] Auto retries", () => {
+ it("[Config: disable] Auto retries", () => {
+ cy.autoRetryConfig(fixtures.configs.gsm, globalState, "false");
+ });
+
+ it("[Config: disable] Step up GSM", () => {
+ cy.updateGsmConfig(fixtures.gsmBody.gsm_update, globalState, false);
+ });
+
+ context("Make payment", () => {
+ context("[Failed] Make payment", () => {
+ it("Payment create call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "PaymentIntent"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.createPaymentIntentTest(
+ fixtures.createPaymentBody,
+ req_data,
+ res_data,
+ "no_three_ds",
+ "automatic",
+ globalState
+ );
+ });
+
+ it("Payment confirm call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "StripeConfirmFail"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.confirmCallTest(
+ fixtures.confirmBody,
+ req_data,
+ res_data,
+ true,
+ globalState
+ );
+ });
+
+ it("Payment retrieve call", () => {
+ cy.retrievePaymentCallTest(globalState, true);
+ });
+ });
+
+ context("[Succeeded] Make payment", () => {
+ it("Payment create call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "PaymentIntent"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.createPaymentIntentTest(
+ fixtures.createPaymentBody,
+ req_data,
+ res_data,
+ "no_three_ds",
+ "automatic",
+ globalState
+ );
+ });
+
+ it("Payment confirm call", () => {
+ let data =
+ utils.getConnectorDetails("autoretries")["card_pm"][
+ "StripeConfirmSuccess"
+ ];
+ let req_data = data["Request"];
+ let res_data = data["Response"];
+ cy.confirmCallTest(
+ fixtures.confirmBody,
+ req_data,
+ res_data,
+ true,
+ globalState
+ );
+ });
+
+ it("Payment retrieve call", () => {
+ cy.retrievePaymentCallTest(globalState, true);
+ });
+ });
+ });
+ });
+ });
+});
diff --git a/cypress-tests/cypress/e2e/RoutingUtils/Autoretries.js b/cypress-tests/cypress/e2e/RoutingUtils/Autoretries.js
new file mode 100644
index 00000000000..cedd411926b
--- /dev/null
+++ b/cypress-tests/cypress/e2e/RoutingUtils/Autoretries.js
@@ -0,0 +1,149 @@
+const card_1142 = {
+ card_number: "4111111145551142",
+ card_exp_month: "03",
+ card_exp_year: "30",
+ card_holder_name: "Borino",
+ card_cvc: "737",
+};
+const card_4242 = {
+ card_number: "4242424242424242",
+ card_exp_month: "03",
+ card_exp_year: "30",
+ card_holder_name: "Borino",
+ card_cvc: "737",
+};
+const card_9299 = {
+ card_number: "4263982640269299",
+ card_exp_month: "02",
+ card_exp_year: "26",
+ card_holder_name: "Borino",
+ card_cvc: "837",
+};
+
+export const connectorDetails = {
+ card_pm: {
+ AdyenConfirm: {
+ Request: {
+ payment_method: "card",
+ payment_method_type: "debit",
+ payment_method_data: {
+ card: card_1142,
+ },
+ currency: "USD",
+ customer_acceptance: null,
+ setup_future_usage: "on_session",
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ connector: "adyen",
+ },
+ },
+ },
+ AdyenConfirmFail: {
+ Request: {
+ payment_method: "card",
+ payment_method_type: "debit",
+ payment_method_data: {
+ card: card_4242,
+ },
+ },
+ Response: {
+ body: {
+ status: "failed",
+ connector: "adyen",
+ },
+ },
+ },
+ BluesnapConfirm: {
+ Request: {
+ payment_method: "card",
+ payment_method_type: "debit",
+ payment_method_data: {
+ card: card_9299,
+ },
+ currency: "USD",
+ customer_acceptance: null,
+ setup_future_usage: "on_session",
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ connector: "bluesnap",
+ },
+ },
+ },
+ PaymentIntent: {
+ Request: {
+ currency: "USD",
+ customer_acceptance: null,
+ setup_future_usage: "on_session",
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_payment_method",
+ },
+ },
+ },
+ StripeConfirmFail: {
+ Request: {
+ payment_method: "card",
+ payment_method_type: "debit",
+ payment_method_data: {
+ card: card_1142,
+ },
+ currency: "USD",
+ customer_acceptance: null,
+ setup_future_usage: "on_session",
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "failed",
+ connector: "stripe",
+ },
+ },
+ },
+ StripeConfirm3DS: {
+ Request: {
+ payment_method: "card",
+ payment_method_type: "debit",
+ payment_method_data: {
+ card: card_1142,
+ },
+ currency: "USD",
+ customer_acceptance: null,
+ setup_future_usage: "on_session",
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_customer_action",
+ connector: "stripe",
+ },
+ },
+ },
+ StripeConfirmSuccess: {
+ Request: {
+ payment_method: "card",
+ payment_method_type: "debit",
+ payment_method_data: {
+ card: card_4242,
+ },
+ currency: "USD",
+ customer_acceptance: null,
+ setup_future_usage: "on_session",
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "succeeded",
+ connector: "stripe",
+ },
+ },
+ },
+ },
+};
diff --git a/cypress-tests/cypress/e2e/RoutingUtils/Utils.js b/cypress-tests/cypress/e2e/RoutingUtils/Utils.js
index 02175b52461..ad92999c287 100644
--- a/cypress-tests/cypress/e2e/RoutingUtils/Utils.js
+++ b/cypress-tests/cypress/e2e/RoutingUtils/Utils.js
@@ -1,9 +1,11 @@
import { connectorDetails as adyenConnectorDetails } from "./Adyen.js";
+import { connectorDetails as autoretryConnectorDetails } from "./Autoretries.js";
import { connectorDetails as commonConnectorDetails } from "./Commons.js";
import { connectorDetails as stripeConnectorDetails } from "./Stripe.js";
const connectorDetails = {
adyen: adyenConnectorDetails,
+ autoretries: autoretryConnectorDetails,
common: commonConnectorDetails,
stripe: stripeConnectorDetails,
};
diff --git a/cypress-tests/cypress/fixtures/configs.json b/cypress-tests/cypress/fixtures/configs.json
new file mode 100644
index 00000000000..7b2ff2469d8
--- /dev/null
+++ b/cypress-tests/cypress/fixtures/configs.json
@@ -0,0 +1,14 @@
+{
+ "gsm": {
+ "key": "",
+ "value": ""
+ },
+ "max_auto_retries": {
+ "key": "",
+ "value": ""
+ },
+ "step_up": {
+ "key": "",
+ "value": ""
+ }
+}
diff --git a/cypress-tests/cypress/fixtures/gsm-body.json b/cypress-tests/cypress/fixtures/gsm-body.json
new file mode 100644
index 00000000000..81b6c973a0f
--- /dev/null
+++ b/cypress-tests/cypress/fixtures/gsm-body.json
@@ -0,0 +1,12 @@
+{
+ "gsm_update": {
+ "connector": "stripe",
+ "flow": "Authorize",
+ "sub_flow": "sub_flow",
+ "code": "card_declined",
+ "message": "card_declined",
+ "status": "failure",
+ "decision": "retry",
+ "step_up_possible": ""
+ }
+}
diff --git a/cypress-tests/cypress/fixtures/imports.js b/cypress-tests/cypress/fixtures/imports.js
index 4816c8a45bd..d5cc66b7d29 100644
--- a/cypress-tests/cypress/fixtures/imports.js
+++ b/cypress-tests/cypress/fixtures/imports.js
@@ -1,4 +1,5 @@
import captureBody from "./capture-flow-body.json";
+import configs from "./configs.json";
import confirmBody from "./confirm-body.json";
import apiKeyCreateBody from "./create-api-key-body.json";
import createConfirmPaymentBody from "./create-confirm-body.json";
@@ -9,6 +10,7 @@ import mitConfirmBody from "./create-mandate-mit.json";
import createPaymentBody from "./create-payment-body.json";
import createPayoutBody from "./create-payout-confirm-body.json";
import pmIdConfirmBody from "./create-pm-id-mit.json";
+import gsmBody from "./gsm-body.json";
import listRefundCall from "./list-refund-call-body.json";
import merchantCreateBody from "./merchant-create-body.json";
import merchantUpdateBody from "./merchant-update-body.json";
@@ -25,6 +27,7 @@ export {
apiKeyUpdateBody,
captureBody,
citConfirmBody,
+ configs,
confirmBody,
createConfirmPaymentBody,
createConnectorBody,
@@ -32,6 +35,7 @@ export {
createPayoutBody,
customerCreateBody,
customerUpdateBody,
+ gsmBody,
listRefundCall,
merchantCreateBody,
merchantUpdateBody,
diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js
index a0e8cd19408..c5708c258bb 100644
--- a/cypress-tests/cypress/support/commands.js
+++ b/cypress-tests/cypress/support/commands.js
@@ -84,7 +84,10 @@ Cypress.Commands.add("merchantRetrieveCall", (globalState) => {
expect(response.body.default_profile).to.not.be.empty;
expect(response.body.organization_id).to.not.be.empty;
globalState.set("organizationId", response.body.organization_id);
- globalState.set("publishableKey", response.body.publishable_key);
+
+ if (globalState.get("publishableKey") === undefined) {
+ globalState.set("publishableKey", response.body.publishable_key);
+ }
});
});
@@ -1394,25 +1397,56 @@ Cypress.Commands.add(
}
);
-Cypress.Commands.add("retrievePaymentCallTest", (globalState) => {
- const payment_id = globalState.get("paymentID");
- cy.request({
- method: "GET",
- url: `${globalState.get("baseUrl")}/payments/${payment_id}?force_sync=true`,
- headers: {
- "Content-Type": "application/json",
- "api-key": globalState.get("apiKey"),
- },
- failOnStatusCode: false,
- }).then((response) => {
- logRequestId(response.headers["x-request-id"]);
+Cypress.Commands.add(
+ "retrievePaymentCallTest",
+ (globalState, autoretries = false, attempt = 1) => {
+ const payment_id = globalState.get("paymentID");
+ cy.request({
+ method: "GET",
+ url: `${globalState.get("baseUrl")}/payments/${payment_id}?force_sync=true&expand_attempts=true`,
+ headers: {
+ "Content-Type": "application/json",
+ "api-key": globalState.get("apiKey"),
+ },
+ failOnStatusCode: false,
+ }).then((response) => {
+ logRequestId(response.headers["x-request-id"]);
- expect(response.headers["content-type"]).to.include("application/json");
- expect(response.body.payment_id).to.equal(payment_id);
- expect(response.body.amount).to.equal(globalState.get("paymentAmount"));
- globalState.set("paymentID", response.body.payment_id);
- });
-});
+ expect(response.headers["content-type"]).to.include("application/json");
+ expect(response.body.payment_id).to.equal(payment_id);
+ expect(response.body.amount).to.equal(globalState.get("paymentAmount"));
+ globalState.set("paymentID", response.body.payment_id);
+
+ if (autoretries) {
+ expect(response.body).to.have.property("attempts");
+ expect(response.body.attempts).to.be.an("array").and.not.empty;
+ expect(response.body.attempts.length).to.equal(attempt);
+ expect(response.body.attempts[0].attempt_id).to.include(
+ `${payment_id}_`
+ );
+ for (const key in response.body.attempts) {
+ if (
+ response.body.attempts[key].attempt_id ===
+ `${payment_id}_${attempt}` &&
+ response.body.status === "succeeded"
+ ) {
+ expect(response.body.attempts[key].status).to.equal("charged");
+ } else if (
+ response.body.attempts[key].attempt_id ===
+ `${payment_id}_${attempt}` &&
+ response.body.status === "requires_customer_action"
+ ) {
+ expect(response.body.attempts[key].status).to.equal(
+ "authentication_pending"
+ );
+ } else {
+ expect(response.body.attempts[key].status).to.equal("failure");
+ }
+ }
+ }
+ });
+ }
+);
Cypress.Commands.add(
"refundCallTest",
@@ -2092,6 +2126,7 @@ Cypress.Commands.add("ListMcaByMid", (globalState) => {
globalState.set("profileId", response.body[0].profile_id);
globalState.set("stripeMcaId", response.body[0].merchant_connector_id);
globalState.set("adyenMcaId", response.body[1].merchant_connector_id);
+ globalState.set("bluesnapMcaId", response.body[3].merchant_connector_id);
});
});
@@ -2190,3 +2225,110 @@ Cypress.Commands.add(
});
}
);
+
+Cypress.Commands.add(
+ "autoRetryConfig",
+ (autoRetryGsmBody, globalState, value) => {
+ const key = `should_call_gsm_${globalState.get("merchantId")}`;
+ autoRetryGsmBody.key = key;
+ autoRetryGsmBody.value = value;
+
+ cy.request({
+ method: "POST",
+ url: `${globalState.get("baseUrl")}/configs/${key}`,
+ headers: {
+ Accept: "application/json",
+ "Content-Type": "application/json",
+ "api-key": globalState.get("adminApiKey"),
+ },
+ body: autoRetryGsmBody,
+ failOnStatusCode: false,
+ }).then((response) => {
+ logRequestId(response.headers["x-request-id"]);
+
+ if (response.status === 200) {
+ expect(response.body).to.have.property("key").to.equal(key);
+ expect(response.body).to.have.property("value").to.equal(value);
+ }
+ });
+ }
+);
+
+Cypress.Commands.add(
+ "setMaxAutoRetries",
+ (maxAutoRetryBody, globalState, value) => {
+ const key = `max_auto_retries_enabled_${globalState.get("merchantId")}`;
+ maxAutoRetryBody.key = key;
+ maxAutoRetryBody.value = value;
+
+ cy.request({
+ method: "POST",
+ url: `${globalState.get("baseUrl")}/configs/${key}`,
+ headers: {
+ Accept: "application/json",
+ "Content-Type": "application/json",
+ "api-key": globalState.get("adminApiKey"),
+ },
+ body: maxAutoRetryBody,
+ failOnStatusCode: false,
+ }).then((response) => {
+ logRequestId(response.headers["x-request-id"]);
+ if (response.status === 200) {
+ expect(response.body).to.have.property("key").to.equal(key);
+ expect(response.body).to.have.property("value").to.equal(value);
+ }
+ });
+ }
+);
+
+Cypress.Commands.add(
+ "updateGsmConfig",
+ (gsmBody, globalState, step_up_possible) => {
+ gsmBody.step_up_possible = step_up_possible;
+ cy.request({
+ method: "POST",
+ url: `${globalState.get("baseUrl")}/gsm/update`,
+ headers: {
+ "Content-Type": "application/json",
+ "api-key": globalState.get("adminApiKey"),
+ },
+ body: gsmBody,
+ failOnStatusCode: false,
+ }).then((response) => {
+ logRequestId(response.headers["x-request-id"]);
+ if (response.status === 200) {
+ expect(response.body)
+ .to.have.property("message")
+ .to.equal("card_declined");
+ expect(response.body).to.have.property("connector").to.equal("stripe");
+ expect(response.body)
+ .to.have.property("step_up_possible")
+ .to.equal(step_up_possible);
+ }
+ });
+ }
+);
+
+Cypress.Commands.add("stepUp", (stepUpBody, globalState, value) => {
+ const key = `step_up_enabled_${globalState.get("merchantId")}`;
+ stepUpBody.key = key;
+ stepUpBody.value = value;
+
+ cy.request({
+ method: "POST",
+ url: `${globalState.get("baseUrl")}/configs/${key}`,
+ headers: {
+ "Content-Type": "application/json",
+ "api-key": globalState.get("adminApiKey"),
+ },
+ body: stepUpBody,
+ failOnStatusCode: false,
+ }).then((response) => {
+ logRequestId(response.headers["x-request-id"]);
+
+ if (response.status === 200) {
+ expect(response.body).to.have.property("key").to.equal(key);
+ expect(response.body).to.have.property("value").to.equal(value);
+ }
+ });
+});
|
ci
|
add auto-retry tests to routing (#5713)
|
ce1e165cecade481ce6002795049d6a9ffec96e2
|
2024-04-10 14:52:19
|
Swangi Kumari
|
refactor(payment_methods): add some payment method data to new domain type to be used in connector module (#4234)
| false
|
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index cf39d9f5bb9..568eab11ffb 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -734,9 +734,9 @@ pub enum OnlineBankingCzechRepublicBanks {
C,
}
-impl TryFrom<&Box<payments::JCSVoucherData>> for JCSVoucherData {
+impl TryFrom<&Box<domain::JCSVoucherData>> for JCSVoucherData {
type Error = Error;
- fn try_from(jcs_data: &Box<payments::JCSVoucherData>) -> Result<Self, Self::Error> {
+ fn try_from(jcs_data: &Box<domain::JCSVoucherData>) -> Result<Self, Self::Error> {
Ok(Self {
first_name: jcs_data.first_name.clone(),
last_name: jcs_data.last_name.clone(),
@@ -1593,7 +1593,7 @@ impl<'a> TryFrom<&types::PaymentsPreProcessingRouterData> for AdyenBalanceReques
let payment_method = match &item.request.payment_method_data {
Some(domain::PaymentMethodData::GiftCard(gift_card_data)) => {
match gift_card_data.as_ref() {
- payments::GiftCardData::Givex(gift_card_data) => {
+ domain::GiftCardData::Givex(gift_card_data) => {
let balance_pm = BalancePmData {
payment_type: GiftCardBrand::Givex,
number: gift_card_data.number.clone(),
@@ -1603,7 +1603,7 @@ impl<'a> TryFrom<&types::PaymentsPreProcessingRouterData> for AdyenBalanceReques
balance_pm,
)))
}
- payments::GiftCardData::PaySafeCard {} => {
+ domain::GiftCardData::PaySafeCard {} => {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Balance".to_string(),
connector: "adyen".to_string(),
@@ -1797,24 +1797,22 @@ fn get_country_code(
address.and_then(|billing| billing.address.as_ref().and_then(|address| address.country))
}
-fn get_social_security_number(
- voucher_data: &api_models::payments::VoucherData,
-) -> Option<Secret<String>> {
+fn get_social_security_number(voucher_data: &domain::VoucherData) -> Option<Secret<String>> {
match voucher_data {
- payments::VoucherData::Boleto(boleto_data) => boleto_data.social_security_number.clone(),
- payments::VoucherData::Alfamart { .. }
- | payments::VoucherData::Indomaret { .. }
- | payments::VoucherData::Efecty
- | payments::VoucherData::PagoEfectivo
- | payments::VoucherData::RedCompra
- | payments::VoucherData::Oxxo
- | payments::VoucherData::RedPagos
- | payments::VoucherData::SevenEleven { .. }
- | payments::VoucherData::Lawson { .. }
- | payments::VoucherData::MiniStop { .. }
- | payments::VoucherData::FamilyMart { .. }
- | payments::VoucherData::Seicomart { .. }
- | payments::VoucherData::PayEasy { .. } => None,
+ domain::VoucherData::Boleto(boleto_data) => boleto_data.social_security_number.clone(),
+ domain::VoucherData::Alfamart { .. }
+ | domain::VoucherData::Indomaret { .. }
+ | domain::VoucherData::Efecty
+ | domain::VoucherData::PagoEfectivo
+ | domain::VoucherData::RedCompra
+ | domain::VoucherData::Oxxo
+ | domain::VoucherData::RedPagos
+ | domain::VoucherData::SevenEleven { .. }
+ | domain::VoucherData::Lawson { .. }
+ | domain::VoucherData::MiniStop { .. }
+ | domain::VoucherData::FamilyMart { .. }
+ | domain::VoucherData::Seicomart { .. }
+ | domain::VoucherData::PayEasy { .. } => None,
}
}
@@ -1888,48 +1886,48 @@ impl<'a> TryFrom<&api_models::payments::BankDebitData> for AdyenPaymentMethod<'a
}
}
-impl<'a> TryFrom<&api_models::payments::VoucherData> for AdyenPaymentMethod<'a> {
+impl<'a> TryFrom<&domain::VoucherData> for AdyenPaymentMethod<'a> {
type Error = Error;
- fn try_from(voucher_data: &api_models::payments::VoucherData) -> Result<Self, Self::Error> {
+ fn try_from(voucher_data: &domain::VoucherData) -> Result<Self, Self::Error> {
match voucher_data {
- payments::VoucherData::Boleto { .. } => Ok(AdyenPaymentMethod::BoletoBancario),
- payments::VoucherData::Alfamart(alfarmart_data) => {
+ domain::VoucherData::Boleto { .. } => Ok(AdyenPaymentMethod::BoletoBancario),
+ domain::VoucherData::Alfamart(alfarmart_data) => {
Ok(AdyenPaymentMethod::Alfamart(Box::new(DokuBankData {
first_name: alfarmart_data.first_name.clone(),
last_name: alfarmart_data.last_name.clone(),
shopper_email: alfarmart_data.email.clone(),
})))
}
- payments::VoucherData::Indomaret(indomaret_data) => {
+ domain::VoucherData::Indomaret(indomaret_data) => {
Ok(AdyenPaymentMethod::Indomaret(Box::new(DokuBankData {
first_name: indomaret_data.first_name.clone(),
last_name: indomaret_data.last_name.clone(),
shopper_email: indomaret_data.email.clone(),
})))
}
- payments::VoucherData::Oxxo => Ok(AdyenPaymentMethod::Oxxo),
- payments::VoucherData::SevenEleven(jcs_data) => Ok(AdyenPaymentMethod::SevenEleven(
+ domain::VoucherData::Oxxo => Ok(AdyenPaymentMethod::Oxxo),
+ domain::VoucherData::SevenEleven(jcs_data) => Ok(AdyenPaymentMethod::SevenEleven(
Box::new(JCSVoucherData::try_from(jcs_data)?),
)),
- payments::VoucherData::Lawson(jcs_data) => Ok(AdyenPaymentMethod::Lawson(Box::new(
+ domain::VoucherData::Lawson(jcs_data) => Ok(AdyenPaymentMethod::Lawson(Box::new(
JCSVoucherData::try_from(jcs_data)?,
))),
- payments::VoucherData::MiniStop(jcs_data) => Ok(AdyenPaymentMethod::MiniStop(
- Box::new(JCSVoucherData::try_from(jcs_data)?),
- )),
- payments::VoucherData::FamilyMart(jcs_data) => Ok(AdyenPaymentMethod::FamilyMart(
+ domain::VoucherData::MiniStop(jcs_data) => Ok(AdyenPaymentMethod::MiniStop(Box::new(
+ JCSVoucherData::try_from(jcs_data)?,
+ ))),
+ domain::VoucherData::FamilyMart(jcs_data) => Ok(AdyenPaymentMethod::FamilyMart(
Box::new(JCSVoucherData::try_from(jcs_data)?),
)),
- payments::VoucherData::Seicomart(jcs_data) => Ok(AdyenPaymentMethod::Seicomart(
+ domain::VoucherData::Seicomart(jcs_data) => Ok(AdyenPaymentMethod::Seicomart(
Box::new(JCSVoucherData::try_from(jcs_data)?),
)),
- payments::VoucherData::PayEasy(jcs_data) => Ok(AdyenPaymentMethod::PayEasy(Box::new(
+ domain::VoucherData::PayEasy(jcs_data) => Ok(AdyenPaymentMethod::PayEasy(Box::new(
JCSVoucherData::try_from(jcs_data)?,
))),
- payments::VoucherData::Efecty
- | payments::VoucherData::PagoEfectivo
- | payments::VoucherData::RedCompra
- | payments::VoucherData::RedPagos => Err(errors::ConnectorError::NotImplemented(
+ domain::VoucherData::Efecty
+ | domain::VoucherData::PagoEfectivo
+ | domain::VoucherData::RedCompra
+ | domain::VoucherData::RedPagos => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
)
.into()),
@@ -1937,12 +1935,12 @@ impl<'a> TryFrom<&api_models::payments::VoucherData> for AdyenPaymentMethod<'a>
}
}
-impl<'a> TryFrom<&api_models::payments::GiftCardData> for AdyenPaymentMethod<'a> {
+impl<'a> TryFrom<&domain::GiftCardData> for AdyenPaymentMethod<'a> {
type Error = Error;
- fn try_from(gift_card_data: &api_models::payments::GiftCardData) -> Result<Self, Self::Error> {
+ fn try_from(gift_card_data: &domain::GiftCardData) -> Result<Self, Self::Error> {
match gift_card_data {
- payments::GiftCardData::PaySafeCard {} => Ok(AdyenPaymentMethod::PaySafeCard),
- payments::GiftCardData::Givex(givex_data) => {
+ domain::GiftCardData::PaySafeCard {} => Ok(AdyenPaymentMethod::PaySafeCard),
+ domain::GiftCardData::Givex(givex_data) => {
let gift_card_pm = GiftCardData {
payment_type: PaymentType::Giftcard,
brand: GiftCardBrand::Givex,
@@ -2741,7 +2739,7 @@ impl<'a>
impl<'a>
TryFrom<(
&AdyenRouterData<&types::PaymentsAuthorizeRouterData>,
- &api_models::payments::VoucherData,
+ &domain::VoucherData,
)> for AdyenPaymentRequest<'a>
{
type Error = Error;
@@ -2749,7 +2747,7 @@ impl<'a>
fn try_from(
value: (
&AdyenRouterData<&types::PaymentsAuthorizeRouterData>,
- &api_models::payments::VoucherData,
+ &domain::VoucherData,
),
) -> Result<Self, Self::Error> {
let (item, voucher_data) = value;
@@ -2845,7 +2843,7 @@ impl<'a>
impl<'a>
TryFrom<(
&AdyenRouterData<&types::PaymentsAuthorizeRouterData>,
- &api_models::payments::GiftCardData,
+ &domain::GiftCardData,
)> for AdyenPaymentRequest<'a>
{
type Error = Error;
@@ -2853,7 +2851,7 @@ impl<'a>
fn try_from(
value: (
&AdyenRouterData<&types::PaymentsAuthorizeRouterData>,
- &api_models::payments::GiftCardData,
+ &domain::GiftCardData,
),
) -> Result<Self, Self::Error> {
let (item, gift_card_data) = value;
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 94f18e6b8d4..e5e4d13dbb9 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -701,39 +701,36 @@ impl TryFrom<&api_models::payments::BankTransferData> for PaypalPaymentsRequest
}
}
-impl TryFrom<&api_models::payments::VoucherData> for PaypalPaymentsRequest {
+impl TryFrom<&domain::VoucherData> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: &api_models::payments::VoucherData) -> Result<Self, Self::Error> {
+ fn try_from(value: &domain::VoucherData) -> Result<Self, Self::Error> {
match value {
- api_models::payments::VoucherData::Boleto(_)
- | api_models::payments::VoucherData::Efecty
- | api_models::payments::VoucherData::PagoEfectivo
- | api_models::payments::VoucherData::RedCompra
- | api_models::payments::VoucherData::RedPagos
- | api_models::payments::VoucherData::Alfamart(_)
- | api_models::payments::VoucherData::Indomaret(_)
- | api_models::payments::VoucherData::Oxxo
- | api_models::payments::VoucherData::SevenEleven(_)
- | api_models::payments::VoucherData::Lawson(_)
- | api_models::payments::VoucherData::MiniStop(_)
- | api_models::payments::VoucherData::FamilyMart(_)
- | api_models::payments::VoucherData::Seicomart(_)
- | api_models::payments::VoucherData::PayEasy(_) => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Paypal"),
- )
- .into())
- }
+ domain::VoucherData::Boleto(_)
+ | domain::VoucherData::Efecty
+ | domain::VoucherData::PagoEfectivo
+ | domain::VoucherData::RedCompra
+ | domain::VoucherData::RedPagos
+ | domain::VoucherData::Alfamart(_)
+ | domain::VoucherData::Indomaret(_)
+ | domain::VoucherData::Oxxo
+ | domain::VoucherData::SevenEleven(_)
+ | domain::VoucherData::Lawson(_)
+ | domain::VoucherData::MiniStop(_)
+ | domain::VoucherData::FamilyMart(_)
+ | domain::VoucherData::Seicomart(_)
+ | domain::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Paypal"),
+ )
+ .into()),
}
}
}
-impl TryFrom<&api_models::payments::GiftCardData> for PaypalPaymentsRequest {
+impl TryFrom<&domain::GiftCardData> for PaypalPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: &api_models::payments::GiftCardData) -> Result<Self, Self::Error> {
+ fn try_from(value: &domain::GiftCardData) -> Result<Self, Self::Error> {
match value {
- api_models::payments::GiftCardData::Givex(_)
- | api_models::payments::GiftCardData::PaySafeCard {} => {
+ domain::GiftCardData::Givex(_) | domain::GiftCardData::PaySafeCard {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Paypal"),
)
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index 372f110ab87..df4a38336b5 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -243,24 +243,24 @@ impl TryFrom<&api_models::payments::BankTransferData> for Shift4PaymentMethod {
}
}
-impl TryFrom<&api_models::payments::VoucherData> for Shift4PaymentMethod {
+impl TryFrom<&domain::VoucherData> for Shift4PaymentMethod {
type Error = Error;
- fn try_from(voucher_data: &api_models::payments::VoucherData) -> Result<Self, Self::Error> {
+ fn try_from(voucher_data: &domain::VoucherData) -> Result<Self, Self::Error> {
match voucher_data {
- payments::VoucherData::Boleto(_)
- | payments::VoucherData::Efecty
- | payments::VoucherData::PagoEfectivo
- | payments::VoucherData::RedCompra
- | payments::VoucherData::RedPagos
- | payments::VoucherData::Alfamart(_)
- | payments::VoucherData::Indomaret(_)
- | payments::VoucherData::Oxxo
- | payments::VoucherData::SevenEleven(_)
- | payments::VoucherData::Lawson(_)
- | payments::VoucherData::MiniStop(_)
- | payments::VoucherData::FamilyMart(_)
- | payments::VoucherData::Seicomart(_)
- | payments::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented(
+ domain::VoucherData::Boleto(_)
+ | domain::VoucherData::Efecty
+ | domain::VoucherData::PagoEfectivo
+ | domain::VoucherData::RedCompra
+ | domain::VoucherData::RedPagos
+ | domain::VoucherData::Alfamart(_)
+ | domain::VoucherData::Indomaret(_)
+ | domain::VoucherData::Oxxo
+ | domain::VoucherData::SevenEleven(_)
+ | domain::VoucherData::Lawson(_)
+ | domain::VoucherData::MiniStop(_)
+ | domain::VoucherData::FamilyMart(_)
+ | domain::VoucherData::Seicomart(_)
+ | domain::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
@@ -268,11 +268,11 @@ impl TryFrom<&api_models::payments::VoucherData> for Shift4PaymentMethod {
}
}
-impl TryFrom<&api_models::payments::GiftCardData> for Shift4PaymentMethod {
+impl TryFrom<&domain::GiftCardData> for Shift4PaymentMethod {
type Error = Error;
- fn try_from(gift_card_data: &api_models::payments::GiftCardData) -> Result<Self, Self::Error> {
+ fn try_from(gift_card_data: &domain::GiftCardData) -> Result<Self, Self::Error> {
match gift_card_data {
- payments::GiftCardData::Givex(_) | payments::GiftCardData::PaySafeCard {} => {
+ domain::GiftCardData::Givex(_) | domain::GiftCardData::PaySafeCard {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index 7c5ef36127c..219b3fb264d 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -1435,7 +1435,7 @@ fn create_stripe_payment_method(
.into()),
domain::PaymentMethodData::GiftCard(giftcard_data) => match giftcard_data.deref() {
- payments::GiftCardData::Givex(_) | payments::GiftCardData::PaySafeCard {} => {
+ domain::GiftCardData::Givex(_) | domain::GiftCardData::PaySafeCard {} => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
)
@@ -1459,24 +1459,24 @@ fn create_stripe_payment_method(
.into()),
domain::PaymentMethodData::Voucher(voucher_data) => match voucher_data {
- payments::VoucherData::Boleto(_) | payments::VoucherData::Oxxo => {
+ domain::VoucherData::Boleto(_) | domain::VoucherData::Oxxo => {
Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
)
.into())
}
- payments::VoucherData::Alfamart(_)
- | payments::VoucherData::Efecty
- | payments::VoucherData::PagoEfectivo
- | payments::VoucherData::RedCompra
- | payments::VoucherData::RedPagos
- | payments::VoucherData::Indomaret(_)
- | payments::VoucherData::SevenEleven(_)
- | payments::VoucherData::Lawson(_)
- | payments::VoucherData::MiniStop(_)
- | payments::VoucherData::FamilyMart(_)
- | payments::VoucherData::Seicomart(_)
- | payments::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented(
+ domain::VoucherData::Alfamart(_)
+ | domain::VoucherData::Efecty
+ | domain::VoucherData::PagoEfectivo
+ | domain::VoucherData::RedCompra
+ | domain::VoucherData::RedPagos
+ | domain::VoucherData::Indomaret(_)
+ | domain::VoucherData::SevenEleven(_)
+ | domain::VoucherData::Lawson(_)
+ | domain::VoucherData::MiniStop(_)
+ | domain::VoucherData::FamilyMart(_)
+ | domain::VoucherData::Seicomart(_)
+ | domain::VoucherData::PayEasy(_) => Err(errors::ConnectorError::NotImplemented(
connector_util::get_unimplemented_payment_method_error_message("stripe"),
)
.into()),
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 7d5afacd3f6..cc69c3f1f11 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -1115,7 +1115,7 @@ pub trait CryptoData {
fn get_pay_currency(&self) -> Result<String, Error>;
}
-impl CryptoData for api::CryptoData {
+impl CryptoData for domain::CryptoData {
fn get_pay_currency(&self) -> Result<String, Error> {
self.pay_currency
.clone()
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs
index 4f11af6a33a..b17762c703c 100644
--- a/crates/router/src/connector/zen/transformers.rs
+++ b/crates/router/src/connector/zen/transformers.rs
@@ -257,14 +257,14 @@ impl
impl
TryFrom<(
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
- &api_models::payments::VoucherData,
+ &domain::VoucherData,
)> for ZenPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
value: (
&ZenRouterData<&types::PaymentsAuthorizeRouterData>,
- &api_models::payments::VoucherData,
+ &domain::VoucherData,
),
) -> Result<Self, Self::Error> {
let (item, voucher_data) = value;
@@ -278,30 +278,22 @@ impl
return_url: item.router_data.request.get_router_return_url()?,
});
let payment_channel = match voucher_data {
- api_models::payments::VoucherData::Boleto { .. } => {
- ZenPaymentChannels::PclBoacompraBoleto
- }
- api_models::payments::VoucherData::Efecty => ZenPaymentChannels::PclBoacompraEfecty,
- api_models::payments::VoucherData::PagoEfectivo => {
- ZenPaymentChannels::PclBoacompraPagoefectivo
- }
- api_models::payments::VoucherData::RedCompra => {
- ZenPaymentChannels::PclBoacompraRedcompra
- }
- api_models::payments::VoucherData::RedPagos => ZenPaymentChannels::PclBoacompraRedpagos,
- api_models::payments::VoucherData::Oxxo { .. }
- | api_models::payments::VoucherData::Alfamart { .. }
- | api_models::payments::VoucherData::Indomaret { .. }
- | api_models::payments::VoucherData::SevenEleven { .. }
- | api_models::payments::VoucherData::Lawson { .. }
- | api_models::payments::VoucherData::MiniStop { .. }
- | api_models::payments::VoucherData::FamilyMart { .. }
- | api_models::payments::VoucherData::Seicomart { .. }
- | api_models::payments::VoucherData::PayEasy { .. } => {
- Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Zen"),
- ))?
- }
+ domain::VoucherData::Boleto { .. } => ZenPaymentChannels::PclBoacompraBoleto,
+ domain::VoucherData::Efecty => ZenPaymentChannels::PclBoacompraEfecty,
+ domain::VoucherData::PagoEfectivo => ZenPaymentChannels::PclBoacompraPagoefectivo,
+ domain::VoucherData::RedCompra => ZenPaymentChannels::PclBoacompraRedcompra,
+ domain::VoucherData::RedPagos => ZenPaymentChannels::PclBoacompraRedpagos,
+ domain::VoucherData::Oxxo { .. }
+ | domain::VoucherData::Alfamart { .. }
+ | domain::VoucherData::Indomaret { .. }
+ | domain::VoucherData::SevenEleven { .. }
+ | domain::VoucherData::Lawson { .. }
+ | domain::VoucherData::MiniStop { .. }
+ | domain::VoucherData::FamilyMart { .. }
+ | domain::VoucherData::Seicomart { .. }
+ | domain::VoucherData::PayEasy { .. } => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Zen"),
+ ))?,
};
Ok(Self::ApiRequest(Box::new(ApiRequest {
merchant_transaction_id: item.router_data.connector_request_reference_id.clone(),
@@ -810,12 +802,11 @@ impl TryFrom<&domain::payments::CardRedirectData> for ZenPaymentsRequest {
}
}
-impl TryFrom<&api_models::payments::GiftCardData> for ZenPaymentsRequest {
+impl TryFrom<&domain::GiftCardData> for ZenPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: &api_models::payments::GiftCardData) -> Result<Self, Self::Error> {
+ fn try_from(value: &domain::GiftCardData) -> Result<Self, Self::Error> {
match value {
- api_models::payments::GiftCardData::PaySafeCard {}
- | api_models::payments::GiftCardData::Givex(_) => {
+ domain::GiftCardData::PaySafeCard {} | domain::GiftCardData::Givex(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Zen"),
)
diff --git a/crates/router/src/types/domain/payments.rs b/crates/router/src/types/domain/payments.rs
index 61a036d1079..7fa18feef2e 100644
--- a/crates/router/src/types/domain/payments.rs
+++ b/crates/router/src/types/domain/payments.rs
@@ -1,4 +1,4 @@
-use common_utils::pii::Email;
+use common_utils::pii::{self, Email};
use masking::Secret;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
@@ -14,13 +14,13 @@ pub enum PaymentMethodData {
BankRedirect(BankRedirectData),
BankDebit(api_models::payments::BankDebitData),
BankTransfer(Box<api_models::payments::BankTransferData>),
- Crypto(api_models::payments::CryptoData),
+ Crypto(CryptoData),
MandatePayment,
Reward,
- Upi(api_models::payments::UpiData),
- Voucher(api_models::payments::VoucherData),
- GiftCard(Box<api_models::payments::GiftCardData>),
- CardToken(api_models::payments::CardToken),
+ Upi(UpiData),
+ Voucher(VoucherData),
+ GiftCard(Box<GiftCardData>),
+ CardToken(CardToken),
}
impl PaymentMethodData {
@@ -318,6 +318,117 @@ pub struct BankRedirectBilling {
pub email: Option<Email>,
}
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct CryptoData {
+ pub pay_currency: Option<String>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub struct UpiData {
+ #[schema(value_type = Option<String>, example = "successtest@iata")]
+ pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
+#[serde(rename_all = "snake_case")]
+pub enum VoucherData {
+ Boleto(Box<BoletoVoucherData>),
+ Efecty,
+ PagoEfectivo,
+ RedCompra,
+ RedPagos,
+ Alfamart(Box<AlfamartVoucherData>),
+ Indomaret(Box<IndomaretVoucherData>),
+ Oxxo,
+ SevenEleven(Box<JCSVoucherData>),
+ Lawson(Box<JCSVoucherData>),
+ MiniStop(Box<JCSVoucherData>),
+ FamilyMart(Box<JCSVoucherData>),
+ Seicomart(Box<JCSVoucherData>),
+ PayEasy(Box<JCSVoucherData>),
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct BoletoVoucherData {
+ /// The shopper's social security number
+ #[schema(value_type = Option<String>)]
+ pub social_security_number: Option<Secret<String>>,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct AlfamartVoucherData {
+ /// The billing first name for Alfamart
+ #[schema(value_type = String, example = "Jane")]
+ pub first_name: Secret<String>,
+ /// The billing second name for Alfamart
+ #[schema(value_type = String, example = "Doe")]
+ pub last_name: Option<Secret<String>>,
+ /// The Email ID for Alfamart
+ #[schema(value_type = String, example = "[email protected]")]
+ pub email: Email,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct IndomaretVoucherData {
+ /// The billing first name for Alfamart
+ #[schema(value_type = String, example = "Jane")]
+ pub first_name: Secret<String>,
+ /// The billing second name for Alfamart
+ #[schema(value_type = String, example = "Doe")]
+ pub last_name: Option<Secret<String>>,
+ /// The Email ID for Alfamart
+ #[schema(value_type = String, example = "[email protected]")]
+ pub email: Email,
+}
+
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct JCSVoucherData {
+ /// The billing first name for Japanese convenience stores
+ #[schema(value_type = String, example = "Jane")]
+ pub first_name: Secret<String>,
+ /// The billing second name Japanese convenience stores
+ #[schema(value_type = String, example = "Doe")]
+ pub last_name: Option<Secret<String>>,
+ /// The Email ID for Japanese convenience stores
+ #[schema(value_type = String, example = "[email protected]")]
+ pub email: Email,
+ /// The telephone number for Japanese convenience stores
+ #[schema(value_type = String, example = "9999999999")]
+ pub phone_number: String,
+}
+
+#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub enum GiftCardData {
+ Givex(GiftCardDetails),
+ PaySafeCard {},
+}
+
+#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)]
+#[serde(rename_all = "snake_case")]
+pub struct GiftCardDetails {
+ /// The gift card number
+ #[schema(value_type = String)]
+ pub number: Secret<String>,
+ /// The card verification code.
+ #[schema(value_type = String)]
+ pub cvc: Secret<String>,
+}
+
+#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)]
+#[serde(rename_all = "snake_case")]
+pub struct CardToken {
+ /// The card holder's name
+ #[schema(value_type = String, example = "John Test")]
+ pub card_holder_name: Option<Secret<String>>,
+
+ /// The CVC number for the card
+ #[schema(value_type = Option<String>)]
+ pub card_cvc: Option<Secret<String>>,
+}
+
impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {
fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self {
match api_model_payment_method_data {
@@ -343,19 +454,21 @@ impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {
Self::BankTransfer(bank_transfer_data)
}
api_models::payments::PaymentMethodData::Crypto(crypto_data) => {
- Self::Crypto(crypto_data)
+ Self::Crypto(From::from(crypto_data))
}
api_models::payments::PaymentMethodData::MandatePayment => Self::MandatePayment,
api_models::payments::PaymentMethodData::Reward => Self::Reward,
- api_models::payments::PaymentMethodData::Upi(upi_data) => Self::Upi(upi_data),
+ api_models::payments::PaymentMethodData::Upi(upi_data) => {
+ Self::Upi(From::from(upi_data))
+ }
api_models::payments::PaymentMethodData::Voucher(voucher_data) => {
- Self::Voucher(voucher_data)
+ Self::Voucher(From::from(voucher_data))
}
api_models::payments::PaymentMethodData::GiftCard(gift_card) => {
- Self::GiftCard(gift_card)
+ Self::GiftCard(Box::new(From::from(*gift_card)))
}
api_models::payments::PaymentMethodData::CardToken(card_token) => {
- Self::CardToken(card_token)
+ Self::CardToken(From::from(card_token))
}
}
}
@@ -649,3 +762,86 @@ impl From<api_models::payments::BankRedirectBilling> for BankRedirectBilling {
}
}
}
+
+impl From<api_models::payments::CryptoData> for CryptoData {
+ fn from(value: api_models::payments::CryptoData) -> Self {
+ let api_models::payments::CryptoData { pay_currency } = value;
+ Self { pay_currency }
+ }
+}
+
+impl From<api_models::payments::UpiData> for UpiData {
+ fn from(value: api_models::payments::UpiData) -> Self {
+ let api_models::payments::UpiData { vpa_id } = value;
+ Self { vpa_id }
+ }
+}
+
+impl From<api_models::payments::VoucherData> for VoucherData {
+ fn from(value: api_models::payments::VoucherData) -> Self {
+ match value {
+ api_models::payments::VoucherData::Boleto(boleto_data) => {
+ Self::Boleto(Box::new(BoletoVoucherData {
+ social_security_number: boleto_data.social_security_number,
+ }))
+ }
+ api_models::payments::VoucherData::Alfamart(alfamart_data) => {
+ Self::Alfamart(Box::new(AlfamartVoucherData {
+ first_name: alfamart_data.first_name,
+ last_name: alfamart_data.last_name,
+ email: alfamart_data.email,
+ }))
+ }
+ api_models::payments::VoucherData::Indomaret(indomaret_data) => {
+ Self::Indomaret(Box::new(IndomaretVoucherData {
+ first_name: indomaret_data.first_name,
+ last_name: indomaret_data.last_name,
+ email: indomaret_data.email,
+ }))
+ }
+ api_models::payments::VoucherData::SevenEleven(jcs_data)
+ | api_models::payments::VoucherData::Lawson(jcs_data)
+ | api_models::payments::VoucherData::MiniStop(jcs_data)
+ | api_models::payments::VoucherData::FamilyMart(jcs_data)
+ | api_models::payments::VoucherData::Seicomart(jcs_data)
+ | api_models::payments::VoucherData::PayEasy(jcs_data) => {
+ Self::SevenEleven(Box::new(JCSVoucherData {
+ first_name: jcs_data.first_name,
+ last_name: jcs_data.last_name,
+ email: jcs_data.email,
+ phone_number: jcs_data.phone_number,
+ }))
+ }
+ api_models::payments::VoucherData::Efecty => Self::Efecty,
+ api_models::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo,
+ api_models::payments::VoucherData::RedCompra => Self::RedCompra,
+ api_models::payments::VoucherData::RedPagos => Self::RedPagos,
+ api_models::payments::VoucherData::Oxxo => Self::Oxxo,
+ }
+ }
+}
+
+impl From<api_models::payments::GiftCardData> for GiftCardData {
+ fn from(value: api_models::payments::GiftCardData) -> Self {
+ match value {
+ api_models::payments::GiftCardData::Givex(details) => Self::Givex(GiftCardDetails {
+ number: details.number,
+ cvc: details.cvc,
+ }),
+ api_models::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCard {},
+ }
+ }
+}
+
+impl From<api_models::payments::CardToken> for CardToken {
+ fn from(value: api_models::payments::CardToken) -> Self {
+ let api_models::payments::CardToken {
+ card_holder_name,
+ card_cvc,
+ } = value;
+ Self {
+ card_holder_name,
+ card_cvc,
+ }
+ }
+}
diff --git a/crates/router/tests/connectors/bitpay.rs b/crates/router/tests/connectors/bitpay.rs
index 9a3bbeb8a29..df82775d6cf 100644
--- a/crates/router/tests/connectors/bitpay.rs
+++ b/crates/router/tests/connectors/bitpay.rs
@@ -1,6 +1,5 @@
-use api_models::payments::CryptoData;
use masking::Secret;
-use router::types::{self, api, storage::enums, PaymentAddress};
+use router::types::{self, api, domain, storage::enums, PaymentAddress};
use crate::{
connector_auth,
@@ -68,7 +67,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 1,
currency: enums::Currency::USD,
- payment_method_data: types::domain::PaymentMethodData::Crypto(CryptoData {
+ payment_method_data: types::domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: None,
}),
confirm: true,
diff --git a/crates/router/tests/connectors/coinbase.rs b/crates/router/tests/connectors/coinbase.rs
index d580b50fb57..0136284c826 100644
--- a/crates/router/tests/connectors/coinbase.rs
+++ b/crates/router/tests/connectors/coinbase.rs
@@ -1,6 +1,5 @@
-use api_models::payments::CryptoData;
use masking::Secret;
-use router::types::{self, api, storage::enums, PaymentAddress};
+use router::types::{self, api, domain, storage::enums, PaymentAddress};
use serde_json::json;
use crate::{
@@ -70,7 +69,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 1,
currency: enums::Currency::USD,
- payment_method_data: types::domain::PaymentMethodData::Crypto(CryptoData {
+ payment_method_data: types::domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: None,
}),
confirm: true,
diff --git a/crates/router/tests/connectors/cryptopay.rs b/crates/router/tests/connectors/cryptopay.rs
index 014f7a7e3d1..56c0e29f621 100644
--- a/crates/router/tests/connectors/cryptopay.rs
+++ b/crates/router/tests/connectors/cryptopay.rs
@@ -1,6 +1,5 @@
-use api_models::payments::CryptoData;
use masking::Secret;
-use router::types::{self, api, storage::enums, PaymentAddress};
+use router::types::{self, api, domain, storage::enums, PaymentAddress};
use crate::{
connector_auth,
@@ -69,7 +68,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 1,
currency: enums::Currency::USD,
- payment_method_data: types::domain::PaymentMethodData::Crypto(CryptoData {
+ payment_method_data: types::domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: Some("XRP".to_string()),
}),
confirm: true,
diff --git a/crates/router/tests/connectors/opennode.rs b/crates/router/tests/connectors/opennode.rs
index 9875fdfa23b..e4d347c26d1 100644
--- a/crates/router/tests/connectors/opennode.rs
+++ b/crates/router/tests/connectors/opennode.rs
@@ -1,6 +1,5 @@
-use api_models::payments::CryptoData;
use masking::Secret;
-use router::types::{self, api, storage::enums};
+use router::types::{self, api, domain, storage::enums};
use crate::{
connector_auth,
@@ -69,7 +68,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
amount: 1,
currency: enums::Currency::USD,
- payment_method_data: types::domain::PaymentMethodData::Crypto(CryptoData {
+ payment_method_data: types::domain::PaymentMethodData::Crypto(domain::CryptoData {
pay_currency: None,
}),
confirm: true,
|
refactor
|
add some payment method data to new domain type to be used in connector module (#4234)
|
3a5fb532de39e033feff7e8de126c5e5bf12eb36
|
2024-09-10 13:14:07
|
Sagnik Mitra
|
feat(payment_methods_list): add is_tax_connector_enabled boolean value in payment_methods_list call response (#5707)
| false
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 6b9ba4afd01..783d4751bc5 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -11073,7 +11073,8 @@
"payment_methods",
"mandate_payment",
"show_surcharge_breakup_screen",
- "request_external_three_ds_authentication"
+ "request_external_three_ds_authentication",
+ "is_tax_calculation_enabled"
],
"properties": {
"redirect_url": {
@@ -11135,6 +11136,10 @@
"type": "boolean",
"description": "flag that indicates whether to collect billing details from wallets or from the customer",
"nullable": true
+ },
+ "is_tax_calculation_enabled": {
+ "type": "boolean",
+ "description": "flag that indicates whether to calculate tax on the order amount"
}
}
},
@@ -11923,6 +11928,11 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "skip_external_tax_calculation": {
+ "type": "boolean",
+ "description": "Whether to calculate tax for this payment intent",
+ "nullable": true
}
}
},
@@ -12288,6 +12298,11 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "skip_external_tax_calculation": {
+ "type": "boolean",
+ "description": "Whether to calculate tax for this payment intent",
+ "nullable": true
}
}
},
@@ -13347,6 +13362,11 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "skip_external_tax_calculation": {
+ "type": "boolean",
+ "description": "Whether to calculate tax for this payment intent",
+ "nullable": true
}
},
"additionalProperties": false
@@ -14355,6 +14375,11 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "skip_external_tax_calculation": {
+ "type": "boolean",
+ "description": "Whether to calculate tax for this payment intent",
+ "nullable": true
}
}
},
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index 2a758cc06d2..43845f83f20 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -15071,7 +15071,8 @@
"payment_methods",
"mandate_payment",
"show_surcharge_breakup_screen",
- "request_external_three_ds_authentication"
+ "request_external_three_ds_authentication",
+ "is_tax_calculation_enabled"
],
"properties": {
"redirect_url": {
@@ -15133,6 +15134,10 @@
"type": "boolean",
"description": "flag that indicates whether to collect billing details from wallets or from the customer",
"nullable": true
+ },
+ "is_tax_calculation_enabled": {
+ "type": "boolean",
+ "description": "flag that indicates whether to calculate tax on the order amount"
}
}
},
@@ -15921,6 +15926,11 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "skip_external_tax_calculation": {
+ "type": "boolean",
+ "description": "Whether to calculate tax for this payment intent",
+ "nullable": true
}
}
},
@@ -16286,6 +16296,11 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "skip_external_tax_calculation": {
+ "type": "boolean",
+ "description": "Whether to calculate tax for this payment intent",
+ "nullable": true
}
}
},
@@ -17365,6 +17380,11 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "skip_external_tax_calculation": {
+ "type": "boolean",
+ "description": "Whether to calculate tax for this payment intent",
+ "nullable": true
}
},
"additionalProperties": false
@@ -18373,6 +18393,11 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "skip_external_tax_calculation": {
+ "type": "boolean",
+ "description": "Whether to calculate tax for this payment intent",
+ "nullable": true
}
}
},
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index 2204a7fc584..c6cf6380150 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -1482,6 +1482,9 @@ pub struct PaymentMethodListResponse {
/// flag that indicates whether to collect billing details from wallets or from the customer
pub collect_billing_details_from_wallets: Option<bool>,
+
+ /// flag that indicates whether to calculate tax on the order amount
+ pub is_tax_calculation_enabled: bool,
}
#[derive(Eq, PartialEq, Hash, Debug, serde::Deserialize, ToSchema)]
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index d512d487e5b..cd32c045f18 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -560,6 +560,9 @@ pub struct PaymentsRequest {
example = "Custom_Order_id_123"
)]
pub merchant_order_reference_id: Option<String>,
+
+ /// Whether to calculate tax for this payment intent
+ pub skip_external_tax_calculation: Option<bool>,
}
/// Checks if the inner values of two options are equal
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index c80e9e5f4da..b2f314a0fee 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -72,6 +72,7 @@ pub struct PaymentIntent {
pub shipping_cost: Option<MinorUnit>,
pub organization_id: common_utils::id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
+ pub skip_external_tax_calculation: Option<bool>,
}
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))]
@@ -136,6 +137,7 @@ pub struct PaymentIntent {
pub shipping_cost: Option<MinorUnit>,
pub organization_id: common_utils::id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
+ pub skip_external_tax_calculation: Option<bool>,
}
#[derive(Clone, Default, Debug, PartialEq, Serialize, Deserialize, diesel::AsExpression)]
@@ -219,6 +221,7 @@ pub struct PaymentIntentNew {
pub shipping_cost: Option<MinorUnit>,
pub organization_id: common_utils::id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
+ pub skip_external_tax_calculation: Option<bool>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 213687431d4..8e6c72eb5ba 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -919,6 +919,7 @@ diesel::table! {
#[max_length = 32]
organization_id -> Varchar,
tax_details -> Nullable<Jsonb>,
+ skip_external_tax_calculation -> Nullable<Bool>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index de4adf7984f..2deaa3d4ee4 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -899,6 +899,7 @@ diesel::table! {
#[max_length = 32]
organization_id -> Varchar,
tax_details -> Nullable<Jsonb>,
+ skip_external_tax_calculation -> Nullable<Bool>,
}
}
diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rs
index cfc0d07e0c8..c6b76680d48 100644
--- a/crates/hyperswitch_domain_models/src/business_profile.rs
+++ b/crates/hyperswitch_domain_models/src/business_profile.rs
@@ -659,6 +659,14 @@ impl From<BusinessProfileSetter> for BusinessProfile {
}
impl BusinessProfile {
+ pub fn get_is_tax_connector_enabled(&self) -> bool {
+ let is_tax_connector_enabled = self.is_tax_connector_enabled;
+ match &self.tax_connector_id {
+ Some(_id) => is_tax_connector_enabled,
+ _ => false,
+ }
+ }
+
#[cfg(feature = "v1")]
pub fn get_order_fulfillment_time(&self) -> Option<i64> {
self.intent_fulfillment_time
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 1365a7f082c..14d7e43450d 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -71,4 +71,5 @@ pub struct PaymentIntent {
pub is_payment_processor_token_flow: Option<bool>,
pub organization_id: id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
+ pub skip_external_tax_calculation: Option<bool>,
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index c39e5b8c092..427ca967b9d 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -551,6 +551,7 @@ impl behaviour::Conversion for PaymentIntent {
organization_id: self.organization_id,
shipping_cost: self.shipping_cost,
tax_details: self.tax_details,
+ skip_external_tax_calculation: self.skip_external_tax_calculation,
})
}
async fn convert_back(
@@ -636,6 +637,7 @@ impl behaviour::Conversion for PaymentIntent {
organization_id: storage_model.organization_id,
shipping_cost: storage_model.shipping_cost,
tax_details: storage_model.tax_details,
+ skip_external_tax_calculation: storage_model.skip_external_tax_calculation,
})
}
.await
@@ -697,6 +699,7 @@ impl behaviour::Conversion for PaymentIntent {
organization_id: self.organization_id,
shipping_cost: self.shipping_cost,
tax_details: self.tax_details,
+ skip_external_tax_calculation: self.skip_external_tax_calculation,
})
}
}
@@ -760,6 +763,7 @@ impl behaviour::Conversion for PaymentIntent {
organization_id: self.organization_id,
shipping_cost: self.shipping_cost,
tax_details: self.tax_details,
+ skip_external_tax_calculation: self.skip_external_tax_calculation,
})
}
@@ -846,6 +850,7 @@ impl behaviour::Conversion for PaymentIntent {
.await?,
is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow,
organization_id: storage_model.organization_id,
+ skip_external_tax_calculation: storage_model.skip_external_tax_calculation,
})
}
.await
@@ -907,6 +912,7 @@ impl behaviour::Conversion for PaymentIntent {
organization_id: self.organization_id,
shipping_cost: self.shipping_cost,
tax_details: self.tax_details,
+ skip_external_tax_calculation: self.skip_external_tax_calculation,
})
}
}
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index 3f62b16c420..e5b0e8b9120 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -152,6 +152,7 @@ pub struct PaymentIntentNew {
pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub is_payment_processor_token_flow: Option<bool>,
pub organization_id: id_type::OrganizationId,
+ pub skip_external_tax_calculation: Option<bool>,
}
#[derive(Debug, Clone, Serialize)]
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index cee4e9d1dd2..c553840347d 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -3626,6 +3626,10 @@ pub async fn list_payment_methods(
});
}
let currency = payment_intent.as_ref().and_then(|pi| pi.currency);
+ let skip_external_tax_calculation = payment_intent
+ .as_ref()
+ .and_then(|intent| intent.skip_external_tax_calculation)
+ .unwrap_or(false);
let request_external_three_ds_authentication = payment_intent
.as_ref()
.and_then(|intent| intent.request_external_three_ds_authentication)
@@ -3670,6 +3674,10 @@ pub async fn list_payment_methods(
business_profile.collect_billing_details_from_wallet_connector
}));
+ let is_tax_connector_enabled = business_profile.as_ref().map_or(false, |business_profile| {
+ business_profile.get_is_tax_connector_enabled()
+ });
+
Ok(services::ApplicationResponse::Json(
api::PaymentMethodListResponse {
redirect_url: business_profile
@@ -3710,6 +3718,7 @@ pub async fn list_payment_methods(
request_external_three_ds_authentication,
collect_shipping_details_from_wallets,
collect_billing_details_from_wallets,
+ is_tax_calculation_enabled: is_tax_connector_enabled && !skip_external_tax_calculation,
},
))
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index d97e609aee4..1ad86c7df28 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3108,6 +3108,7 @@ mod tests {
organization_id: id_type::OrganizationId::default(),
shipping_cost: None,
tax_details: None,
+ skip_external_tax_calculation: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_ok());
@@ -3176,6 +3177,7 @@ mod tests {
organization_id: id_type::OrganizationId::default(),
shipping_cost: None,
tax_details: None,
+ skip_external_tax_calculation: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent,).is_err())
@@ -3242,6 +3244,7 @@ mod tests {
organization_id: id_type::OrganizationId::default(),
shipping_cost: None,
tax_details: None,
+ skip_external_tax_calculation: None,
};
let req_cs = Some("1".to_string());
assert!(authenticate_client_secret(req_cs.as_ref(), &payment_intent).is_err())
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 257a3156bbc..9a662dc589b 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -1283,6 +1283,8 @@ impl PaymentCreate {
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt customer details")?;
+ let skip_external_tax_calculation = request.skip_external_tax_calculation;
+
Ok(storage::PaymentIntent {
payment_id: payment_id.to_owned(),
merchant_id: merchant_account.get_id().to_owned(),
@@ -1338,6 +1340,7 @@ impl PaymentCreate {
organization_id: merchant_account.organization_id.clone(),
shipping_cost: request.shipping_cost,
tax_details: None,
+ skip_external_tax_calculation,
})
}
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index 07bfe74f1d5..32728fd8fcc 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -250,6 +250,7 @@ pub async fn generate_sample_data(
organization_id: org_id.clone(),
shipping_cost: None,
tax_details: None,
+ skip_external_tax_calculation: None,
};
let payment_attempt = PaymentAttemptBatchNew {
attempt_id: attempt_id.clone(),
diff --git a/migrations/2024-08-28-044317_add_skip_external_tax_calcualtion_in_payment_intent_table/down.sql b/migrations/2024-08-28-044317_add_skip_external_tax_calcualtion_in_payment_intent_table/down.sql
new file mode 100644
index 00000000000..4ca933a4e36
--- /dev/null
+++ b/migrations/2024-08-28-044317_add_skip_external_tax_calcualtion_in_payment_intent_table/down.sql
@@ -0,0 +1,2 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_intent DROP COLUMN if EXISTS skip_external_tax_calculation;
\ No newline at end of file
diff --git a/migrations/2024-08-28-044317_add_skip_external_tax_calcualtion_in_payment_intent_table/up.sql b/migrations/2024-08-28-044317_add_skip_external_tax_calcualtion_in_payment_intent_table/up.sql
new file mode 100644
index 00000000000..cf185dcdb7a
--- /dev/null
+++ b/migrations/2024-08-28-044317_add_skip_external_tax_calcualtion_in_payment_intent_table/up.sql
@@ -0,0 +1,2 @@
+-- Your SQL goes here
+ALTER TABLE payment_intent ADD COLUMN IF NOT EXISTS skip_external_tax_calculation BOOLEAN;
\ No newline at end of file
|
feat
|
add is_tax_connector_enabled boolean value in payment_methods_list call response (#5707)
|
c6cb527f07e23796c342f3562fbf3b61f1ef6801
|
2023-11-30 15:41:59
|
Sarthak Soni
|
fix(routing): Fix kgraph to exclude PM auth during construction (#3019)
| false
|
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index 841b48b9444..96cd6561519 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -523,8 +523,10 @@ pub async fn refresh_kgraph_cache(
.await
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;
- merchant_connector_accounts
- .retain(|mca| mca.connector_type != storage_enums::ConnectorType::PaymentVas);
+ merchant_connector_accounts.retain(|mca| {
+ mca.connector_type != storage_enums::ConnectorType::PaymentVas
+ && mca.connector_type != storage_enums::ConnectorType::PaymentMethodAuth
+ });
#[cfg(feature = "business_profile_routing")]
let merchant_connector_accounts = payments_oss::helpers::filter_mca_based_on_business_profile(
|
fix
|
Fix kgraph to exclude PM auth during construction (#3019)
|
e911ea4615294d136210bcf9a8bd4b3ab39ca85f
|
2024-10-10 05:54:33
|
github-actions
|
chore(version): 2024.10.10.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 78b97ac4e75..72dff2de512 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,7 @@ All notable changes to HyperSwitch will be documented here.
- - -
+
## 2024.10.09.0
### Features
|
chore
|
2024.10.10.0
|
224b83c51d53fb1ca9ae11ff2f60b7b6cc807fc8
|
2023-10-09 14:33:34
|
Kartikeya Hegde
|
fix: add release feature to drianer (#2507)
| false
|
diff --git a/crates/drainer/Cargo.toml b/crates/drainer/Cargo.toml
index 45186b84ca9..2b0ade02930 100644
--- a/crates/drainer/Cargo.toml
+++ b/crates/drainer/Cargo.toml
@@ -8,6 +8,7 @@ readme = "README.md"
license.workspace = true
[features]
+release = ["kms","vergen"]
kms = ["external_services/kms"]
vergen = ["router_env/vergen"]
|
fix
|
add release feature to drianer (#2507)
|
9341191e39627b661b9d105d65a869e8348c81ed
|
2023-05-23 16:30:58
|
Nishant Joshi
|
fix(list): add mandate type in payment_method_list (#1238)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index 44a48169ffd..da0033c8336 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -876,7 +876,6 @@ version = "0.55.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "22d2a2bcc16e5c4d949ffd2b851da852b9bbed4bb364ed4ae371b42137ca06d9"
dependencies = [
- "aws-smithy-eventstream",
"aws-smithy-types",
"bytes",
"crc32fast",
@@ -3001,7 +3000,7 @@ dependencies = [
[[package]]
name = "opentelemetry"
version = "0.18.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"opentelemetry_api",
"opentelemetry_sdk",
@@ -3010,7 +3009,7 @@ dependencies = [
[[package]]
name = "opentelemetry-otlp"
version = "0.11.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"async-trait",
"futures",
@@ -3027,7 +3026,7 @@ dependencies = [
[[package]]
name = "opentelemetry-proto"
version = "0.1.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"futures",
"futures-util",
@@ -3039,7 +3038,7 @@ dependencies = [
[[package]]
name = "opentelemetry_api"
version = "0.18.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"fnv",
"futures-channel",
@@ -3054,7 +3053,7 @@ dependencies = [
[[package]]
name = "opentelemetry_sdk"
version = "0.18.0"
-source = "git+https://github.com/open-telemetry/opentelemetry-rust/?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
+source = "git+https://github.com/open-telemetry/opentelemetry-rust?rev=44b90202fd744598db8b0ace5b8f0bad7ec45658#44b90202fd744598db8b0ace5b8f0bad7ec45658"
dependencies = [
"async-trait",
"crossbeam-channel",
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index e2b9decc795..30232c705fe 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -439,8 +439,8 @@ pub struct PaymentMethodListResponse {
))]
pub payment_methods: Vec<ResponsePaymentMethodsEnabled>,
/// Value indicating if the current payment is a mandate payment
- #[schema(example = "new_mandate_txn")]
- pub mandate_payment: Option<payments::MandateTxnType>,
+ #[schema(value_type = MandateType)]
+ pub mandate_payment: Option<payments::MandateType>,
}
#[derive(Eq, PartialEq, Hash, Debug, serde::Deserialize, ToSchema)]
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index a2689928139..97928694df5 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1139,8 +1139,7 @@ pub async fn list_payment_methods(
payment_methods: payment_method_responses,
mandate_payment: payment_attempt
.and_then(|inner| inner.mandate_details)
- // The data stored in the payment attempt only corresponds to a setup mandate.
- .map(|_mandate_data| api_models::payments::MandateTxnType::NewMandateTxn),
+ .map(ForeignInto::foreign_into),
},
)))
}
|
fix
|
add mandate type in payment_method_list (#1238)
|
394ed908207b8e83839e896e2d1190bd3143f074
|
2023-11-23 18:54:23
|
github-actions
|
chore(version): v1.88.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f4b86696691..e427f33e8fb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,36 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.88.0 (2023-11-23)
+
+### Features
+
+- **connector:** [BANKOFAMERICA] Implement Google Pay ([#2940](https://github.com/juspay/hyperswitch/pull/2940)) ([`f91d4ae`](https://github.com/juspay/hyperswitch/commit/f91d4ae11b02def92c1dde743a0c01b5aac5703f))
+- **router:** Allow billing and shipping address update in payments confirm flow ([#2963](https://github.com/juspay/hyperswitch/pull/2963)) ([`59ef162`](https://github.com/juspay/hyperswitch/commit/59ef162219db3e4650dde65710850bc9f3280530))
+
+### Bug Fixes
+
+- **connector:** [Prophetpay] Use refund_id as reference_id for Refund ([#2966](https://github.com/juspay/hyperswitch/pull/2966)) ([`dd3e22a`](https://github.com/juspay/hyperswitch/commit/dd3e22a938714f373477e08d1d25e4b84ac796c6))
+- **core:** Fix Default Values Enum FieldType ([#2934](https://github.com/juspay/hyperswitch/pull/2934)) ([`35a44ed`](https://github.com/juspay/hyperswitch/commit/35a44ed2533b748e3fabb8a2f8db4fa7e5d3cf7e))
+- **drainer:** Increase jobs picked only when stream is not empty ([#2958](https://github.com/juspay/hyperswitch/pull/2958)) ([`42eedf3`](https://github.com/juspay/hyperswitch/commit/42eedf3a8c2e62fc22bcead370d129ebaf11a00b))
+- Amount_captured goes to 0 for 3ds payments ([#2954](https://github.com/juspay/hyperswitch/pull/2954)) ([`75eea7e`](https://github.com/juspay/hyperswitch/commit/75eea7e81787f2e0697b930b82a8188193f8d51f))
+- Make drainer sleep on every loop interval instead of cycle end ([#2951](https://github.com/juspay/hyperswitch/pull/2951)) ([`e8df690`](https://github.com/juspay/hyperswitch/commit/e8df69092f4c6acee58109aaff2a9454fceb571a))
+
+### Refactors
+
+- **connector:**
+ - [Payeezy] update error message ([#2919](https://github.com/juspay/hyperswitch/pull/2919)) ([`cb65370`](https://github.com/juspay/hyperswitch/commit/cb653706066b889eaa9423a6227ce1df954b4759))
+ - [Worldline] change error message from NotSupported to NotImplemented ([#2893](https://github.com/juspay/hyperswitch/pull/2893)) ([`e721b06`](https://github.com/juspay/hyperswitch/commit/e721b06c7077e00458450a4fb98f4497e8227dc6))
+
+### Testing
+
+- **postman:** Update postman collection files ([`9a3fa00`](https://github.com/juspay/hyperswitch/commit/9a3fa00426d74f6d18b3c712b292d98d80d517ba))
+
+**Full Changelog:** [`v1.87.0...v1.88.0`](https://github.com/juspay/hyperswitch/compare/v1.87.0...v1.88.0)
+
+- - -
+
+
## 1.87.0 (2023-11-22)
### Features
|
chore
|
v1.88.0
|
46e84a6b0cb74bccc3a63d9568ca2668866a960f
|
2024-01-03 14:57:18
|
likhinbopanna
|
ci(postman): Added necessary card networks (#3230)
| false
|
diff --git a/postman/collection-dir/checkout/Flow Testcases/QuickStart/Payment Connector - Create/request.json b/postman/collection-dir/checkout/Flow Testcases/QuickStart/Payment Connector - Create/request.json
index 9500716c12c..7ca3d82e793 100644
--- a/postman/collection-dir/checkout/Flow Testcases/QuickStart/Payment Connector - Create/request.json
+++ b/postman/collection-dir/checkout/Flow Testcases/QuickStart/Payment Connector - Create/request.json
@@ -56,10 +56,12 @@
"payment_method_types": [
{
"payment_method_type": "credit",
- "card_networks": [
- "Visa",
- "Mastercard"
- ],
+ "card_networks": ["AmericanExpress",
+ "Discover",
+ "Interac",
+ "JCB",
+ "Mastercard",
+ "Visa", "DinersClub","UnionPay","RuPay"],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
@@ -67,10 +69,12 @@
},
{
"payment_method_type": "debit",
- "card_networks": [
- "Visa",
- "Mastercard"
- ],
+ "card_networks": ["AmericanExpress",
+ "Discover",
+ "Interac",
+ "JCB",
+ "Mastercard",
+ "Visa", "DinersClub","UnionPay","RuPay"],
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
|
ci
|
Added necessary card networks (#3230)
|
ff5bba5da30b91e054c2dab6293832da3628cb0a
|
2024-05-24 05:45:12
|
github-actions
|
chore(version): 2024.05.24.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6bf415dd8db..edbae73ad02 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,35 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.05.24.0
+
+### Features
+
+- **analytics:** Added client columns in payments analytics ([#4658](https://github.com/juspay/hyperswitch/pull/4658)) ([`0b415dc`](https://github.com/juspay/hyperswitch/commit/0b415dcca67f2994727627990a9cc9db19885b34))
+- **router:** Send message_version and directory_server_id in next_action block of three_ds_data for external 3ds flow ([#4715](https://github.com/juspay/hyperswitch/pull/4715)) ([`13f6efc`](https://github.com/juspay/hyperswitch/commit/13f6efc7e8c01b4a377f627b9cfe2319b518204d))
+- **users:**
+ - Create terminate 2fa API ([#4731](https://github.com/juspay/hyperswitch/pull/4731)) ([`42e5ef1`](https://github.com/juspay/hyperswitch/commit/42e5ef155128f4df717e8fb101da6e6929659a0a))
+ - Add support to verify 2FA using recovery code ([#4737](https://github.com/juspay/hyperswitch/pull/4737)) ([`f04c6ac`](https://github.com/juspay/hyperswitch/commit/f04c6ac030485cb28ab09e85a0f2f3c13beb6df3))
+- Authentication analytics ([#4684](https://github.com/juspay/hyperswitch/pull/4684)) ([`5e5eb5f`](https://github.com/juspay/hyperswitch/commit/5e5eb5fbae7de2e296899e0372c82906603526d6))
+
+### Bug Fixes
+
+- **kafka:** Fix kafka timestamps sent from application ([#4709](https://github.com/juspay/hyperswitch/pull/4709)) ([`c778af2`](https://github.com/juspay/hyperswitch/commit/c778af26ddb46ff98072e8934a9509ff6e00ddc5))
+- **payment_methods:** Mask the email address being logged in the `payment_method_list` response logs ([#4749](https://github.com/juspay/hyperswitch/pull/4749)) ([`23c7395`](https://github.com/juspay/hyperswitch/commit/23c73951bbdd5e049b75ca6d8e3bcccfb629e6eb))
+
+### Refactors
+
+- **bank-redirect:** Dynamic field changes for bankredirect payment method ([#4650](https://github.com/juspay/hyperswitch/pull/4650)) ([`da2dc10`](https://github.com/juspay/hyperswitch/commit/da2dc10f3d7233a0a9eae7d23cb07f7e8fafad78))
+- **payment_methods:** Use recurring enabled flag to decide which payment method supports MIT ([#4732](https://github.com/juspay/hyperswitch/pull/4732)) ([`ba624d0`](https://github.com/juspay/hyperswitch/commit/ba624d049840f65fc21a5e578f8d4ba8543e1420))
+
+### Miscellaneous Tasks
+
+- Move RouterData Request types to hyperswitch_domain_models crate ([#4723](https://github.com/juspay/hyperswitch/pull/4723)) ([`ae77373`](https://github.com/juspay/hyperswitch/commit/ae77373b4cac63979673fdac37c55986d954358e))
+
+**Full Changelog:** [`2024.05.23.0...2024.05.24.0`](https://github.com/juspay/hyperswitch/compare/2024.05.23.0...2024.05.24.0)
+
+- - -
+
## 2024.05.23.0
### Features
|
chore
|
2024.05.24.0
|
cc5bc095973f594e13bce88b0a1e5878721113be
|
2023-08-30 16:07:15
|
github-actions
|
chore(version): v1.31.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a9423a46776..53d11a5725d 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,22 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.31.0 (2023-08-30)
+
+### Features
+
+- **core:** Conditionally return captures list during payment sync. ([#2033](https://github.com/juspay/hyperswitch/pull/2033)) ([`c2aa014`](https://github.com/juspay/hyperswitch/commit/c2aa0142ed5af0b5fcf21b35cb129addd92c6125))
+
+### Bug Fixes
+
+- **configs:** Fix supported connectors in `multiple_api_version_supported_connectors` table ([#2051](https://github.com/juspay/hyperswitch/pull/2051)) ([`416ad8f`](https://github.com/juspay/hyperswitch/commit/416ad8fd97e423bfdb95409271628085aa97af76))
+- **connector:** [Cryptopay] fix amount to its currency base unit ([#2049](https://github.com/juspay/hyperswitch/pull/2049)) ([`d3f1858`](https://github.com/juspay/hyperswitch/commit/d3f18584f8e8a6090f24c4a469c6a18440d6711e))
+
+**Full Changelog:** [`v1.30.0...v1.31.0`](https://github.com/juspay/hyperswitch/compare/v1.30.0...v1.31.0)
+
+- - -
+
+
## 1.30.0 (2023-08-29)
### Features
|
chore
|
v1.31.0
|
573a4d384ee6a9d72648ab537804799a3993e1e8
|
2023-04-19 13:31:28
|
Gnanasundari24
|
doc: Changelog for release v0.5.7 (#907)
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 074496ee83e..4d2cafc62c8 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,35 @@
+# 0.5.7 (2023-04-18)
+
+## New Features
+
+* **connector:**
+ * [Shift4] add support for card 3DS payment (#828) (29999fe5)
+ * [Nuvei] add support for card mandates (#818) (298a0a49)
+* **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)
+* Update events table after notifying merchant (#871) (013026)
+* **stripe:** remove cancel reason validation for stripe (#876) (fa44c1f6)
+
+## Enhancement
+
+* **payments:** make TokenizationAction clonable (#895)
+
+## Integration
+
+* Frm integration with hyperswitch (#857)
+
+## Refactors
+
+* use lowercase names for run environment and config files (#801) (ffaa8da0)
+* derive `Serialize` and `Deserialize` to `Country` enum (#882) (456c16fb)
+* **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
|
doc
|
Changelog for release v0.5.7 (#907)
|
027080683d00a616e6dec40f57a4586951d76b09
|
2024-03-26 10:11:36
|
github-actions
|
chore(version): 2024.03.26.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e967966117d..c4b683bada5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,21 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.03.26.0
+
+### Features
+
+- **events:** Allow listing webhook events and webhook delivery attempts by business profile ([#4159](https://github.com/juspay/hyperswitch/pull/4159)) ([`4c8cdf1`](https://github.com/juspay/hyperswitch/commit/4c8cdf1475ac74fb2df5bea419dfa7657f26f298))
+- **payouts:** Add user roles for payouts ([#4167](https://github.com/juspay/hyperswitch/pull/4167)) ([`13fe584`](https://github.com/juspay/hyperswitch/commit/13fe58450bad094fb2b4745ecf76bc2df8b96798))
+
+### Miscellaneous Tasks
+
+- Address Rust 1.77 clippy lints ([#4172](https://github.com/juspay/hyperswitch/pull/4172)) ([`f213c51`](https://github.com/juspay/hyperswitch/commit/f213c51b3e5c4f0b3546b35bac4dde9698818e01))
+
+**Full Changelog:** [`2024.03.22.0...2024.03.26.0`](https://github.com/juspay/hyperswitch/compare/2024.03.22.0...2024.03.26.0)
+
+- - -
+
## 2024.03.22.0
### Features
|
chore
|
2024.03.26.0
|
217f1f413dc02ce8f6812f86882830674c6e76d5
|
2024-07-31 05:45:38
|
github-actions
|
chore(version): 2024.07.31.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cef3256f307..8d5f2c5a7e6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,31 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.07.31.0
+
+### Features
+
+- **connector:** [BAMBORA, BITPAY, STAX] Move connector to hyperswitch_connectors ([#5450](https://github.com/juspay/hyperswitch/pull/5450)) ([`827fa07`](https://github.com/juspay/hyperswitch/commit/827fa07418b0514cbc5a43af2e4c7a88d1b7b4e7))
+- **payment_link:** Add provision for secured payment links ([#5357](https://github.com/juspay/hyperswitch/pull/5357)) ([`043abb5`](https://github.com/juspay/hyperswitch/commit/043abb59b9291e18824d16363f60657f22bd33e1))
+- Rename columns in organization for v2 ([#5424](https://github.com/juspay/hyperswitch/pull/5424)) ([`a791391`](https://github.com/juspay/hyperswitch/commit/a791391e2ac125ef7bb6a92de5f1419e673bdfe0))
+
+### Bug Fixes
+
+- **connector:** [Pix] convert data type of pix fields ([#5476](https://github.com/juspay/hyperswitch/pull/5476)) ([`be9347b`](https://github.com/juspay/hyperswitch/commit/be9347b8d56c0a6cf0d04cf51c75dd6426d3a21a))
+
+### Refactors
+
+- **configs:** Include env for cybersource in integration_test ([#5474](https://github.com/juspay/hyperswitch/pull/5474)) ([`b3b71b1`](https://github.com/juspay/hyperswitch/commit/b3b71b10c3627868420648e70913a0620dcb3b6e))
+- **id_type:** Use macros for defining ID types and implementing common traits ([#5471](https://github.com/juspay/hyperswitch/pull/5471)) ([`1d4fb1d`](https://github.com/juspay/hyperswitch/commit/1d4fb1d2474190ea0a70810e416c61883fab34b8))
+
+### Documentation
+
+- Update postgreSQL database url ([#5482](https://github.com/juspay/hyperswitch/pull/5482)) ([`ef7fa0d`](https://github.com/juspay/hyperswitch/commit/ef7fa0d16ebe12bd86572c7ab80e7caa70d75578))
+
+**Full Changelog:** [`2024.07.30.0...2024.07.31.0`](https://github.com/juspay/hyperswitch/compare/2024.07.30.0...2024.07.31.0)
+
+- - -
+
## 2024.07.30.0
### Features
|
chore
|
2024.07.31.0
|
749c83a8e662b44106e979e7619a4230dec3d8a4
|
2023-01-19 15:05:37
|
Sampras Lopes
|
feat(router): reuse reqwest clients for requests made to connectors (#413)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index 4657d265792..a7bae5e5e71 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -82,7 +82,7 @@ dependencies = [
"http",
"httparse",
"httpdate",
- "itoa 1.0.4",
+ "itoa 1.0.5",
"language-tags",
"local-channel",
"mime",
@@ -212,7 +212,7 @@ dependencies = [
"futures-core",
"futures-util",
"http",
- "itoa 1.0.4",
+ "itoa 1.0.5",
"language-tags",
"log",
"mime",
@@ -294,9 +294,9 @@ dependencies = [
[[package]]
name = "anyhow"
-version = "1.0.66"
+version = "1.0.68"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "216261ddc8289130e551ddcd5ce8a064710c0d064a4d2895c67151c92b5443f6"
+checksum = "2cb2f989d18dd141ab8ae82f64d1a8cdd37e0840f73a406896cf5e99502fab61"
[[package]]
name = "api_models"
@@ -317,9 +317,9 @@ dependencies = [
[[package]]
name = "arc-swap"
-version = "1.5.1"
+version = "1.6.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "983cd8b9d4b02a6dc6ffa557262eb5858a27a0038ffffe21a0f133eaa819a164"
+checksum = "bddcadddf5e9015d310179a59bb28c4d4b9920ad0f11e8e14dbadf654890c9a6"
[[package]]
name = "arcstr"
@@ -444,7 +444,7 @@ dependencies = [
"futures-util",
"h2",
"http",
- "itoa 1.0.4",
+ "itoa 1.0.5",
"log",
"mime",
"percent-encoding",
@@ -716,7 +716,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "987b1e37febb9bd409ca0846e82d35299e572ad8279bc404778caeb5fc05ad56"
dependencies = [
"base64-simd",
- "itoa 1.0.4",
+ "itoa 1.0.5",
"num-integer",
"ryu",
"time",
@@ -749,9 +749,9 @@ dependencies = [
[[package]]
name = "axum"
-version = "0.6.1"
+version = "0.6.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "08b108ad2665fa3f6e6a517c3d80ec3e77d224c47d605167aefaa5d7ef97fa48"
+checksum = "1304eab461cf02bd70b083ed8273388f9724c549b316ba3d1e213ce0e9e7fb7e"
dependencies = [
"async-trait",
"axum-core",
@@ -761,7 +761,7 @@ dependencies = [
"http",
"http-body",
"hyper",
- "itoa 1.0.4",
+ "itoa 1.0.5",
"matchit",
"memchr",
"mime",
@@ -778,9 +778,9 @@ dependencies = [
[[package]]
name = "axum-core"
-version = "0.3.0"
+version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "79b8558f5a0581152dc94dcd289132a1d377494bdeafcd41869b3258e3e2ad92"
+checksum = "f487e40dc9daee24d8a1779df88522f159a54a980f99cfbe43db0be0bd3444a8"
dependencies = [
"async-trait",
"bytes",
@@ -879,9 +879,9 @@ dependencies = [
[[package]]
name = "brotli-decompressor"
-version = "2.3.2"
+version = "2.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "59ad2d4653bf5ca36ae797b1f4bb4dbddb60ce49ca4aed8a2ce4829f60425b80"
+checksum = "4b6561fd3f895a11e8f72af2cb7d22e08366bebc2b6b57f7744c4bda27034744"
dependencies = [
"alloc-no-stdlib",
"alloc-stdlib",
@@ -889,9 +889,9 @@ dependencies = [
[[package]]
name = "bumpalo"
-version = "3.11.1"
+version = "3.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "572f695136211188308f16ad2ca5c851a712c464060ae6974944458eb83880ba"
+checksum = "0d261e256854913907f67ed06efbc3338dfe6179796deefc1ff763fc1aee5535"
[[package]]
name = "byteorder"
@@ -926,9 +926,9 @@ dependencies = [
[[package]]
name = "cc"
-version = "1.0.77"
+version = "1.0.78"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e9f73505338f7d905b19d18738976aae232eb46b8efc15554ffc56deb5d9ebe4"
+checksum = "a20104e2335ce8a659d6dd92a51a767a0c062599c73b343fd152cb401e828c3d"
dependencies = [
"jobserver",
]
@@ -1033,9 +1033,9 @@ checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e"
[[package]]
name = "cookie"
-version = "0.16.1"
+version = "0.16.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "344adc371239ef32293cb1c4fe519592fcf21206c79c02854320afcdf3ab4917"
+checksum = "e859cd57d0710d9e06c381b550c06e76992472a8c6d527aecd2fc673dcc231fb"
dependencies = [
"percent-encoding",
"time",
@@ -1127,7 +1127,7 @@ dependencies = [
"hashbrown",
"lock_api",
"once_cell",
- "parking_lot_core 0.9.5",
+ "parking_lot_core 0.9.6",
]
[[package]]
@@ -1182,7 +1182,7 @@ dependencies = [
"bitflags",
"byteorder",
"diesel_derives",
- "itoa 1.0.4",
+ "itoa 1.0.5",
"pq-sys",
"r2d2",
"serde_json",
@@ -1734,7 +1734,7 @@ checksum = "75f43d41e26995c17e71ee126451dd3941010b0514a81a9d11f3b341debc2399"
dependencies = [
"bytes",
"fnv",
- "itoa 1.0.4",
+ "itoa 1.0.5",
]
[[package]]
@@ -1811,7 +1811,7 @@ dependencies = [
"http-body",
"httparse",
"httpdate",
- "itoa 1.0.4",
+ "itoa 1.0.5",
"pin-project-lite",
"socket2",
"tokio",
@@ -1899,9 +1899,9 @@ dependencies = [
[[package]]
name = "ipnet"
-version = "2.5.1"
+version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f88c5561171189e69df9d98bcf18fd5f9558300f7ea7b801eb8a0fd748bd8745"
+checksum = "30e22bd8629359895450b59ea7a776c850561b96a3b1d31321c1949d9e6c9146"
[[package]]
name = "is_ci"
@@ -1926,9 +1926,9 @@ checksum = "b71991ff56294aa922b450139ee08b3bfc70982c6b2c7562771375cf73542dd4"
[[package]]
name = "itoa"
-version = "1.0.4"
+version = "1.0.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4217ad341ebadf8d8e724e264f13e593e0648f5b3e94b3896a5df283be015ecc"
+checksum = "fad582f4b9e86b6caa621cabeb0963332d92eea04729ab12892c2533951e6440"
[[package]]
name = "jobserver"
@@ -2023,9 +2023,9 @@ dependencies = [
[[package]]
name = "libmimalloc-sys"
-version = "0.1.28"
+version = "0.1.30"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "04d1c67deb83e6b75fa4fe3309e09cfeade12e7721d95322af500d3814ea60c9"
+checksum = "dd8c7cbf8b89019683667e347572e6d55a7df7ea36b0c4ce69961b0cde67b174"
dependencies = [
"cc",
"libc",
@@ -2151,9 +2151,9 @@ checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d"
[[package]]
name = "mimalloc"
-version = "0.1.32"
+version = "0.1.34"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9b2374e2999959a7b583e1811a1ddbf1d3a4b9496eceb9746f1192a59d871eca"
+checksum = "9dcb174b18635f7561a0c6c9fc2ce57218ac7523cf72c50af80e2d79ab8f3ba1"
dependencies = [
"libmimalloc-sys",
]
@@ -2188,7 +2188,7 @@ dependencies = [
"libc",
"log",
"wasi 0.11.0+wasi-snapshot-preview1",
- "windows-sys 0.42.0",
+ "windows-sys",
]
[[package]]
@@ -2220,9 +2220,9 @@ dependencies = [
[[package]]
name = "nom"
-version = "7.1.1"
+version = "7.1.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a8903e5a29a317527874d0402f867152a3d21c908bb0b933e416c65e301d4c36"
+checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a"
dependencies = [
"memchr",
"minimal-lexical",
@@ -2301,9 +2301,9 @@ checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5"
[[package]]
name = "openssl"
-version = "0.10.43"
+version = "0.10.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "020433887e44c27ff16365eaa2d380547a94544ad509aff6eb5b6e3e0b27b376"
+checksum = "b102428fd03bc5edf97f62620f7298614c45cedf287c271e7ed450bbaf83f2e1"
dependencies = [
"bitflags",
"cfg-if",
@@ -2333,9 +2333,9 @@ checksum = "ff011a302c396a5197692431fc1948019154afc178baf7d8e37367442a4601cf"
[[package]]
name = "openssl-sys"
-version = "0.9.78"
+version = "0.9.80"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "07d5c8cb6e57b3a3612064d7b18b117912b4ce70955c2504d4b741c9e244b132"
+checksum = "23bbbf7854cd45b83958ebe919f0e8e516793727652e27fda10a8384cfc790b7"
dependencies = [
"autocfg",
"cc",
@@ -2469,7 +2469,7 @@ checksum = "7d17b78036a60663b797adeaee46f5c9dfebb86948d1255007a1d6be0271ff99"
dependencies = [
"instant",
"lock_api",
- "parking_lot_core 0.8.5",
+ "parking_lot_core 0.8.6",
]
[[package]]
@@ -2479,14 +2479,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f"
dependencies = [
"lock_api",
- "parking_lot_core 0.9.5",
+ "parking_lot_core 0.9.6",
]
[[package]]
name = "parking_lot_core"
-version = "0.8.5"
+version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d76e8e1493bcac0d2766c42737f34458f1c8c50c0d23bcb24ea953affb273216"
+checksum = "60a2cfe6f0ad2bfc16aefa463b497d5c7a5ecd44a23efa72aa342d90177356dc"
dependencies = [
"cfg-if",
"instant",
@@ -2498,22 +2498,22 @@ dependencies = [
[[package]]
name = "parking_lot_core"
-version = "0.9.5"
+version = "0.9.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7ff9f3fef3968a3ec5945535ed654cb38ff72d7495a25619e2247fb15a2ed9ba"
+checksum = "ba1ef8814b5c993410bb3adfad7a5ed269563e4a2f90c41f5d85be7fb47133bf"
dependencies = [
"cfg-if",
"libc",
"redox_syscall",
"smallvec",
- "windows-sys 0.42.0",
+ "windows-sys",
]
[[package]]
name = "paste"
-version = "1.0.9"
+version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b1de2e551fb905ac83f73f7aedf2f0cb4a0da7e35efa24a202a936269f1f18e1"
+checksum = "d01a5bd0424d00070b0098dd17ebca6f961a959dead1dbcbbbc1d1cd8d3deeba"
[[package]]
name = "pathdiff"
@@ -2523,9 +2523,9 @@ checksum = "8835116a5c179084a830efb3adc117ab007512b535bc1a21c991d3b32a6b44dd"
[[package]]
name = "pem"
-version = "1.1.0"
+version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "03c64931a1a212348ec4f3b4362585eca7159d0d09cbdf4a7f74f02173596fd4"
+checksum = "a8835c273a76a90455d7344889b0964598e3316e2a79ede8e36f16bdcf2228b8"
dependencies = [
"base64 0.13.1",
]
@@ -2538,9 +2538,9 @@ checksum = "478c572c3d73181ff3c2539045f6eb99e5491218eae919370993b890cdbdd98e"
[[package]]
name = "pest"
-version = "2.5.0"
+version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5f400b0f7905bf702f9f3dc3df5a121b16c54e9e8012c082905fdf09a931861a"
+checksum = "4257b4a04d91f7e9e6290be5d3da4804dd5784fafde3a497d73eb2b4a158c30a"
dependencies = [
"thiserror",
"ucd-trie",
@@ -2548,9 +2548,9 @@ dependencies = [
[[package]]
name = "pest_derive"
-version = "2.5.0"
+version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "423c2ba011d6e27b02b482a3707c773d19aec65cc024637aec44e19652e66f63"
+checksum = "241cda393b0cdd65e62e07e12454f1f25d57017dcc514b1514cd3c4645e3a0a6"
dependencies = [
"pest",
"pest_generator",
@@ -2558,9 +2558,9 @@ dependencies = [
[[package]]
name = "pest_generator"
-version = "2.5.0"
+version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3e64e6c2c85031c02fdbd9e5c72845445ca0a724d419aa0bc068ac620c9935c1"
+checksum = "46b53634d8c8196302953c74d5352f33d0c512a9499bd2ce468fc9f4128fa27c"
dependencies = [
"pest",
"pest_meta",
@@ -2571,13 +2571,13 @@ dependencies = [
[[package]]
name = "pest_meta"
-version = "2.5.0"
+version = "2.5.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "57959b91f0a133f89a68be874a5c88ed689c19cd729ecdb5d762ebf16c64d662"
+checksum = "0ef4f1332a8d4678b41966bb4cc1d0676880e84183a1ecc3f4b69f03e99c7a51"
dependencies = [
"once_cell",
"pest",
- "sha1",
+ "sha2",
]
[[package]]
@@ -2669,15 +2669,15 @@ dependencies = [
[[package]]
name = "proc-macro-hack"
-version = "0.5.19"
+version = "0.5.20+deprecated"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dbf0c48bc1d91375ae5c3cd81e3722dff1abcf81a30960240640d223f59fe0e5"
+checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068"
[[package]]
name = "proc-macro2"
-version = "1.0.49"
+version = "1.0.50"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "57a8eca9f9c4ffde41714334dee777596264c7825420f521abc92b5b5deb63a5"
+checksum = "6ef7d57beacfaf2d8aee5937dab7b7f28de3cb8b1828479bb5de2a7106f2bae2"
dependencies = [
"unicode-ident",
]
@@ -2704,9 +2704,9 @@ dependencies = [
[[package]]
name = "prost"
-version = "0.11.3"
+version = "0.11.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c0b18e655c21ff5ac2084a5ad0611e827b3f92badf79f4910b5a5c58f4d87ff0"
+checksum = "21dc42e00223fc37204bd4aa177e69420c604ca4a183209a8f9de30c6d934698"
dependencies = [
"bytes",
"prost-derive",
@@ -2714,9 +2714,9 @@ dependencies = [
[[package]]
name = "prost-derive"
-version = "0.11.2"
+version = "0.11.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "164ae68b6587001ca506d3bf7f1000bfa248d0e1217b618108fba4ec1d0cc306"
+checksum = "8bda8c0881ea9f722eb9629376db3d0b903b462477c1aafcb0566610ac28ac5d"
dependencies = [
"anyhow",
"itertools",
@@ -3112,9 +3112,9 @@ dependencies = [
[[package]]
name = "rustls"
-version = "0.20.7"
+version = "0.20.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "539a2bfe908f471bfa933876bd1eb6a19cf2176d375f82ef7f99530a40e48c2c"
+checksum = "fff78fc74d175294f4e83b28343315ffcfb114b156f0185e9741cb5570f50e2f"
dependencies = [
"log",
"ring",
@@ -3145,9 +3145,9 @@ dependencies = [
[[package]]
name = "rustversion"
-version = "1.0.9"
+version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "97477e48b4cf8603ad5f7aaf897467cf42ab4218a38ef76fb14c2d6773a6d6a8"
+checksum = "5583e89e108996506031660fe09baa5011b9dd0341b89029313006d1fb508d70"
[[package]]
name = "rusty-fork"
@@ -3163,18 +3163,17 @@ dependencies = [
[[package]]
name = "ryu"
-version = "1.0.11"
+version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09"
+checksum = "7b4b9743ed687d4b4bcedf9ff5eaa7398495ae14e61cba0a295704edbc7decde"
[[package]]
name = "schannel"
-version = "0.1.20"
+version = "0.1.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "88d6731146462ea25d9244b2ed5fd1d716d25c52e4d54aa4fb0f3c4e9854dbe2"
+checksum = "713cfb06c7059f3588fb8044c0fad1d09e3c01d225e25b9220dbfdcf16dbb1b3"
dependencies = [
- "lazy_static",
- "windows-sys 0.36.1",
+ "windows-sys",
]
[[package]]
@@ -3227,9 +3226,9 @@ dependencies = [
[[package]]
name = "semver"
-version = "1.0.14"
+version = "1.0.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e25dfac463d778e353db5be2449d1cce89bd6fd23c9f1ea21310ce6e5a1b29c4"
+checksum = "58bc9567378fc7690d6b2addae4e60ac2eeea07becb2c64b9f218b53865cba2a"
[[package]]
name = "serde"
@@ -3258,7 +3257,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877c235533714907a8c2464236f5c4b2a17262ef1bd71f38f35ea592c8da6883"
dependencies = [
"indexmap",
- "itoa 1.0.4",
+ "itoa 1.0.5",
"ryu",
"serde",
]
@@ -3301,7 +3300,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
dependencies = [
"form_urlencoded",
- "itoa 1.0.4",
+ "itoa 1.0.5",
"ryu",
"serde",
]
@@ -3515,9 +3514,9 @@ checksum = "20518fe4a4c9acf048008599e464deb21beeae3d3578418951a189c235a7a9a8"
[[package]]
name = "sysinfo"
-version = "0.27.4"
+version = "0.27.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "444c7f371193a054273b0a1bbfe1e617b804b7fd62fd3e2794b4be6b0a872b0c"
+checksum = "975fe381e0ecba475d4acff52466906d95b153a40324956552e027b2a9eaa89e"
dependencies = [
"cfg-if",
"core-foundation-sys",
@@ -3543,9 +3542,9 @@ dependencies = [
[[package]]
name = "termcolor"
-version = "1.1.3"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755"
+checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6"
dependencies = [
"winapi-util",
]
@@ -3585,7 +3584,7 @@ version = "0.3.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a561bf4617eebd33bca6434b988f39ed798e527f51a1e797d0ee4f61c0a38376"
dependencies = [
- "itoa 1.0.4",
+ "itoa 1.0.5",
"serde",
"time-core",
"time-macros",
@@ -3623,9 +3622,9 @@ checksum = "cda74da7e1a664f795bb1f8a87ec406fb89a02522cf6e50620d016add6dbbf5c"
[[package]]
name = "tokio"
-version = "1.24.1"
+version = "1.24.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1d9f76183f91ecfb55e1d7d5602bd1d979e38a3a522fe900241cf195624d67ae"
+checksum = "597a12a59981d9e3c38d216785b0c37399f6e415e8d0712047620f189371b0bb"
dependencies = [
"autocfg",
"bytes",
@@ -3638,7 +3637,7 @@ dependencies = [
"signal-hook-registry",
"socket2",
"tokio-macros",
- "windows-sys 0.42.0",
+ "windows-sys",
]
[[package]]
@@ -3785,9 +3784,9 @@ dependencies = [
[[package]]
name = "tower-http"
-version = "0.3.4"
+version = "0.3.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3c530c8675c1dbf98facee631536fa116b5fb6382d7dd6dc1b118d970eafe3ba"
+checksum = "f873044bf02dd1e8239e9c1293ea39dad76dc594ec16185d0a1bf31d8dc8d858"
dependencies = [
"bitflags",
"bytes",
@@ -3941,9 +3940,9 @@ dependencies = [
[[package]]
name = "try-lock"
-version = "0.2.3"
+version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "59547bce71d9c38b83d9c0e92b6066c4253371f15005def0c30d9657f50c7642"
+checksum = "3528ecfd12c466c6f163363caf2d02a71161dd5e1cc6ae7b34207ea2d42d81ed"
[[package]]
name = "typenum"
@@ -4240,25 +4239,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "04662ed0e3e5630dfa9b26e4cb823b817f1a9addda855d973a9458c236556244"
dependencies = [
"windows_aarch64_gnullvm",
- "windows_aarch64_msvc 0.42.0",
- "windows_i686_gnu 0.42.0",
- "windows_i686_msvc 0.42.0",
- "windows_x86_64_gnu 0.42.0",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
"windows_x86_64_gnullvm",
- "windows_x86_64_msvc 0.42.0",
-]
-
-[[package]]
-name = "windows-sys"
-version = "0.36.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ea04155a16a59f9eab786fe12a4a450e75cdb175f9e0d80da1e17db09f55b8d2"
-dependencies = [
- "windows_aarch64_msvc 0.36.1",
- "windows_i686_gnu 0.36.1",
- "windows_i686_msvc 0.36.1",
- "windows_x86_64_gnu 0.36.1",
- "windows_x86_64_msvc 0.36.1",
+ "windows_x86_64_msvc",
]
[[package]]
@@ -4268,85 +4254,55 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7"
dependencies = [
"windows_aarch64_gnullvm",
- "windows_aarch64_msvc 0.42.0",
- "windows_i686_gnu 0.42.0",
- "windows_i686_msvc 0.42.0",
- "windows_x86_64_gnu 0.42.0",
+ "windows_aarch64_msvc",
+ "windows_i686_gnu",
+ "windows_i686_msvc",
+ "windows_x86_64_gnu",
"windows_x86_64_gnullvm",
- "windows_x86_64_msvc 0.42.0",
+ "windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
-version = "0.42.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "41d2aa71f6f0cbe00ae5167d90ef3cfe66527d6f613ca78ac8024c3ccab9a19e"
-
-[[package]]
-name = "windows_aarch64_msvc"
-version = "0.36.1"
+version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9bb8c3fd39ade2d67e9874ac4f3db21f0d710bee00fe7cab16949ec184eeaa47"
+checksum = "8c9864e83243fdec7fc9c5444389dcbbfd258f745e7853198f365e3c4968a608"
[[package]]
name = "windows_aarch64_msvc"
-version = "0.42.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dd0f252f5a35cac83d6311b2e795981f5ee6e67eb1f9a7f64eb4500fbc4dcdb4"
-
-[[package]]
-name = "windows_i686_gnu"
-version = "0.36.1"
+version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "180e6ccf01daf4c426b846dfc66db1fc518f074baa793aa7d9b9aaeffad6a3b6"
+checksum = "4c8b1b673ffc16c47a9ff48570a9d85e25d265735c503681332589af6253c6c7"
[[package]]
name = "windows_i686_gnu"
-version = "0.42.0"
+version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fbeae19f6716841636c28d695375df17562ca208b2b7d0dc47635a50ae6c5de7"
+checksum = "de3887528ad530ba7bdbb1faa8275ec7a1155a45ffa57c37993960277145d640"
[[package]]
name = "windows_i686_msvc"
-version = "0.36.1"
+version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e2e7917148b2812d1eeafaeb22a97e4813dfa60a3f8f78ebe204bcc88f12f024"
-
-[[package]]
-name = "windows_i686_msvc"
-version = "0.42.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "84c12f65daa39dd2babe6e442988fc329d6243fdce47d7d2d155b8d874862246"
-
-[[package]]
-name = "windows_x86_64_gnu"
-version = "0.36.1"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4dcd171b8776c41b97521e5da127a2d86ad280114807d0b2ab1e462bc764d9e1"
+checksum = "bf4d1122317eddd6ff351aa852118a2418ad4214e6613a50e0191f7004372605"
[[package]]
name = "windows_x86_64_gnu"
-version = "0.42.0"
+version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf7b1b21b5362cbc318f686150e5bcea75ecedc74dd157d874d754a2ca44b0ed"
+checksum = "c1040f221285e17ebccbc2591ffdc2d44ee1f9186324dd3e84e99ac68d699c45"
[[package]]
name = "windows_x86_64_gnullvm"
-version = "0.42.0"
+version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "09d525d2ba30eeb3297665bd434a54297e4170c7f1a44cad4ef58095b4cd2028"
+checksum = "628bfdf232daa22b0d64fdb62b09fcc36bb01f05a3939e20ab73aaf9470d0463"
[[package]]
name = "windows_x86_64_msvc"
-version = "0.36.1"
+version = "0.42.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c811ca4a8c853ef420abd8592ba53ddbbac90410fab6903b3e79972a631f7680"
-
-[[package]]
-name = "windows_x86_64_msvc"
-version = "0.42.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f40009d85759725a34da6d89a94e63d7bdc50a862acf0dbc7c8e488f1edcb6f5"
+checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd"
[[package]]
name = "winreg"
@@ -4421,10 +4377,11 @@ dependencies = [
[[package]]
name = "zstd-sys"
-version = "2.0.4+zstd.1.5.2"
+version = "2.0.5+zstd.1.5.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4fa202f2ef00074143e219d15b62ffc317d17cc33909feac471c044087cad7b0"
+checksum = "edc50ffce891ad571e9f9afe5039c4837bede781ac4bb13052ed7ae695518596"
dependencies = [
"cc",
"libc",
+ "pkg-config",
]
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index ee19000eaae..f4aafd37b4b 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1,7 +1,13 @@
mod client;
pub(crate) mod request;
-use std::{collections::HashMap, fmt::Debug, future::Future, str, time::Instant};
+use std::{
+ collections::HashMap,
+ fmt::Debug,
+ future::Future,
+ str,
+ time::{Duration, Instant},
+};
use actix_web::{body, HttpRequest, HttpResponse, Responder};
use bytes::Bytes;
@@ -210,17 +216,16 @@ async fn send_request(
let client = client::create_client(
&state.conf.proxy,
should_bypass_proxy,
- crate::consts::REQUEST_TIME_OUT,
request.certificate,
request.certificate_key,
)?;
let headers = request.headers.construct_header_map()?;
match request.method {
- Method::Get => client.get(url).add_headers(headers).send().await,
+ Method::Get => client.get(url),
Method::Post => {
- let client = client.post(url).add_headers(headers);
+ let client = client.post(url);
match request.content_type {
- Some(ContentType::Json) => client.json(&request.payload).send(),
+ Some(ContentType::Json) => client.json(&request.payload),
// Currently this is not used remove this if not required
// If using this then handle the serde_part
@@ -236,26 +241,24 @@ async fn send_request(
})?;
logger::debug!(?url_encoded_payload);
- client.body(url_encoded_payload).send()
+ client.body(url_encoded_payload)
}
// If payload needs processing the body cannot have default
- None => client
- .body(request.payload.expose_option().unwrap_or_default())
- .send(),
+ None => client.body(request.payload.expose_option().unwrap_or_default()),
}
- .await
}
Method::Put => {
client
.put(url)
- .add_headers(headers)
.body(request.payload.expose_option().unwrap_or_default()) // If payload needs processing the body cannot have default
- .send()
- .await
}
- Method::Delete => client.delete(url).add_headers(headers).send().await,
+ Method::Delete => client.delete(url),
}
+ .add_headers(headers)
+ .timeout(Duration::from_secs(crate::consts::REQUEST_TIME_OUT))
+ .send()
+ .await
.map_err(|error| match error {
error if error.is_timeout() => errors::ApiClientError::RequestTimeoutReceived,
_ => errors::ApiClientError::RequestNotSent(error.to_string()),
diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs
index e8b8409f021..368f7cf4d6a 100644
--- a/crates/router/src/services/api/client.rs
+++ b/crates/router/src/services/api/client.rs
@@ -1,7 +1,6 @@
-use core::time::Duration;
-
use base64::Engine;
use error_stack::{IntoReport, ResultExt};
+use once_cell::sync::OnceCell;
use crate::{
configs::settings::{Locker, Proxy},
@@ -12,6 +11,10 @@ use crate::{
const HTTP_PROXY: &str = "ROUTER_HTTP_PROXY";
const HTTPS_PROXY: &str = "ROUTER_HTTPS_PROXY";
+static PLAIN_CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
+static HTTPS_PROXY_CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
+static HTTP_PROXY_CLIENT: OnceCell<reqwest::Client> = OnceCell::new();
+
enum ProxyType {
Http,
Https,
@@ -32,15 +35,59 @@ impl ProxyType {
}
}
+fn create_base_client(
+ proxy: Option<(ProxyType, String)>,
+) -> CustomResult<reqwest::Client, errors::ApiClientError> {
+ Ok(match proxy {
+ None => &PLAIN_CLIENT,
+ Some((ProxyType::Http, _)) => &HTTP_PROXY_CLIENT,
+ Some((ProxyType::Https, _)) => &HTTPS_PROXY_CLIENT,
+ }
+ .get_or_try_init(|| {
+ let mut cb = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none());
+ cb = match proxy {
+ None => cb,
+ Some((proxy_type, url)) => cb.proxy(
+ match proxy_type {
+ ProxyType::Http => reqwest::Proxy::http(url),
+ ProxyType::Https => reqwest::Proxy::https(url),
+ }
+ .into_report()
+ .change_context(errors::ApiClientError::InvalidProxyConfiguration)
+ .attach_printable("HTTP proxy configuration error")?,
+ ),
+ };
+ cb.build()
+ .into_report()
+ .change_context(errors::ApiClientError::ClientConstructionFailed)
+ .attach_printable("Error with client library")
+ })?
+ .clone())
+}
+
// We may need to use outbound proxy to connect to external world.
// Precedence will be the environment variables, followed by the config.
pub(super) fn create_client(
proxy: &Proxy,
should_bypass_proxy: bool,
- request_time_out: u64,
client_certificate: Option<String>,
client_certificate_key: Option<String>,
) -> CustomResult<reqwest::Client, errors::ApiClientError> {
+ if client_certificate.is_none() && client_certificate_key.is_none() {
+ return match should_bypass_proxy {
+ true => create_base_client(None),
+ false => create_base_client(
+ ProxyType::Https
+ .get_proxy_url(proxy)
+ .map(|url| (ProxyType::Https, url))
+ .or_else(|| {
+ ProxyType::Http
+ .get_proxy_url(proxy)
+ .map(|url| (ProxyType::Http, url))
+ }),
+ ),
+ };
+ }
let mut client_builder = reqwest::Client::builder().redirect(reqwest::redirect::Policy::none());
if !should_bypass_proxy {
@@ -94,9 +141,6 @@ pub(super) fn create_client(
_ => client_builder,
};
- let duration = Duration::from_secs(request_time_out);
- client_builder = client_builder.timeout(duration);
-
client_builder
.build()
.into_report()
|
feat
|
reuse reqwest clients for requests made to connectors (#413)
|
2cabb0bedcdf0d1adf568f2533b6ab9ce8d9fc57
|
2024-05-24 17:35:21
|
Prajjwal Kumar
|
refactor(core): Inclusion of constraint graph for merchant Payment Method list (#4626)
| false
|
diff --git a/crates/euclid/src/enums.rs b/crates/euclid/src/enums.rs
index 1aba6338d9d..8e65d23d5ea 100644
--- a/crates/euclid/src/enums.rs
+++ b/crates/euclid/src/enums.rs
@@ -79,6 +79,8 @@ pub enum MandateAcceptanceType {
pub enum PaymentType {
SetupMandate,
NonMandate,
+ NewMandate,
+ UpdateMandate,
}
#[derive(
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 71f0bdac03a..4b4eb34b7e2 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -1,6 +1,7 @@
pub mod cards;
pub mod surcharge_decision_configs;
pub mod transformers;
+pub mod utils;
pub mod vault;
pub use api_models::enums::Connector;
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 9fe8d899ea3..379050ba73e 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -5,7 +5,7 @@ use std::{
};
use api_models::{
- admin::{self, PaymentMethodsEnabled},
+ admin::PaymentMethodsEnabled,
enums::{self as api_enums},
payment_methods::{
BankAccountTokenData, Card, CardDetailUpdate, CardDetailsPaymentMethod, CardNetworkTypes,
@@ -19,18 +19,22 @@ use api_models::{
pm_auth::PaymentMethodAuthConfig,
surcharge_decision_configs as api_surcharge_decision_configs,
};
+use cgraph::ConstraintGraph;
use common_enums::enums::MerchantStorageScheme;
use common_utils::{
consts,
ext_traits::{AsyncExt, Encode, StringExt, ValueExt},
generate_id,
};
-use diesel_models::{
- business_profile::BusinessProfile, encryption::Encryption, enums as storage_enums,
- payment_method,
-};
+use diesel_models::{business_profile::BusinessProfile, encryption::Encryption, payment_method};
use domain::CustomerUpdate;
use error_stack::{report, ResultExt};
+use euclid::{
+ dssa::graph::{AnalysisContext, CgraphExt},
+ frontend::dir,
+};
+use hyperswitch_constraint_graph as cgraph;
+use kgraph_utils::transformers::IntoDirValue;
use masking::Secret;
use router_env::{instrument, tracing};
use strum::IntoEnumIterator;
@@ -45,7 +49,11 @@ use crate::{
configs::settings,
core::{
errors::{self, StorageErrorExt},
- payment_methods::{transformers as payment_methods, vault},
+ payment_methods::{
+ transformers as payment_methods,
+ utils::{get_merchant_pm_filter_graph, make_pm_graph, refresh_pm_filters_cache},
+ vault,
+ },
payments::{
helpers,
routing::{self, SessionFlowRoutingInput},
@@ -1876,31 +1884,94 @@ 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);
+ let filtered_mcas =
+ helpers::filter_mca_based_on_business_profile(all_mcas.clone(), profile_id.clone());
logger::debug!(mca_before_filtering=?filtered_mcas);
let mut response: Vec<ResponsePaymentMethodIntermediate> = vec![];
- for mca in &filtered_mcas {
- let payment_methods = match &mca.payment_methods_enabled {
- Some(pm) => pm.clone(),
- None => continue,
- };
- filter_payment_methods(
- payment_methods,
- &mut req,
- &mut response,
- payment_intent.as_ref(),
- payment_attempt.as_ref(),
- billing_address.as_ref(),
- mca.connector_name.clone(),
- pm_config_mapping,
- &state.conf.mandates.supported_payment_methods,
- &state.conf.mandates.update_mandate_supported,
- &state.conf.saved_payment_methods,
+ // Key creation for storing PM_FILTER_CGRAPH
+ #[cfg(feature = "business_profile_routing")]
+ let key = {
+ let profile_id = profile_id
+ .clone()
+ .get_required_value("profile_id")
+ .change_context(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "Profile id not found".to_string(),
+ })?;
+ format!(
+ "pm_filters_cgraph_{}_{}",
+ &merchant_account.merchant_id, profile_id
)
- .await?;
+ };
+
+ #[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(&key).await {
+ // Derivation of PM_FILTER_CGRAPH from MokaCache successful
+ for mca in &filtered_mcas {
+ let payment_methods = match &mca.payment_methods_enabled {
+ Some(pm) => pm,
+ None => continue,
+ };
+ filter_payment_methods(
+ &graph,
+ payment_methods,
+ &mut req,
+ &mut response,
+ payment_intent.as_ref(),
+ payment_attempt.as_ref(),
+ billing_address.as_ref(),
+ mca.connector_name.clone(),
+ &state.conf.saved_payment_methods,
+ )
+ .await?;
+ }
+ } else {
+ // No PM_FILTER_CGRAPH Cache present in MokaCache
+ let mut builder = cgraph::ConstraintGraphBuilder::<'static, _>::new();
+ for mca in &filtered_mcas {
+ let payment_methods = match &mca.payment_methods_enabled {
+ Some(pm) => pm,
+ None => continue,
+ };
+ if let Err(e) = make_pm_graph(
+ &mut builder,
+ payment_methods,
+ mca.connector_name.clone(),
+ pm_config_mapping,
+ &state.conf.mandates.supported_payment_methods,
+ &state.conf.mandates.update_mandate_supported,
+ ) {
+ logger::error!(
+ "Failed to construct constraint graph for list payment methods {e:?}"
+ );
+ }
+ }
+
+ // Refreshing our CGraph cache
+ let graph = refresh_pm_filters_cache(&key, builder.build()).await;
+
+ for mca in &filtered_mcas {
+ let payment_methods = match &mca.payment_methods_enabled {
+ Some(pm) => pm,
+ None => continue,
+ };
+ filter_payment_methods(
+ &graph,
+ payment_methods,
+ &mut req,
+ &mut response,
+ payment_intent.as_ref(),
+ payment_attempt.as_ref(),
+ billing_address.as_ref(),
+ mca.connector_name.clone(),
+ &state.conf.saved_payment_methods,
+ )
+ .await?;
+ }
}
// Filter out wallet payment method from mca if customer has already saved it
@@ -2757,20 +2828,18 @@ pub async fn call_surcharge_decision_management_for_saved_card(
#[allow(clippy::too_many_arguments)]
pub async fn filter_payment_methods(
- payment_methods: Vec<serde_json::Value>,
+ graph: &ConstraintGraph<'_, dir::DirValue>,
+ payment_methods: &[serde_json::Value],
req: &mut api::PaymentMethodListRequest,
resp: &mut Vec<ResponsePaymentMethodIntermediate>,
payment_intent: Option<&storage::PaymentIntent>,
payment_attempt: Option<&storage::PaymentAttempt>,
address: Option<&domain::Address>,
connector: String,
- config: &settings::ConnectorFilters,
- supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
- supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate,
saved_payment_methods: &settings::EligiblePaymentMethods,
) -> errors::CustomResult<(), errors::ApiErrorResponse> {
- for payment_method in payment_methods.into_iter() {
- let parse_result = serde_json::from_value::<PaymentMethodsEnabled>(payment_method);
+ for payment_method in payment_methods.iter() {
+ let parse_result = serde_json::from_value::<PaymentMethodsEnabled>(payment_method.clone());
if let Ok(payment_methods_enabled) = parse_result {
let payment_method = payment_methods_enabled.payment_method;
@@ -2801,57 +2870,13 @@ pub async fn filter_payment_methods(
.map(|minor_amount| minor_amount.get_amount_as_i64()),
)
{
- let mut payment_method_object = payment_method_type_info;
-
- let filter;
- (
- payment_method_object.accepted_countries,
- req.accepted_countries,
- filter,
- ) = filter_pm_country_based(
- &payment_method_object.accepted_countries,
- &req.accepted_countries,
- );
- let filter2;
- (
- payment_method_object.accepted_currencies,
- req.accepted_currencies,
- filter2,
- ) = filter_pm_currencies_based(
- &payment_method_object.accepted_currencies,
- &req.accepted_currencies,
- );
+ let payment_method_object = payment_method_type_info.clone();
- let filter4 = filter_pm_card_network_based(
- payment_method_object.card_networks.as_ref(),
- req.card_networks.as_ref(),
- &payment_method_object.payment_method_type,
- );
-
- let filter3 = if let Some(payment_intent) = payment_intent {
- filter_payment_country_based(&payment_method_object, address).await?
- && filter_payment_currency_based(payment_intent, &payment_method_object)
- && filter_payment_amount_based(payment_intent, &payment_method_object)
- && filter_payment_mandate_based(payment_attempt, &payment_method_object)
- .await?
- } else {
- true
- };
-
- let filter5 = filter_pm_based_on_config(
- config,
- &connector,
- &payment_method_object.payment_method_type,
- payment_attempt,
- &mut payment_method_object.card_networks,
- &address.and_then(|inner| inner.country),
- payment_attempt.and_then(|value| value.currency),
- );
-
- let filter6 = filter_pm_based_on_allowed_types(
- allowed_payment_method_types.as_ref(),
- &payment_method_object.payment_method_type,
- );
+ let pm_dir_value: dir::DirValue =
+ (payment_method_type_info.payment_method_type, payment_method)
+ .into_dir_value()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("pm_value_node not created")?;
let connector_variant = api_enums::Connector::from_str(connector.as_str())
.change_context(errors::ConnectorError::InvalidConnectorName)
@@ -2861,35 +2886,98 @@ pub async fn filter_payment_methods(
.attach_printable_lazy(|| {
format!("unable to parse connector name {connector:?}")
})?;
- let filter7 = payment_attempt
- .and_then(|attempt| attempt.mandate_details.as_ref())
- .map(|_mandate_details| {
- filter_pm_based_on_supported_payments_for_mandate(
- supported_payment_methods_for_mandate,
- &payment_method,
- &payment_method_object.payment_method_type,
- connector_variant,
- )
+
+ let mut context_values: Vec<dir::DirValue> = Vec::new();
+ context_values.push(pm_dir_value.clone());
+
+ payment_intent.map(|intent| {
+ intent.currency.map(|currency| {
+ context_values.push(dir::DirValue::PaymentCurrency(currency))
})
- .unwrap_or(true);
+ });
+ address.map(|address| {
+ address.country.map(|country| {
+ context_values.push(dir::DirValue::BillingCountry(
+ common_enums::Country::from_alpha2(country),
+ ))
+ })
+ });
- let filter8 = payment_attempt
+ let filter_pm_based_on_allowed_types = filter_pm_based_on_allowed_types(
+ allowed_payment_method_types.as_ref(),
+ &payment_method_object.payment_method_type,
+ );
+
+ if payment_attempt
+ .and_then(|attempt| attempt.mandate_details.as_ref())
+ .is_some()
+ {
+ context_values.push(dir::DirValue::PaymentType(
+ euclid::enums::PaymentType::NewMandate,
+ ));
+ if let Ok(connector) = api_enums::RoutableConnectors::from_str(
+ connector_variant.to_string().as_str(),
+ ) {
+ context_values.push(dir::DirValue::Connector(Box::new(
+ api_models::routing::ast::ConnectorChoice {
+ connector,
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ sub_label: None,
+ },
+ )));
+ };
+ };
+
+ payment_attempt
.and_then(|attempt| attempt.mandate_data.as_ref())
.map(|mandate_detail| {
if mandate_detail.update_mandate_id.is_some() {
- filter_pm_based_on_update_mandate_support_for_connector(
- supported_payment_methods_for_update_mandate,
- &payment_method,
- &payment_method_object.payment_method_type,
- connector_variant,
- )
- } else {
- true
+ context_values.push(dir::DirValue::PaymentType(
+ euclid::enums::PaymentType::UpdateMandate,
+ ));
+ if let Ok(connector) = api_enums::RoutableConnectors::from_str(
+ connector_variant.to_string().as_str(),
+ ) {
+ context_values.push(dir::DirValue::Connector(Box::new(
+ api_models::routing::ast::ConnectorChoice {
+ connector,
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ sub_label: None,
+ },
+ )));
+ };
}
+ });
+
+ payment_attempt
+ .map(|attempt| {
+ attempt.mandate_data.is_none() && attempt.mandate_details.is_none()
})
- .unwrap_or(true);
+ .and_then(|res| {
+ res.then(|| {
+ context_values.push(dir::DirValue::PaymentType(
+ euclid::enums::PaymentType::NonMandate,
+ ))
+ })
+ });
+
+ payment_attempt
+ .and_then(|inner| inner.capture_method)
+ .and_then(|capture_method| {
+ (capture_method == common_enums::CaptureMethod::Manual).then(|| {
+ context_values.push(dir::DirValue::CaptureMethod(
+ common_enums::CaptureMethod::Manual,
+ ));
+ })
+ });
- let filter9 = req
+ let filter_pm_card_network_based = filter_pm_card_network_based(
+ payment_method_object.card_networks.as_ref(),
+ req.card_networks.as_ref(),
+ &payment_method_object.payment_method_type,
+ );
+
+ let saved_payment_methods_filter = req
.client_secret
.as_ref()
.map(|cs| {
@@ -2903,25 +2991,28 @@ pub async fn filter_payment_methods(
})
.unwrap_or(true);
- let connector = connector.clone();
+ let context = AnalysisContext::from_dir_values(context_values.clone());
- let response_pm_type = ResponsePaymentMethodIntermediate::new(
- payment_method_object,
- connector,
- payment_method,
+ let result = graph.key_value_analysis(
+ pm_dir_value.clone(),
+ &context,
+ &mut cgraph::Memoization::new(),
+ &mut cgraph::CycleCheck::new(),
+ None,
);
-
- if filter
- && filter2
- && filter3
- && filter4
- && filter5
- && filter6
- && filter7
- && filter8
- && filter9
+ if filter_pm_based_on_allowed_types
+ && filter_pm_card_network_based
+ && saved_payment_methods_filter
+ && matches!(result, Ok(()))
{
+ let response_pm_type = ResponsePaymentMethodIntermediate::new(
+ payment_method_object,
+ connector.clone(),
+ payment_method,
+ );
resp.push(response_pm_type);
+ } else {
+ logger::error!("Filtering Payment Methods Failed");
}
}
}
@@ -2929,287 +3020,12 @@ pub async fn filter_payment_methods(
}
Ok(())
}
-pub fn filter_pm_based_on_update_mandate_support_for_connector(
- supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
- payment_method: &api_enums::PaymentMethod,
- payment_method_type: &api_enums::PaymentMethodType,
- connector: api_enums::Connector,
-) -> bool {
- if payment_method == &api_enums::PaymentMethod::Card {
- supported_payment_methods_for_mandate
- .0
- .get(payment_method)
- .map(|payment_method_type_hm| {
- let pm_credit = payment_method_type_hm
- .0
- .get(&api_enums::PaymentMethodType::Credit)
- .map(|conn| conn.connector_list.clone())
- .unwrap_or_default();
- let pm_debit = payment_method_type_hm
- .0
- .get(&api_enums::PaymentMethodType::Debit)
- .map(|conn| conn.connector_list.clone())
- .unwrap_or_default();
- &pm_credit | &pm_debit
- })
- .map(|supported_connectors| supported_connectors.contains(&connector))
- .unwrap_or(false)
- } else {
- supported_payment_methods_for_mandate
- .0
- .get(payment_method)
- .and_then(|payment_method_type_hm| payment_method_type_hm.0.get(payment_method_type))
- .map(|supported_connectors| supported_connectors.connector_list.contains(&connector))
- .unwrap_or(false)
- }
-}
-
-fn filter_pm_based_on_supported_payments_for_mandate(
- supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
- payment_method: &api_enums::PaymentMethod,
- payment_method_type: &api_enums::PaymentMethodType,
- connector: api_enums::Connector,
-) -> bool {
- supported_payment_methods_for_mandate
- .0
- .get(payment_method)
- .and_then(|payment_method_type_hm| payment_method_type_hm.0.get(payment_method_type))
- .map(|supported_connectors| supported_connectors.connector_list.contains(&connector))
- .unwrap_or(false)
-}
-fn filter_pm_based_on_config<'a>(
- config: &'a settings::ConnectorFilters,
- connector: &'a str,
- payment_method_type: &'a api_enums::PaymentMethodType,
- payment_attempt: Option<&storage::PaymentAttempt>,
- card_network: &mut Option<Vec<api_enums::CardNetwork>>,
- country: &Option<api_enums::CountryAlpha2>,
- currency: Option<api_enums::Currency>,
-) -> bool {
- config
- .0
- .get(connector)
- .or_else(|| config.0.get("default"))
- .and_then(|inner| match payment_method_type {
- api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
- let country_currency_filter = inner
- .0
- .get(&settings::PaymentMethodFilterKey::PaymentMethodType(
- *payment_method_type,
- ))
- .map(|value| global_country_currency_filter(value, country, currency));
-
- card_network_filter(country, currency, card_network, inner);
-
- let capture_method_filter = payment_attempt
- .and_then(|inner| inner.capture_method)
- .and_then(|capture_method| {
- (capture_method == storage_enums::CaptureMethod::Manual).then(|| {
- filter_pm_based_on_capture_method_used(inner, payment_method_type)
- })
- });
-
- Some(
- country_currency_filter.unwrap_or(true)
- && capture_method_filter.unwrap_or(true),
- )
- }
- payment_method_type => inner
- .0
- .get(&settings::PaymentMethodFilterKey::PaymentMethodType(
- *payment_method_type,
- ))
- .map(|value| global_country_currency_filter(value, country, currency)),
- })
- .unwrap_or(true)
-}
-
-///Filters the payment method list on basis of Capture methods, checks whether the connector issues Manual payments using cards or not if not it won't be visible in payment methods list
-fn filter_pm_based_on_capture_method_used(
- payment_method_filters: &settings::PaymentMethodFilters,
+fn filter_pm_based_on_allowed_types(
+ allowed_types: Option<&Vec<api_enums::PaymentMethodType>>,
payment_method_type: &api_enums::PaymentMethodType,
) -> bool {
- payment_method_filters
- .0
- .get(&settings::PaymentMethodFilterKey::PaymentMethodType(
- *payment_method_type,
- ))
- .and_then(|v| v.not_available_flows)
- .and_then(|v| v.capture_method)
- .map(|v| !matches!(v, api_enums::CaptureMethod::Manual))
- .unwrap_or(true)
-}
-
-fn card_network_filter(
- country: &Option<api_enums::CountryAlpha2>,
- currency: Option<api_enums::Currency>,
- card_network: &mut Option<Vec<api_enums::CardNetwork>>,
- payment_method_filters: &settings::PaymentMethodFilters,
-) {
- if let Some(value) = card_network.as_mut() {
- let filtered_card_networks = value
- .iter()
- .filter(|&element| {
- let key = settings::PaymentMethodFilterKey::CardNetwork(element.clone());
- payment_method_filters
- .0
- .get(&key)
- .map(|value| global_country_currency_filter(value, country, currency))
- .unwrap_or(true)
- })
- .cloned()
- .collect::<Vec<_>>();
- *value = filtered_card_networks;
- }
-}
-
-fn global_country_currency_filter(
- item: &settings::CurrencyCountryFlowFilter,
- country: &Option<api_enums::CountryAlpha2>,
- currency: Option<api_enums::Currency>,
-) -> bool {
- let country_condition = item
- .country
- .as_ref()
- .zip(country.as_ref())
- .map(|(lhs, rhs)| lhs.contains(rhs));
- let currency_condition = item
- .currency
- .as_ref()
- .zip(currency)
- .map(|(lhs, rhs)| lhs.contains(&rhs));
- country_condition.unwrap_or(true) && currency_condition.unwrap_or(true)
-}
-
-fn filter_pm_card_network_based(
- pm_card_networks: Option<&Vec<api_enums::CardNetwork>>,
- request_card_networks: Option<&Vec<api_enums::CardNetwork>>,
- pm_type: &api_enums::PaymentMethodType,
-) -> bool {
- match pm_type {
- api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
- match (pm_card_networks, request_card_networks) {
- (Some(pm_card_networks), Some(request_card_networks)) => request_card_networks
- .iter()
- .all(|card_network| pm_card_networks.contains(card_network)),
- (None, Some(_)) => false,
- _ => true,
- }
- }
- _ => true,
- }
-}
-fn filter_pm_country_based(
- accepted_countries: &Option<admin::AcceptedCountries>,
- req_country_list: &Option<Vec<api_enums::CountryAlpha2>>,
-) -> (
- Option<admin::AcceptedCountries>,
- Option<Vec<api_enums::CountryAlpha2>>,
- bool,
-) {
- match (accepted_countries, req_country_list) {
- (None, None) => (None, None, true),
- (None, Some(ref r)) => (
- Some(admin::AcceptedCountries::EnableOnly(r.to_vec())),
- Some(r.to_vec()),
- true,
- ),
- (Some(l), None) => (Some(l.to_owned()), None, true),
- (Some(l), Some(ref r)) => {
- let updated = match l {
- admin::AcceptedCountries::EnableOnly(acc) => {
- filter_accepted_enum_based(&Some(acc.clone()), &Some(r.to_owned()))
- .map(admin::AcceptedCountries::EnableOnly)
- }
-
- admin::AcceptedCountries::DisableOnly(den) => {
- filter_disabled_enum_based(&Some(den.clone()), &Some(r.to_owned()))
- .map(admin::AcceptedCountries::DisableOnly)
- }
-
- admin::AcceptedCountries::AllAccepted => {
- Some(admin::AcceptedCountries::AllAccepted)
- }
- };
-
- (updated, Some(r.to_vec()), true)
- }
- }
-}
-
-fn filter_pm_currencies_based(
- accepted_currency: &Option<admin::AcceptedCurrencies>,
- req_currency_list: &Option<Vec<api_enums::Currency>>,
-) -> (
- Option<admin::AcceptedCurrencies>,
- Option<Vec<api_enums::Currency>>,
- bool,
-) {
- match (accepted_currency, req_currency_list) {
- (None, None) => (None, None, true),
- (None, Some(ref r)) => (
- Some(admin::AcceptedCurrencies::EnableOnly(r.to_vec())),
- Some(r.to_vec()),
- true,
- ),
- (Some(l), None) => (Some(l.to_owned()), None, true),
- (Some(l), Some(ref r)) => {
- let updated = match l {
- admin::AcceptedCurrencies::EnableOnly(acc) => {
- filter_accepted_enum_based(&Some(acc.clone()), &Some(r.to_owned()))
- .map(admin::AcceptedCurrencies::EnableOnly)
- }
-
- admin::AcceptedCurrencies::DisableOnly(den) => {
- filter_disabled_enum_based(&Some(den.clone()), &Some(r.to_owned()))
- .map(admin::AcceptedCurrencies::DisableOnly)
- }
-
- admin::AcceptedCurrencies::AllAccepted => {
- Some(admin::AcceptedCurrencies::AllAccepted)
- }
- };
-
- (updated, Some(r.to_vec()), true)
- }
- }
-}
-
-fn filter_accepted_enum_based<T: Eq + std::hash::Hash + Clone>(
- left: &Option<Vec<T>>,
- right: &Option<Vec<T>>,
-) -> Option<Vec<T>> {
- match (left, right) {
- (Some(ref l), Some(ref r)) => {
- let a: HashSet<&T> = HashSet::from_iter(l.iter());
- let b: HashSet<&T> = HashSet::from_iter(r.iter());
-
- let y: Vec<T> = a.intersection(&b).map(|&i| i.to_owned()).collect();
- Some(y)
- }
- (Some(ref l), None) => Some(l.to_vec()),
- (_, _) => None,
- }
-}
-
-fn filter_disabled_enum_based<T: Eq + std::hash::Hash + Clone>(
- left: &Option<Vec<T>>,
- right: &Option<Vec<T>>,
-) -> Option<Vec<T>> {
- match (left, right) {
- (Some(ref l), Some(ref r)) => {
- let mut enabled = Vec::new();
- for element in r {
- if !l.contains(element) {
- enabled.push(element.to_owned());
- }
- }
- Some(enabled)
- }
- (None, Some(r)) => Some(r.to_vec()),
- (_, _) => None,
- }
+ allowed_types.map_or(true, |pm| pm.contains(payment_method_type))
}
fn filter_amount_based(payment_method: &RequestPaymentMethodTypes, amount: Option<i64>) -> bool {
@@ -3227,24 +3043,9 @@ fn filter_amount_based(payment_method: &RequestPaymentMethodTypes, amount: Optio
.map(|max_amt| amt <= max_amt.into())
})
.unwrap_or(true);
- // let min_check = match (amount, payment_method.minimum_amount) {
- // (Some(amt), Some(min_amt)) => amt >= min_amt,
- // (_, _) => true,
- // };
- // let max_check = match (amount, payment_method.maximum_amount) {
- // (Some(amt), Some(max_amt)) => amt <= max_amt,
- // (_, _) => true,
- // };
(min_check && max_check) || amount == Some(0)
}
-fn filter_pm_based_on_allowed_types(
- allowed_types: Option<&Vec<api_enums::PaymentMethodType>>,
- payment_method_type: &api_enums::PaymentMethodType,
-) -> bool {
- allowed_types.map_or(true, |pm| pm.contains(payment_method_type))
-}
-
fn filter_recurring_based(
payment_method: &RequestPaymentMethodTypes,
recurring_enabled: Option<bool>,
@@ -3261,54 +3062,23 @@ fn filter_installment_based(
})
}
-async fn filter_payment_country_based(
- pm: &RequestPaymentMethodTypes,
- address: Option<&domain::Address>,
-) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
- Ok(address.map_or(true, |address| {
- address.country.as_ref().map_or(true, |country| {
- pm.accepted_countries.as_ref().map_or(true, |ac| match ac {
- admin::AcceptedCountries::EnableOnly(acc) => acc.contains(country),
- admin::AcceptedCountries::DisableOnly(den) => !den.contains(country),
- admin::AcceptedCountries::AllAccepted => true,
- })
- })
- }))
-}
-
-fn filter_payment_currency_based(
- payment_intent: &storage::PaymentIntent,
- pm: &RequestPaymentMethodTypes,
-) -> bool {
- payment_intent.currency.map_or(true, |currency| {
- pm.accepted_currencies.as_ref().map_or(true, |ac| match ac {
- admin::AcceptedCurrencies::EnableOnly(acc) => acc.contains(¤cy),
- admin::AcceptedCurrencies::DisableOnly(den) => !den.contains(¤cy),
- admin::AcceptedCurrencies::AllAccepted => true,
- })
- })
-}
-
-fn filter_payment_amount_based(
- payment_intent: &storage::PaymentIntent,
- pm: &RequestPaymentMethodTypes,
+fn filter_pm_card_network_based(
+ pm_card_networks: Option<&Vec<api_enums::CardNetwork>>,
+ request_card_networks: Option<&Vec<api_enums::CardNetwork>>,
+ pm_type: &api_enums::PaymentMethodType,
) -> bool {
- let amount = payment_intent.amount.get_amount_as_i64();
- (pm.maximum_amount.map_or(true, |amt| amount <= amt.into())
- && pm.minimum_amount.map_or(true, |amt| amount >= amt.into()))
- || payment_intent.amount.get_amount_as_i64() == 0
-}
-
-async fn filter_payment_mandate_based(
- payment_attempt: Option<&storage::PaymentAttempt>,
- pm: &RequestPaymentMethodTypes,
-) -> errors::CustomResult<bool, errors::ApiErrorResponse> {
- let recurring_filter = if !pm.recurring_enabled {
- payment_attempt.map_or(true, |pa| pa.mandate_id.is_none())
- } else {
- true
- };
- Ok(recurring_filter)
+ match pm_type {
+ api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit => {
+ match (pm_card_networks, request_card_networks) {
+ (Some(pm_card_networks), Some(request_card_networks)) => request_card_networks
+ .iter()
+ .all(|card_network| pm_card_networks.contains(card_network)),
+ (None, Some(_)) => false,
+ _ => true,
+ }
+ }
+ _ => true,
+ }
}
pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
diff --git a/crates/router/src/core/payment_methods/utils.rs b/crates/router/src/core/payment_methods/utils.rs
new file mode 100644
index 00000000000..fc7416bf7ed
--- /dev/null
+++ b/crates/router/src/core/payment_methods/utils.rs
@@ -0,0 +1,828 @@
+use std::{str::FromStr, sync::Arc};
+
+use api_models::{
+ admin::{self, PaymentMethodsEnabled},
+ enums as api_enums,
+ payment_methods::RequestPaymentMethodTypes,
+};
+use common_enums::enums;
+use euclid::frontend::dir;
+use hyperswitch_constraint_graph as cgraph;
+use kgraph_utils::{error::KgraphError, transformers::IntoDirValue};
+use storage_impl::redis::cache::PM_FILTERS_CGRAPH_CACHE;
+
+use crate::configs::settings;
+
+pub fn make_pm_graph(
+ builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>,
+ payment_methods: &[serde_json::value::Value],
+ connector: String,
+ pm_config_mapping: &settings::ConnectorFilters,
+ supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
+ supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate,
+) -> Result<(), KgraphError> {
+ for payment_method in payment_methods.iter() {
+ let pm_enabled = serde_json::from_value::<PaymentMethodsEnabled>(payment_method.clone());
+ if let Ok(payment_methods_enabled) = pm_enabled {
+ compile_pm_graph(
+ builder,
+ payment_methods_enabled.clone(),
+ connector.clone(),
+ pm_config_mapping,
+ supported_payment_methods_for_mandate,
+ supported_payment_methods_for_update_mandate,
+ )?;
+ };
+ }
+ Ok(())
+}
+
+pub async fn get_merchant_pm_filter_graph<'a>(
+ key: &str,
+) -> Option<Arc<hyperswitch_constraint_graph::ConstraintGraph<'a, dir::DirValue>>> {
+ PM_FILTERS_CGRAPH_CACHE
+ .get_val::<Arc<hyperswitch_constraint_graph::ConstraintGraph<'_, dir::DirValue>>>(key)
+ .await
+}
+
+pub async fn refresh_pm_filters_cache(
+ key: &str,
+ graph: cgraph::ConstraintGraph<'static, dir::DirValue>,
+) -> Arc<hyperswitch_constraint_graph::ConstraintGraph<'static, dir::DirValue>> {
+ let pm_filter_graph = Arc::new(graph);
+ PM_FILTERS_CGRAPH_CACHE
+ .push(key.to_string(), pm_filter_graph.clone())
+ .await;
+ pm_filter_graph
+}
+
+fn compile_pm_graph(
+ builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>,
+ pm_enabled: PaymentMethodsEnabled,
+ connector: String,
+ config: &settings::ConnectorFilters,
+ supported_payment_methods_for_mandate: &settings::SupportedPaymentMethodsForMandate,
+ supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate,
+) -> Result<(), KgraphError> {
+ if let Some(payment_method_types) = pm_enabled.payment_method_types {
+ for pmt in payment_method_types {
+ let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> =
+ Vec::new();
+ let mut agg_or_nodes_for_mandate_filters: Vec<(
+ cgraph::NodeId,
+ cgraph::Relation,
+ cgraph::Strength,
+ )> = Vec::new();
+
+ // Connector supported for Update mandate filter
+ let res = construct_supported_connectors_for_update_mandate_node(
+ builder,
+ supported_payment_methods_for_update_mandate,
+ pmt.clone(),
+ &pm_enabled.payment_method,
+ );
+ if let Ok(Some(connector_eligible_for_update_mandates_node)) = res {
+ agg_or_nodes_for_mandate_filters.push((
+ connector_eligible_for_update_mandates_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ))
+ }
+
+ // Connector supported for mandates filter
+ if let Some(supported_pm_for_mandates) = supported_payment_methods_for_mandate
+ .0
+ .get(&pm_enabled.payment_method)
+ {
+ if let Some(supported_connector_for_mandates) =
+ supported_pm_for_mandates.0.get(&pmt.payment_method_type)
+ {
+ let supported_connectors: Vec<api_enums::Connector> =
+ supported_connector_for_mandates
+ .connector_list
+ .clone()
+ .into_iter()
+ .collect();
+ if let Ok(Some(connector_eligible_for_mandates_node)) =
+ construct_supported_connectors_for_mandate_node(
+ builder,
+ supported_connectors,
+ )
+ {
+ agg_or_nodes_for_mandate_filters.push((
+ connector_eligible_for_mandates_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ))
+ }
+ }
+ }
+
+ // Non Prominent Mandate flows
+ let payment_type_non_mandate_value_node = builder.make_value_node(
+ cgraph::NodeValue::Value(dir::DirValue::PaymentType(
+ euclid::enums::PaymentType::NonMandate,
+ )),
+ None,
+ None::<()>,
+ );
+ let payment_type_setup_mandate_value_node = builder.make_value_node(
+ cgraph::NodeValue::Value(dir::DirValue::PaymentType(
+ euclid::enums::PaymentType::SetupMandate,
+ )),
+ None,
+ None::<()>,
+ );
+
+ let non_major_mandate_any_node = builder
+ .make_any_aggregator(
+ &[
+ (
+ payment_type_non_mandate_value_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ (
+ payment_type_setup_mandate_value_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ ],
+ None,
+ None::<()>,
+ None,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ agg_or_nodes_for_mandate_filters.push((
+ non_major_mandate_any_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ));
+
+ let agg_or_node = builder
+ .make_any_aggregator(&agg_or_nodes_for_mandate_filters, None, None::<()>, None)
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ agg_nodes.push((
+ agg_or_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ));
+
+ // Capture Method filter
+ config
+ .0
+ .get(connector.as_str())
+ .or_else(|| config.0.get("default"))
+ .map(|inner| {
+ if let Ok(Some(capture_method_filter)) =
+ construct_capture_method_node(builder, inner, &pmt.payment_method_type)
+ {
+ agg_nodes.push((
+ capture_method_filter,
+ cgraph::Relation::Negative,
+ cgraph::Strength::Strong,
+ ))
+ }
+ });
+
+ // Country filter
+ if let Some(pm_object_countries) = pmt.accepted_countries {
+ if let Ok(Some(country_node)) = compile_accepted_countries_for_mca(
+ builder,
+ &pmt.payment_method_type,
+ pm_object_countries,
+ config,
+ connector.clone(),
+ ) {
+ agg_nodes.push((
+ country_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ))
+ }
+ }
+
+ // Currency filter
+ if let Some(pm_object_currencies) = pmt.accepted_currencies {
+ if let Ok(Some(currency_node)) = compile_accepted_currency_for_mca(
+ builder,
+ &pmt.payment_method_type,
+ pm_object_currencies,
+ config,
+ connector.clone(),
+ ) {
+ agg_nodes.push((
+ currency_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ))
+ }
+ }
+
+ let and_node_for_all_the_filters = builder
+ .make_all_aggregator(&agg_nodes, None, None::<()>, None)
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ // Making our output node
+ let pmt_info = "PaymentMethodType";
+ let dir_node: cgraph::NodeValue<dir::DirValue> =
+ (pmt.payment_method_type, pm_enabled.payment_method)
+ .into_dir_value()
+ .map(Into::into)?;
+ let payment_method_type_value_node =
+ builder.make_value_node(dir_node, Some(pmt_info), None::<()>);
+
+ builder
+ .make_edge(
+ and_node_for_all_the_filters,
+ payment_method_type_value_node,
+ cgraph::Strength::Strong,
+ cgraph::Relation::Positive,
+ None::<cgraph::DomainId>,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
+ }
+ }
+ Ok(())
+}
+
+fn construct_capture_method_node(
+ builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>,
+ payment_method_filters: &settings::PaymentMethodFilters,
+ payment_method_type: &api_enums::PaymentMethodType,
+) -> Result<Option<cgraph::NodeId>, KgraphError> {
+ if !payment_method_filters
+ .0
+ .get(&settings::PaymentMethodFilterKey::PaymentMethodType(
+ *payment_method_type,
+ ))
+ .and_then(|v| v.not_available_flows)
+ .and_then(|v| v.capture_method)
+ .map(|v| !matches!(v, api_enums::CaptureMethod::Manual))
+ .unwrap_or(true)
+ {
+ return Ok(Some(builder.make_value_node(
+ cgraph::NodeValue::Value(dir::DirValue::CaptureMethod(
+ common_enums::CaptureMethod::Manual,
+ )),
+ None,
+ None::<()>,
+ )));
+ }
+ Ok(None)
+}
+
+fn construct_supported_connectors_for_update_mandate_node(
+ builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>,
+ supported_payment_methods_for_update_mandate: &settings::SupportedPaymentMethodsForMandate,
+ pmt: RequestPaymentMethodTypes,
+ payment_method: &enums::PaymentMethod,
+) -> Result<Option<cgraph::NodeId>, KgraphError> {
+ let card_value_node = builder.make_value_node(
+ cgraph::NodeValue::Value(dir::DirValue::PaymentMethod(enums::PaymentMethod::Card)),
+ None,
+ None::<()>,
+ );
+
+ let payment_type_value_node = builder.make_value_node(
+ cgraph::NodeValue::Value(dir::DirValue::PaymentType(
+ euclid::enums::PaymentType::UpdateMandate,
+ )),
+ None,
+ None::<()>,
+ );
+
+ let mut agg_nodes: Vec<(cgraph::NodeId, cgraph::Relation, cgraph::Strength)> = Vec::new();
+ let mut card_dir_values = Vec::new();
+ let mut non_card_dir_values = Vec::new();
+
+ if let Some(supported_pm_for_mandates) = supported_payment_methods_for_update_mandate
+ .0
+ .get(payment_method)
+ {
+ if payment_method == &enums::PaymentMethod::Card {
+ if let Some(credit_connector_list) = supported_pm_for_mandates
+ .0
+ .get(&api_enums::PaymentMethodType::Credit)
+ {
+ card_dir_values.extend(
+ credit_connector_list
+ .connector_list
+ .clone()
+ .into_iter()
+ .filter_map(|connector| {
+ api_enums::RoutableConnectors::from_str(connector.to_string().as_str())
+ .ok()
+ .map(|connector| {
+ dir::DirValue::Connector(Box::new(
+ api_models::routing::ast::ConnectorChoice {
+ connector,
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ sub_label: None,
+ },
+ ))
+ })
+ }),
+ );
+ }
+
+ if let Some(debit_connector_list) = supported_pm_for_mandates
+ .0
+ .get(&api_enums::PaymentMethodType::Debit)
+ {
+ card_dir_values.extend(
+ debit_connector_list
+ .connector_list
+ .clone()
+ .into_iter()
+ .filter_map(|connector| {
+ api_enums::RoutableConnectors::from_str(connector.to_string().as_str())
+ .ok()
+ .map(|connector| {
+ dir::DirValue::Connector(Box::new(
+ api_models::routing::ast::ConnectorChoice {
+ connector,
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ sub_label: None,
+ },
+ ))
+ })
+ }),
+ );
+ }
+ let card_in_node = builder
+ .make_in_aggregator(card_dir_values, None, None::<()>)
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ let card_and_node = builder
+ .make_all_aggregator(
+ &[
+ (
+ card_value_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ (
+ payment_type_value_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ (
+ card_in_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ ],
+ None,
+ None::<()>,
+ None,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ agg_nodes.push((
+ card_and_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ));
+ } else if let Some(connector_list) =
+ supported_pm_for_mandates.0.get(&pmt.payment_method_type)
+ {
+ non_card_dir_values.extend(
+ connector_list
+ .connector_list
+ .clone()
+ .into_iter()
+ .filter_map(|connector| {
+ api_enums::RoutableConnectors::from_str(connector.to_string().as_str())
+ .ok()
+ .map(|connector| {
+ dir::DirValue::Connector(Box::new(
+ api_models::routing::ast::ConnectorChoice {
+ connector,
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ sub_label: None,
+ },
+ ))
+ })
+ }),
+ );
+ let non_card_mandate_in_node = builder
+ .make_in_aggregator(non_card_dir_values, None, None::<()>)
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ let non_card_and_node = builder
+ .make_all_aggregator(
+ &[
+ (
+ card_value_node,
+ cgraph::Relation::Negative,
+ cgraph::Strength::Strong,
+ ),
+ (
+ payment_type_value_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ (
+ non_card_mandate_in_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ ],
+ None,
+ None::<()>,
+ None,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ agg_nodes.push((
+ non_card_and_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ));
+ }
+ }
+
+ Ok(Some(
+ builder
+ .make_any_aggregator(
+ &agg_nodes,
+ Some("any node for card and non card pm"),
+ None::<()>,
+ None,
+ )
+ .map_err(KgraphError::GraphConstructionError)?,
+ ))
+}
+
+fn construct_supported_connectors_for_mandate_node(
+ builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>,
+ eligible_connectors: Vec<api_enums::Connector>,
+) -> Result<Option<cgraph::NodeId>, KgraphError> {
+ let payment_type_value_node = builder.make_value_node(
+ cgraph::NodeValue::Value(dir::DirValue::PaymentType(
+ euclid::enums::PaymentType::NewMandate,
+ )),
+ None,
+ None::<()>,
+ );
+ let connectors_from_config: Vec<dir::DirValue> = eligible_connectors
+ .into_iter()
+ .filter_map(|connector| {
+ match api_enums::RoutableConnectors::from_str(connector.to_string().as_str()) {
+ Ok(connector) => Some(dir::DirValue::Connector(Box::new(
+ api_models::routing::ast::ConnectorChoice {
+ connector,
+ #[cfg(not(feature = "connector_choice_mca_id"))]
+ sub_label: None,
+ },
+ ))),
+ Err(_) => None,
+ }
+ })
+ .collect();
+
+ if connectors_from_config.is_empty() {
+ Ok(None)
+ } else {
+ let connector_in_aggregator = builder
+ .make_in_aggregator(connectors_from_config, None, None::<()>)
+ .map_err(KgraphError::GraphConstructionError)?;
+ Ok(Some(
+ builder
+ .make_all_aggregator(
+ &[
+ (
+ payment_type_value_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ (
+ connector_in_aggregator,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ ],
+ None,
+ None::<()>,
+ None,
+ )
+ .map_err(KgraphError::GraphConstructionError)?,
+ ))
+ }
+}
+
+// fn construct_card_network_nodes(
+// builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>,
+// mca_card_networks: Vec<api_enums::CardNetwork>,
+// ) -> Result<Option<cgraph::NodeId>, KgraphError> {
+// Ok(Some(
+// builder
+// .make_in_aggregator(
+// mca_card_networks
+// .into_iter()
+// .map(dir::DirValue::CardNetwork)
+// .collect(),
+// None,
+// None::<()>,
+// )
+// .map_err(KgraphError::GraphConstructionError)?,
+// ))
+// }
+
+fn compile_accepted_countries_for_mca(
+ builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>,
+ payment_method_type: &enums::PaymentMethodType,
+ pm_obj_countries: admin::AcceptedCountries,
+ config: &settings::ConnectorFilters,
+ connector: String,
+) -> Result<Option<cgraph::NodeId>, KgraphError> {
+ match pm_obj_countries {
+ admin::AcceptedCountries::EnableOnly(countries) => {
+ // Country from the MCA
+ let pm_object_country_value_node = builder
+ .make_in_aggregator(
+ countries
+ .into_iter()
+ .map(|country| {
+ dir::DirValue::BillingCountry(common_enums::Country::from_alpha2(
+ country,
+ ))
+ })
+ .collect(),
+ None,
+ None::<()>,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
+ if let Some(config) = config
+ .0
+ .get(connector.as_str())
+ .or_else(|| config.0.get("default"))
+ {
+ if let Some(value) =
+ config
+ .0
+ .get(&settings::PaymentMethodFilterKey::PaymentMethodType(
+ *payment_method_type,
+ ))
+ {
+ // country from config
+ if let Some(config_countries) = value.country.as_ref() {
+ let config_countries: Vec<common_enums::Country> =
+ Vec::from_iter(config_countries)
+ .into_iter()
+ .map(|country| common_enums::Country::from_alpha2(*country))
+ .collect();
+ let dir_countries: Vec<dir::DirValue> = config_countries
+ .into_iter()
+ .map(dir::DirValue::BillingCountry)
+ .collect();
+
+ let config_country_agg_node = builder
+ .make_in_aggregator(dir_countries, None, None::<()>)
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ let node = builder
+ .make_all_aggregator(
+ &[
+ (
+ pm_object_country_value_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ (
+ config_country_agg_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ ],
+ None,
+ None::<()>,
+ None,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
+ return Ok(Some(node));
+ }
+ }
+ }
+ }
+ admin::AcceptedCountries::DisableOnly(countries) => {
+ if let Some(config) = config
+ .0
+ .get(connector.as_str())
+ .or_else(|| config.0.get("default"))
+ {
+ // Country from the MCA
+ let pm_object_country_value_node = builder
+ .make_in_aggregator(
+ countries
+ .into_iter()
+ .map(|country| {
+ dir::DirValue::BillingCountry(common_enums::Country::from_alpha2(
+ country,
+ ))
+ })
+ .collect(),
+ None,
+ None::<()>,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ if let Some(value) =
+ config
+ .0
+ .get(&settings::PaymentMethodFilterKey::PaymentMethodType(
+ *payment_method_type,
+ ))
+ {
+ // country from config
+ if let Some(config_countries) = value.country.as_ref() {
+ let config_countries: Vec<common_enums::Country> =
+ Vec::from_iter(config_countries)
+ .into_iter()
+ .map(|country| common_enums::Country::from_alpha2(*country))
+ .collect();
+ let dir_countries: Vec<dir::DirValue> = config_countries
+ .into_iter()
+ .map(dir::DirValue::BillingCountry)
+ .collect();
+
+ let config_country_agg_node = builder
+ .make_in_aggregator(dir_countries, None, None::<()>)
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ let node = builder
+ .make_all_aggregator(
+ &[
+ (
+ pm_object_country_value_node,
+ cgraph::Relation::Negative,
+ cgraph::Strength::Strong,
+ ),
+ (
+ config_country_agg_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ ],
+ None,
+ None::<()>,
+ None,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
+ return Ok(Some(node));
+ }
+ }
+ }
+ }
+ admin::AcceptedCountries::AllAccepted => return Ok(None),
+ }
+ Ok(None)
+}
+
+fn compile_accepted_currency_for_mca(
+ builder: &mut cgraph::ConstraintGraphBuilder<'_, dir::DirValue>,
+ payment_method_type: &enums::PaymentMethodType,
+ pm_obj_currency: admin::AcceptedCurrencies,
+ config: &settings::ConnectorFilters,
+ connector: String,
+) -> Result<Option<cgraph::NodeId>, KgraphError> {
+ match pm_obj_currency {
+ admin::AcceptedCurrencies::EnableOnly(currency) => {
+ // Currency from the MCA
+ let pm_object_currency_value_node = builder
+ .make_in_aggregator(
+ currency
+ .into_iter()
+ .map(dir::DirValue::PaymentCurrency)
+ .collect(),
+ None,
+ None::<()>,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ if let Some(config) = config
+ .0
+ .get(connector.as_str())
+ .or_else(|| config.0.get("default"))
+ {
+ if let Some(value) =
+ config
+ .0
+ .get(&settings::PaymentMethodFilterKey::PaymentMethodType(
+ *payment_method_type,
+ ))
+ {
+ // Currency from config
+ if let Some(config_currencies) = value.currency.as_ref() {
+ let config_currency: Vec<common_enums::Currency> =
+ Vec::from_iter(config_currencies)
+ .into_iter()
+ .cloned()
+ .collect();
+
+ let dir_currencies: Vec<dir::DirValue> = config_currency
+ .into_iter()
+ .map(dir::DirValue::PaymentCurrency)
+ .collect();
+
+ let config_currency_agg_node = builder
+ .make_in_aggregator(dir_currencies, None, None::<()>)
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ let node = builder
+ .make_all_aggregator(
+ &[
+ (
+ pm_object_currency_value_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ (
+ config_currency_agg_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ ],
+ None,
+ None::<()>,
+ None,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
+ return Ok(Some(node));
+ }
+ }
+ }
+ }
+ admin::AcceptedCurrencies::DisableOnly(currency) => {
+ // Currency from the MCA
+ let pm_object_currency_value_node = builder
+ .make_in_aggregator(
+ currency
+ .into_iter()
+ .map(dir::DirValue::PaymentCurrency)
+ .collect(),
+ None,
+ None::<()>,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ if let Some(config) = config
+ .0
+ .get(connector.as_str())
+ .or_else(|| config.0.get("default"))
+ {
+ if let Some(value) =
+ config
+ .0
+ .get(&settings::PaymentMethodFilterKey::PaymentMethodType(
+ *payment_method_type,
+ ))
+ {
+ // Currency from config
+ if let Some(config_currencies) = value.currency.as_ref() {
+ let config_currency: Vec<common_enums::Currency> =
+ Vec::from_iter(config_currencies)
+ .into_iter()
+ .cloned()
+ .collect();
+
+ let dir_currencies: Vec<dir::DirValue> = config_currency
+ .into_iter()
+ .map(dir::DirValue::PaymentCurrency)
+ .collect();
+
+ let config_currency_agg_node = builder
+ .make_in_aggregator(dir_currencies, None, None::<()>)
+ .map_err(KgraphError::GraphConstructionError)?;
+
+ let node = builder
+ .make_all_aggregator(
+ &[
+ (
+ pm_object_currency_value_node,
+ cgraph::Relation::Negative,
+ cgraph::Strength::Strong,
+ ),
+ (
+ config_currency_agg_node,
+ cgraph::Relation::Positive,
+ cgraph::Strength::Strong,
+ ),
+ ],
+ None,
+ None::<()>,
+ None,
+ )
+ .map_err(KgraphError::GraphConstructionError)?;
+ return Ok(Some(node));
+ }
+ }
+ }
+ }
+ admin::AcceptedCurrencies::AllAccepted => return Ok(None),
+ }
+ Ok(None)
+}
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index 31d965c8cd6..72199c20e08 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -430,6 +430,9 @@ impl MerchantConnectorAccountInterface for Store {
cache::CacheKind::CGraph(
format!("cgraph_{}_{_profile_id}", _merchant_id).into(),
),
+ cache::CacheKind::PmFiltersCGraph(
+ format!("pm_filters_cgraph_{}_{_profile_id}", _merchant_id).into(),
+ ),
],
update_call,
)
@@ -487,6 +490,9 @@ impl MerchantConnectorAccountInterface for Store {
cache::CacheKind::CGraph(
format!("cgraph_{}_{_profile_id}", mca.merchant_id).into(),
),
+ cache::CacheKind::PmFiltersCGraph(
+ format!("pm_filters_cgraph_{}_{_profile_id}", mca.merchant_id).into(),
+ ),
],
delete_call,
)
diff --git a/crates/storage_impl/src/redis/cache.rs b/crates/storage_impl/src/redis/cache.rs
index 80a6847e376..edcbed21ad6 100644
--- a/crates/storage_impl/src/redis/cache.rs
+++ b/crates/storage_impl/src/redis/cache.rs
@@ -27,6 +27,9 @@ const ROUTING_CACHE_PREFIX: &str = "routing";
/// Prefix for kgraph cache key
const CGRAPH_CACHE_PREFIX: &str = "cgraph";
+/// Prefix for PM Filter cgraph cache key
+const PM_FILTERS_CGRAPH_CACHE_PREFIX: &str = "pm_filters_cgraph";
+
/// Prefix for all kinds of cache key
const ALL_CACHE_PREFIX: &str = "all_cache_kind";
@@ -54,6 +57,10 @@ pub static ROUTING_CACHE: Lazy<Cache> =
pub static CGRAPH_CACHE: Lazy<Cache> =
Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
+/// PM Filter CGraph Cache
+pub static PM_FILTERS_CGRAPH_CACHE: Lazy<Cache> =
+ Lazy::new(|| Cache::new(CACHE_TTL, CACHE_TTI, Some(MAX_CAPACITY)));
+
/// Trait which defines the behaviour of types that's gonna be stored in Cache
pub trait Cacheable: Any + Send + Sync + DynClone {
fn as_any(&self) -> &dyn Any;
@@ -64,6 +71,7 @@ pub enum CacheKind<'a> {
Accounts(Cow<'a, str>),
Routing(Cow<'a, str>),
CGraph(Cow<'a, str>),
+ PmFiltersCGraph(Cow<'a, str>),
All(Cow<'a, str>),
}
@@ -74,6 +82,7 @@ impl<'a> From<CacheKind<'a>> for RedisValue {
CacheKind::Accounts(s) => format!("{ACCOUNTS_CACHE_PREFIX},{s}"),
CacheKind::Routing(s) => format!("{ROUTING_CACHE_PREFIX},{s}"),
CacheKind::CGraph(s) => format!("{CGRAPH_CACHE_PREFIX},{s}"),
+ CacheKind::PmFiltersCGraph(s) => format!("{PM_FILTERS_CGRAPH_CACHE_PREFIX},{s}"),
CacheKind::All(s) => format!("{ALL_CACHE_PREFIX},{s}"),
};
Self::from_string(value)
@@ -93,6 +102,9 @@ impl<'a> TryFrom<RedisValue> for CacheKind<'a> {
CONFIG_CACHE_PREFIX => Ok(Self::Config(Cow::Owned(split.1.to_string()))),
ROUTING_CACHE_PREFIX => Ok(Self::Routing(Cow::Owned(split.1.to_string()))),
CGRAPH_CACHE_PREFIX => Ok(Self::CGraph(Cow::Owned(split.1.to_string()))),
+ PM_FILTERS_CGRAPH_CACHE_PREFIX => {
+ Ok(Self::PmFiltersCGraph(Cow::Owned(split.1.to_string())))
+ }
ALL_CACHE_PREFIX => Ok(Self::All(Cow::Owned(split.1.to_string()))),
_ => Err(validation_err.into()),
}
diff --git a/crates/storage_impl/src/redis/pub_sub.rs b/crates/storage_impl/src/redis/pub_sub.rs
index 9669e826663..e4ebaf471d4 100644
--- a/crates/storage_impl/src/redis/pub_sub.rs
+++ b/crates/storage_impl/src/redis/pub_sub.rs
@@ -2,7 +2,9 @@ use error_stack::ResultExt;
use redis_interface::{errors as redis_errors, PubsubInterface, RedisValue};
use router_env::logger;
-use crate::redis::cache::{CacheKind, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, ROUTING_CACHE};
+use crate::redis::cache::{
+ CacheKind, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE, PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE,
+};
#[async_trait::async_trait]
pub trait PubSubInterface {
@@ -71,6 +73,10 @@ impl PubSubInterface for redis_interface::RedisConnectionPool {
CGRAPH_CACHE.remove(key.as_ref()).await;
key
}
+ CacheKind::PmFiltersCGraph(key) => {
+ PM_FILTERS_CGRAPH_CACHE.remove(key.as_ref()).await;
+ key
+ }
CacheKind::Routing(key) => {
ROUTING_CACHE.remove(key.as_ref()).await;
key
@@ -79,6 +85,7 @@ impl PubSubInterface for redis_interface::RedisConnectionPool {
CONFIG_CACHE.remove(key.as_ref()).await;
ACCOUNTS_CACHE.remove(key.as_ref()).await;
CGRAPH_CACHE.remove(key.as_ref()).await;
+ PM_FILTERS_CGRAPH_CACHE.remove(key.as_ref()).await;
ROUTING_CACHE.remove(key.as_ref()).await;
key
}
|
refactor
|
Inclusion of constraint graph for merchant Payment Method list (#4626)
|
3d62cb07dd94d827b18e664a3454352f300575fe
|
2023-08-17 12:58:31
|
Arjun Karthik
|
fix(connector): [Payme] Fix for partial capture validation (#1939)
| false
|
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/router/src/connector/payme/transformers.rs
index 9799130415d..fd2121ac811 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/router/src/connector/payme/transformers.rs
@@ -551,6 +551,12 @@ pub struct PaymentCaptureRequest {
impl TryFrom<&types::PaymentsCaptureRouterData> for PaymentCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCaptureRouterData) -> Result<Self, Self::Error> {
+ if item.request.amount_to_capture != item.request.payment_amount {
+ Err(errors::ConnectorError::NotSupported {
+ message: "Partial Capture".to_string(),
+ connector: "Payme",
+ })?
+ }
Ok(Self {
payme_sale_id: item.request.connector_transaction_id.clone(),
sale_price: item.request.amount_to_capture,
|
fix
|
[Payme] Fix for partial capture validation (#1939)
|
a808c02501d652f017e1920a1e896d9106cf8dc7
|
2023-10-10 20:16:16
|
github-actions
|
chore(version): v1.55.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 86a9b01a683..9a3ef270b47 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,39 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.55.0 (2023-10-10)
+
+### Features
+
+- **connector:**
+ - [Multisafepay] Use connector_request_reference_id as reference to the connector ([#2503](https://github.com/juspay/hyperswitch/pull/2503)) ([`c34f1bf`](https://github.com/juspay/hyperswitch/commit/c34f1bf36ffb3a3533dd51ac87e7f66ab0dcce79))
+ - [GlobalPayments] Introduce connector_request_reference_id for GlobalPayments ([#2519](https://github.com/juspay/hyperswitch/pull/2519)) ([`116139b`](https://github.com/juspay/hyperswitch/commit/116139ba7ae6878b7018068b0cb8303a8e8d1f7a))
+ - [Airwallex] Use connector_request_reference_id as merchant reference id #2291 ([#2516](https://github.com/juspay/hyperswitch/pull/2516)) ([`6e89e41`](https://github.com/juspay/hyperswitch/commit/6e89e4103da4ecf6d7f06f7a9ec7da64eb493a6e))
+- **trace:** Add optional sampling behaviour for routes ([#2511](https://github.com/juspay/hyperswitch/pull/2511)) ([`ec51e48`](https://github.com/juspay/hyperswitch/commit/ec51e48402da63e1250328485095b8665d7eca65))
+- Gracefully shutdown drainer if redis goes down ([#2391](https://github.com/juspay/hyperswitch/pull/2391)) ([`2870af1`](https://github.com/juspay/hyperswitch/commit/2870af1286e897be0d40c014bc5742eafc6795db))
+- Kv for reverse lookup ([#2445](https://github.com/juspay/hyperswitch/pull/2445)) ([`13aaf96`](https://github.com/juspay/hyperswitch/commit/13aaf96db0f62dc7a706ba2ba230912ee7ef7a68))
+- Add x-hs-latency header for application overhead measurement ([#2486](https://github.com/juspay/hyperswitch/pull/2486)) ([`cf0db35`](https://github.com/juspay/hyperswitch/commit/cf0db35923d39caca9bf267b7d87a3f215884b66))
+
+### Bug Fixes
+
+- **connector:**
+ - [Airwallex] convert expiry year to four digit ([#2527](https://github.com/juspay/hyperswitch/pull/2527)) ([`4b0fa12`](https://github.com/juspay/hyperswitch/commit/4b0fa1295ca8f4e611b65fbf2458c38b89303d3b))
+ - [noon] add missing response status ([#2528](https://github.com/juspay/hyperswitch/pull/2528)) ([`808ee45`](https://github.com/juspay/hyperswitch/commit/808ee45556f90b1c1360a3edbffe9ba3603439d4))
+
+### Refactors
+
+- **payment_methods:** Added mca_id in bank details ([#2495](https://github.com/juspay/hyperswitch/pull/2495)) ([`ac3c500`](https://github.com/juspay/hyperswitch/commit/ac3c5008f80172a575f2fb08b7a5e78016ce7595))
+- **test_utils:** Refactor `test_utils` crate and add `folder` support with updated documentation ([#2487](https://github.com/juspay/hyperswitch/pull/2487)) ([`6b52ac3`](https://github.com/juspay/hyperswitch/commit/6b52ac3d398d5a180c1dc67c5b53702ad01a0773))
+
+### Miscellaneous Tasks
+
+- [GOCARDLESS] env changes for becs and sepa mandates ([#2535](https://github.com/juspay/hyperswitch/pull/2535)) ([`4f5a383`](https://github.com/juspay/hyperswitch/commit/4f5a383bab567a1b46b2d6990c0c23ed60f1201b))
+
+**Full Changelog:** [`v1.54.0...v1.55.0`](https://github.com/juspay/hyperswitch/compare/v1.54.0...v1.55.0)
+
+- - -
+
+
## 1.54.0 (2023-10-09)
### Features
|
chore
|
v1.55.0
|
241653bd69e3503241f7556d363c243292a4603d
|
2025-03-04 11:55:43
|
DEEPANSHU BANSAL
|
refactor(connector): [AUTHORIZEDOTNET,CHECKOUT,NOON,OPAYO,OPENNODE,PAYME,TRUSTPAY] Move to crate hyperswitch_connectors (#7235)
| false
|
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index bf815d5c2ca..6fa0d9e103e 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -1,6 +1,7 @@
pub mod aci;
pub mod airwallex;
pub mod amazonpay;
+pub mod authorizedotnet;
pub mod bambora;
pub mod bamboraapac;
pub mod bankofamerica;
@@ -11,6 +12,7 @@ pub mod boku;
pub mod braintree;
pub mod cashtocode;
pub mod chargebee;
+pub mod checkout;
pub mod coinbase;
pub mod coingate;
pub mod cryptopay;
@@ -42,10 +44,14 @@ pub mod multisafepay;
pub mod nexinets;
pub mod nexixpay;
pub mod nomupay;
+pub mod noon;
pub mod novalnet;
pub mod nuvei;
+pub mod opayo;
+pub mod opennode;
pub mod paybox;
pub mod payeezy;
+pub mod payme;
pub mod paystack;
pub mod payu;
pub mod placetopay;
@@ -60,6 +66,7 @@ pub mod stax;
pub mod stripebilling;
pub mod taxjar;
pub mod thunes;
+pub mod trustpay;
pub mod tsys;
pub mod unified_authentication_service;
pub mod volt;
@@ -71,21 +78,22 @@ pub mod zen;
pub mod zsl;
pub use self::{
- aci::Aci, airwallex::Airwallex, amazonpay::Amazonpay, bambora::Bambora,
- bamboraapac::Bamboraapac, bankofamerica::Bankofamerica, billwerk::Billwerk, bitpay::Bitpay,
- bluesnap::Bluesnap, boku::Boku, braintree::Braintree, cashtocode::Cashtocode,
- chargebee::Chargebee, coinbase::Coinbase, 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, getnet::Getnet,
- globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless, helcim::Helcim,
- iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, klarna::Klarna,
- mifinity::Mifinity, mollie::Mollie, moneris::Moneris, multisafepay::Multisafepay,
- nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay, novalnet::Novalnet, nuvei::Nuvei,
- paybox::Paybox, payeezy::Payeezy, paystack::Paystack, payu::Payu, placetopay::Placetopay,
+ aci::Aci, airwallex::Airwallex, amazonpay::Amazonpay, authorizedotnet::Authorizedotnet,
+ bambora::Bambora, bamboraapac::Bamboraapac, bankofamerica::Bankofamerica, billwerk::Billwerk,
+ bitpay::Bitpay, bluesnap::Bluesnap, boku::Boku, braintree::Braintree, cashtocode::Cashtocode,
+ chargebee::Chargebee, checkout::Checkout, coinbase::Coinbase, 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,
+ getnet::Getnet, globalpay::Globalpay, globepay::Globepay, gocardless::Gocardless,
+ helcim::Helcim, iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan,
+ klarna::Klarna, mifinity::Mifinity, mollie::Mollie, moneris::Moneris,
+ multisafepay::Multisafepay, nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay,
+ noon::Noon, novalnet::Novalnet, nuvei::Nuvei, opayo::Opayo, opennode::Opennode, paybox::Paybox,
+ payeezy::Payeezy, payme::Payme, paystack::Paystack, payu::Payu, placetopay::Placetopay,
powertranz::Powertranz, prophetpay::Prophetpay, rapyd::Rapyd, razorpay::Razorpay,
redsys::Redsys, shift4::Shift4, square::Square, stax::Stax, stripebilling::Stripebilling,
- taxjar::Taxjar, thunes::Thunes, tsys::Tsys,
+ taxjar::Taxjar, thunes::Thunes, trustpay::Trustpay, tsys::Tsys,
unified_authentication_service::UnifiedAuthenticationService, volt::Volt,
wellsfargo::Wellsfargo, worldline::Worldline, worldpay::Worldpay, xendit::Xendit, zen::Zen,
zsl::Zsl,
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs
similarity index 64%
rename from crates/router/src/connector/authorizedotnet.rs
rename to crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs
index afc8f063e4e..29af20a9570 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs
@@ -1,31 +1,60 @@
pub mod transformers;
use std::fmt::Debug;
-use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
-use diesel_models::enums;
+use common_enums::{enums, PaymentAction};
+use common_utils::{
+ crypto,
+ errors::CustomResult,
+ ext_traits::ByteSliceExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::ResultExt;
-use transformers as authorizedotnet;
-
-use crate::{
- configs::settings,
- connector::{
- utils as connector_utils,
- utils::{PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData},
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{AccessToken, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ CompleteAuthorize,
+ },
+ router_request_types::{
+ AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
+ PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
- consts,
- core::{
- errors::{self, CustomResult},
- payments,
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundsRouterData,
+ SetupMandateRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{
+ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
+ ConnectorValidation, MandateSetup,
},
+ configs::Connectors,
+ consts, errors,
events::connector_api_logs::ConnectorEvent,
- headers,
- services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt, PaymentsCompleteAuthorize},
- transformers::ForeignTryFrom,
+ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType,
+ PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response,
+ SetupMandateType,
+ },
+ webhooks,
+};
+use masking::Maskable;
+use transformers as authorizedotnet;
+
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{
+ self as connector_utils, ForeignTryFrom, PaymentMethodDataType,
+ PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
},
- utils::BytesExt,
};
#[derive(Debug, Clone)]
@@ -37,9 +66,9 @@ where
{
fn build_headers(
&self,
- _req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ _req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
Ok(vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
@@ -60,7 +89,7 @@ impl ConnectorCommon for Authorizedotnet {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.authorizedotnet.base_url.as_ref()
}
}
@@ -85,11 +114,10 @@ impl ConnectorValidation for Authorizedotnet {
fn validate_mandate_payment(
&self,
- pm_type: Option<types::storage::enums::PaymentMethodType>,
- pm_data: types::domain::payments::PaymentMethodData,
+ pm_type: Option<enums::PaymentMethodType>,
+ pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
- let mandate_supported_pmd =
- std::collections::HashSet::from([crate::connector::utils::PaymentMethodDataType::Card]);
+ let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]);
connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
@@ -103,42 +131,32 @@ impl api::PaymentSession for Authorizedotnet {}
impl api::ConnectorAccessToken for Authorizedotnet {}
impl api::PaymentToken for Authorizedotnet {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Authorizedotnet
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Authorizedotnet
{
// Not Implemented (R)
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Authorizedotnet
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Authorizedotnet {
// Not Implemented (R)
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
for Authorizedotnet
{
// Not Implemented (R)
}
-impl api::MandateSetup for Authorizedotnet {}
+impl MandateSetup for Authorizedotnet {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Authorizedotnet
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Authorizedotnet
{
fn get_headers(
&self,
- req: &types::SetupMandateRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &SetupMandateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
// This connector does not require an auth header, the authentication details are sent in the request body
self.build_headers(req, connectors)
}
@@ -147,15 +165,15 @@ impl
}
fn get_url(
&self,
- _req: &types::SetupMandateRouterData,
- connectors: &settings::Connectors,
+ _req: &SetupMandateRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
- req: &types::SetupMandateRouterData,
- _connectors: &settings::Connectors,
+ req: &SetupMandateRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = authorizedotnet::CreateCustomerProfileRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -163,28 +181,26 @@ impl
fn build_request(
&self,
- req: &types::SetupMandateRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<common_utils::request::Request>, errors::ConnectorError> {
+ req: &SetupMandateRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::SetupMandateType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::SetupMandateType::get_headers(self, req, connectors)?)
- .set_body(types::SetupMandateType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(SetupMandateType::get_headers(self, req, connectors)?)
+ .set_body(SetupMandateType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::SetupMandateRouterData,
+ data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::SetupMandateRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
@@ -199,7 +215,7 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -208,21 +224,19 @@ impl
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Authorizedotnet
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Authorizedotnet {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -232,15 +246,15 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- _req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from((
&self.get_currency_unit(),
@@ -256,18 +270,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
+ .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -276,10 +288,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
@@ -295,8 +307,8 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
+ RouterData::foreign_try_from((
+ ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -307,21 +319,19 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Authorizedotnet
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Authorizedotnet {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
// This connector does not require an auth header, the authentication details are sent in the request body
self.build_headers(req, connectors)
}
@@ -332,16 +342,16 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
- req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = authorizedotnet::AuthorizedotnetCreateSyncRequest::try_from(req)?;
@@ -350,27 +360,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
- .set_body(types::PaymentsSyncType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsSyncType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
@@ -384,7 +392,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -393,21 +401,21 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Authorizedotnet
{
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
// This connector does not require an auth header, the authentication details are sent in the request body
self.build_headers(req, connectors)
}
@@ -418,16 +426,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from((
&self.get_currency_unit(),
@@ -442,24 +450,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::RouterData<
- api::Authorize,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -468,10 +468,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
@@ -487,8 +487,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
+ RouterData::foreign_try_from((
+ ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -499,21 +499,19 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Authorizedotnet
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Authorizedotnet {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -523,16 +521,16 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- _req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
- req: &types::PaymentsCancelRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = authorizedotnet::CancelOrCaptureTransactionRequest::try_from(req)?;
@@ -540,28 +538,26 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&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,
- )?)
+ .headers(PaymentsVoidType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
@@ -575,7 +571,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -584,9 +580,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
@@ -595,14 +591,12 @@ impl api::Refund for Authorizedotnet {}
impl api::RefundExecute for Authorizedotnet {}
impl api::RefundSync for Authorizedotnet {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Authorizedotnet
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Authorizedotnet {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
// This connector does not require an auth header, the authentication details are sent in the request body
self.build_headers(req, connectors)
}
@@ -613,16 +607,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ _req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from((
&self.get_currency_unit(),
@@ -637,29 +631,25 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&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,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
@@ -673,7 +663,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -682,21 +672,19 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
- for Authorizedotnet
-{
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Authorizedotnet {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::RSync>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<RSync>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
// This connector does not require an auth header, the authentication details are sent in the request body
self.build_headers(req, connectors)
}
@@ -707,16 +695,16 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::RSync>,
- connectors: &settings::Connectors,
+ _req: &RefundsRouterData<RSync>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::RSync>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<RSync>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from((
&self.get_currency_unit(),
@@ -732,27 +720,25 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundsRouterData<api::RSync>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ req: &RefundsRouterData<RSync>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&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,
- )?)
+ .headers(RefundSyncType::get_headers(self, req, connectors)?)
+ .set_body(RefundSyncType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::RSync>,
+ data: &RefundsRouterData<RSync>,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::RefundsRouterData<api::RSync>, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<RefundsRouterData<RSync>, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
@@ -766,7 +752,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -775,27 +761,23 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
-impl PaymentsCompleteAuthorize for Authorizedotnet {}
+impl api::PaymentsCompleteAuthorize for Authorizedotnet {}
-impl
- ConnectorIntegration<
- api::CompleteAuthorize,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- > for Authorizedotnet
+impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
+ for Authorizedotnet
{
fn get_headers(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -805,15 +787,15 @@ impl
fn get_url(
&self,
- _req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCompleteAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = authorizedotnet::AuthorizedotnetRouterData::try_from((
&self.get_currency_unit(),
@@ -829,20 +811,20 @@ impl
fn build_request(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCompleteAuthorizeType::get_url(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
- .headers(types::PaymentsCompleteAuthorizeType::get_headers(
+ .headers(PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
- .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
+ .set_body(PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -851,10 +833,10 @@ impl
fn handle_response(
&self,
- data: &types::PaymentsCompleteAuthorizeRouterData,
+ data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
use bytes::Buf;
// Handle the case where response bytes contains U+FEFF (BOM) character sent by connector
@@ -868,8 +850,8 @@ impl
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
+ RouterData::foreign_try_from((
+ ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -880,25 +862,25 @@ impl
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
get_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Authorizedotnet {
+impl webhooks::IncomingWebhook for Authorizedotnet {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha512))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let security_header = request
@@ -920,7 +902,7 @@ impl api::IncomingWebhook for Authorizedotnet {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -929,7 +911,7 @@ impl api::IncomingWebhook for Authorizedotnet {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let details: authorizedotnet::AuthorizedotnetWebhookObjectId = request
.body
@@ -959,18 +941,20 @@ impl api::IncomingWebhook for Authorizedotnet {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let details: authorizedotnet::AuthorizedotnetWebhookEventType = request
.body
.parse_struct("AuthorizedotnetWebhookEventType")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
- Ok(api::IncomingWebhookEvent::from(details.event_type))
+ Ok(api_models::webhooks::IncomingWebhookEvent::from(
+ details.event_type,
+ ))
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let payload: authorizedotnet::AuthorizedotnetWebhookObjectId = request
.body
@@ -985,13 +969,13 @@ impl api::IncomingWebhook for Authorizedotnet {
#[inline]
fn get_error_response(
- types::Response {
+ Response {
response,
status_code,
..
- }: types::Response,
+ }: Response,
event_builder: Option<&mut ConnectorEvent>,
-) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: authorizedotnet::AuthorizedotnetPaymentsResponse = response
.parse_struct("AuthorizedotnetPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
@@ -1005,7 +989,7 @@ fn get_error_response(
)) => Ok(payment_response
.errors
.and_then(|errors| {
- errors.into_iter().next().map(|error| types::ErrorResponse {
+ errors.into_iter().next().map(|error| ErrorResponse {
code: error.error_code,
message: error.error_text.to_owned(),
reason: Some(error.error_text),
@@ -1014,7 +998,7 @@ fn get_error_response(
connector_transaction_id: None,
})
})
- .unwrap_or_else(|| types::ErrorResponse {
+ .unwrap_or_else(|| ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(), // authorizedotnet sends 200 in case of bad request so this are hard coded to NO_ERROR_CODE and NO_ERROR_MESSAGE
message: consts::NO_ERROR_MESSAGE.to_string(),
reason: None,
@@ -1030,7 +1014,7 @@ fn get_error_response(
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?
.text;
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(),
message: message.to_string(),
reason: Some(message.to_string()),
@@ -1042,18 +1026,18 @@ fn get_error_response(
}
}
-impl services::ConnectorRedirectResponse for Authorizedotnet {
+impl api::ConnectorRedirectResponse for Authorizedotnet {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
- action: services::PaymentAction,
- ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ action: PaymentAction,
+ ) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
match action {
- services::PaymentAction::PSync
- | services::PaymentAction::CompleteAuthorize
- | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
- Ok(payments::CallConnectorAction::Trigger)
+ PaymentAction::PSync
+ | PaymentAction::CompleteAuthorize
+ | PaymentAction::PaymentAuthenticateCompleteAuthorize => {
+ Ok(enums::CallConnectorAction::Trigger)
}
}
}
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
similarity index 83%
rename from crates/router/src/connector/authorizedotnet/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
index d48ead5d52e..626d6d76599 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
@@ -1,29 +1,39 @@
use std::collections::BTreeMap;
+use api_models::webhooks::IncomingWebhookEvent;
+use common_enums::enums;
use common_utils::{
errors::CustomResult,
- ext_traits::{Encode, ValueExt},
+ ext_traits::{Encode, OptionExt, ValueExt},
+ request::Method,
};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::{Card, PaymentMethodData, WalletData},
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::RSync,
+ router_request_types::ResponseId,
+ router_response_types::{
+ MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
+ },
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundsRouterData,
+ SetupMandateRouterData,
+ },
+};
+use hyperswitch_interfaces::{api, errors};
use masking::{ExposeInterface, PeekInterface, Secret, StrongSecret};
use rand::distributions::{Alphanumeric, DistString};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
- connector::utils::{
- self, CardData, PaymentsSyncRequestData, RefundsRequestData, RouterData, WalletData,
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{
+ self, CardData, ForeignTryFrom, PaymentsSyncRequestData, RefundsRequestData,
+ RouterData as OtherRouterData, WalletData as OtherWalletData,
},
- core::errors,
- services,
- types::{
- self,
- api::{self, enums as api_enums},
- domain,
- storage::enums,
- transformers::{ForeignFrom, ForeignTryFrom},
- },
- utils::OptionExt,
};
#[derive(Debug, Serialize)]
@@ -70,11 +80,11 @@ pub struct AuthorizedotnetAuthType {
transaction_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for AuthorizedotnetAuthType {
+impl TryFrom<&ConnectorAuthType> for AuthorizedotnetAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
name: api_key.to_owned(),
transaction_key: key1.to_owned(),
@@ -214,7 +224,7 @@ pub struct BillTo {
city: Option<String>,
state: Option<Secret<String>>,
zip: Option<Secret<String>>,
- country: Option<api_enums::CountryAlpha2>,
+ country: Option<enums::CountryAlpha2>,
}
#[derive(Debug, Serialize)]
@@ -336,11 +346,11 @@ impl ForeignTryFrom<Value> for Vec<UserField> {
}
}
-impl TryFrom<&types::SetupMandateRouterData> for CreateCustomerProfileRequest {
+impl TryFrom<&SetupMandateRouterData> for CreateCustomerProfileRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::SetupMandateRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &SetupMandateRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ccard) => {
+ PaymentMethodData::Card(ccard) => {
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.connector_auth_type)?;
let validation_mode = match item.test_mode {
@@ -366,24 +376,24 @@ impl TryFrom<&types::SetupMandateRouterData> for CreateCustomerProfileRequest {
},
})
}
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?
@@ -403,32 +413,21 @@ pub struct AuthorizedotnetSetupMandateResponse {
// zero dollar response
impl<F, T>
- TryFrom<
- types::ResponseRouterData<
- F,
- AuthorizedotnetSetupMandateResponse,
- T,
- types::PaymentsResponseData,
- >,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+ TryFrom<ResponseRouterData<F, AuthorizedotnetSetupMandateResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- AuthorizedotnetSetupMandateResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, AuthorizedotnetSetupMandateResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.messages.result_code {
ResultCode::Ok => Ok(Self {
status: enums::AttemptStatus::Charged,
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(item.response.customer_profile_id.map(
- |customer_profile_id| types::MandateReference {
+ |customer_profile_id| MandateReference {
connector_mandate_id:
item.response.customer_payment_profile_id_list.first().map(
|payment_profile_id| {
@@ -451,7 +450,7 @@ impl<F, T>
ResultCode::Error => {
let error_code = match item.response.messages.message.first() {
Some(first_error_message) => first_error_message.code.clone(),
- None => crate::consts::NO_ERROR_CODE.to_string(),
+ None => hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
};
let error_reason = item
.response
@@ -461,7 +460,7 @@ impl<F, T>
.map(|error: &ResponseMessage| error.text.clone())
.collect::<Vec<String>>()
.join(" ");
- let response = Err(types::ErrorResponse {
+ let response = Err(ErrorResponse {
code: error_code,
message: item.response.messages.result_code.to_string(),
reason: Some(error_reason),
@@ -515,12 +514,12 @@ impl TryFrom<enums::CaptureMethod> for AuthorizationType {
}
}
-impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
+impl TryFrom<&AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>>
for CreateTransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ item: &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let merchant_authentication =
AuthorizedotnetAuthType::try_from(&item.router_data.connector_auth_type)?;
@@ -551,29 +550,27 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
}
None => {
match &item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Card(ccard) => {
- TransactionRequest::try_from((item, ccard))
- }
- domain::PaymentMethodData::Wallet(wallet_data) => {
+ PaymentMethodData::Card(ccard) => TransactionRequest::try_from((item, ccard)),
+ PaymentMethodData::Wallet(wallet_data) => {
TransactionRequest::try_from((item, wallet_data))
}
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"authorizedotnet",
@@ -595,14 +592,14 @@ impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>>
impl
TryFrom<(
- &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
String,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, network_trans_id): (
- &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
String,
),
) -> Result<Self, Self::Error> {
@@ -611,31 +608,31 @@ impl
amount: item.amount,
currency_code: item.router_data.request.currency,
payment: Some(match item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Card(ref ccard) => {
+ PaymentMethodData::Card(ref ccard) => {
PaymentDetails::CreditCard(CreditCardDetails {
card_number: (*ccard.card_number).clone(),
expiration_date: ccard.get_expiry_date_as_yyyymm("-"),
card_code: None,
})
}
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?
@@ -684,14 +681,14 @@ impl
impl
TryFrom<(
- &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::ConnectorMandateReferenceId,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, connector_mandate_id): (
- &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
+ &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
api_models::payments::ConnectorMandateReferenceId,
),
) -> Result<Self, Self::Error> {
@@ -740,15 +737,15 @@ impl
impl
TryFrom<(
- &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
- &domain::Card,
+ &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
+ &Card,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, ccard): (
- &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
- &domain::Card,
+ &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
+ &Card,
),
) -> Result<Self, Self::Error> {
let (profile, customer) =
@@ -833,15 +830,15 @@ impl
impl
TryFrom<(
- &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
- &domain::WalletData,
+ &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
+ &WalletData,
)> for TransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, wallet_data): (
- &AuthorizedotnetRouterData<&types::PaymentsAuthorizeRouterData>,
- &domain::WalletData,
+ &AuthorizedotnetRouterData<&PaymentsAuthorizeRouterData>,
+ &WalletData,
),
) -> Result<Self, Self::Error> {
Ok(Self {
@@ -888,9 +885,9 @@ impl
}
}
-impl TryFrom<&types::PaymentsCancelRouterData> for CancelOrCaptureTransactionRequest {
+impl TryFrom<&PaymentsCancelRouterData> for CancelOrCaptureTransactionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let transaction_request = TransactionVoidOrCaptureRequest {
amount: None, //amount is not required for void
transaction_type: TransactionType::Void,
@@ -908,12 +905,12 @@ impl TryFrom<&types::PaymentsCancelRouterData> for CancelOrCaptureTransactionReq
}
}
-impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCaptureRouterData>>
+impl TryFrom<&AuthorizedotnetRouterData<&PaymentsCaptureRouterData>>
for CancelOrCaptureTransactionRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &AuthorizedotnetRouterData<&types::PaymentsCaptureRouterData>,
+ item: &AuthorizedotnetRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let transaction_request = TransactionVoidOrCaptureRequest {
amount: Some(item.amount),
@@ -964,22 +961,22 @@ pub enum AuthorizedotnetRefundStatus {
HeldForReview,
}
-impl ForeignFrom<(AuthorizedotnetPaymentStatus, bool)> for enums::AttemptStatus {
- fn foreign_from((item, auto_capture): (AuthorizedotnetPaymentStatus, bool)) -> Self {
- match item {
- AuthorizedotnetPaymentStatus::Approved => {
- if auto_capture {
- Self::Charged
- } else {
- Self::Authorized
- }
- }
- AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => {
- Self::Failure
+fn get_payment_status(
+ (item, auto_capture): (AuthorizedotnetPaymentStatus, bool),
+) -> enums::AttemptStatus {
+ match item {
+ AuthorizedotnetPaymentStatus::Approved => {
+ if auto_capture {
+ enums::AttemptStatus::Charged
+ } else {
+ enums::AttemptStatus::Authorized
}
- AuthorizedotnetPaymentStatus::RequiresAction => Self::AuthenticationPending,
- AuthorizedotnetPaymentStatus::HeldForReview => Self::Pending,
}
+ AuthorizedotnetPaymentStatus::Declined | AuthorizedotnetPaymentStatus::Error => {
+ enums::AttemptStatus::Failure
+ }
+ AuthorizedotnetPaymentStatus::RequiresAction => enums::AttemptStatus::AuthenticationPending,
+ AuthorizedotnetPaymentStatus::HeldForReview => enums::AttemptStatus::Pending,
}
}
@@ -1113,35 +1110,25 @@ impl From<AuthorizedotnetVoidStatus> for enums::AttemptStatus {
impl<F, T>
ForeignTryFrom<(
- types::ResponseRouterData<
- F,
- AuthorizedotnetPaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ ResponseRouterData<F, AuthorizedotnetPaymentsResponse, T, PaymentsResponseData>,
bool,
- )> for types::RouterData<F, T, types::PaymentsResponseData>
+ )> for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, is_auto_capture): (
- types::ResponseRouterData<
- F,
- AuthorizedotnetPaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ ResponseRouterData<F, AuthorizedotnetPaymentsResponse, T, PaymentsResponseData>,
bool,
),
) -> Result<Self, Self::Error> {
match &item.response.transaction_response {
Some(TransactionResponse::AuthorizedotnetTransactionResponse(transaction_response)) => {
- let status = enums::AttemptStatus::foreign_from((
+ let status = get_payment_status((
transaction_response.response_code.clone(),
is_auto_capture,
));
let error = transaction_response.errors.as_ref().and_then(|errors| {
- errors.iter().next().map(|error| types::ErrorResponse {
+ errors.iter().next().map(|error| ErrorResponse {
code: error.error_code.clone(),
message: error.error_text.clone(),
reason: Some(error.error_text.clone()),
@@ -1164,15 +1151,14 @@ impl<F, T>
.secure_acceptance
.as_ref()
.and_then(|x| x.secure_acceptance_url.to_owned());
- let redirection_data =
- url.map(|url| services::RedirectForm::from((url, services::Method::Get)));
+ let redirection_data = url.map(|url| RedirectForm::from((url, Method::Get)));
let mandate_reference = item.response.profile_response.map(|profile_response| {
let payment_profile_id = profile_response
.customer_payment_profile_id_list
.and_then(|customer_payment_profile_id_list| {
customer_payment_profile_id_list.first().cloned()
});
- types::MandateReference {
+ MandateReference {
connector_mandate_id: profile_response.customer_profile_id.and_then(
|customer_profile_id| {
payment_profile_id.map(|payment_profile_id| {
@@ -1190,8 +1176,8 @@ impl<F, T>
status,
response: match error {
Some(err) => Err(err),
- None => Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ None => Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
transaction_response.transaction_id.clone(),
),
redirection_data: Box::new(redirection_data),
@@ -1222,25 +1208,18 @@ impl<F, T>
}
}
-impl<F, T>
- TryFrom<
- types::ResponseRouterData<F, AuthorizedotnetVoidResponse, T, types::PaymentsResponseData>,
- > for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, AuthorizedotnetVoidResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- AuthorizedotnetVoidResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, AuthorizedotnetVoidResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match &item.response.transaction_response {
Some(transaction_response) => {
let status = enums::AttemptStatus::from(transaction_response.response_code.clone());
let error = transaction_response.errors.as_ref().and_then(|errors| {
- errors.iter().next().map(|error| types::ErrorResponse {
+ errors.iter().next().map(|error| ErrorResponse {
code: error.error_code.clone(),
message: error.error_text.clone(),
reason: Some(error.error_text.clone()),
@@ -1263,8 +1242,8 @@ impl<F, T>
status,
response: match error {
Some(err) => Err(err),
- None => Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ None => Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
transaction_response.transaction_id.clone(),
),
redirection_data: Box::new(None),
@@ -1318,10 +1297,10 @@ pub struct CreateRefundRequest {
create_transaction_request: AuthorizedotnetRefundRequest,
}
-impl<F> TryFrom<&AuthorizedotnetRouterData<&types::RefundsRouterData<F>>> for CreateRefundRequest {
+impl<F> TryFrom<&AuthorizedotnetRouterData<&RefundsRouterData<F>>> for CreateRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &AuthorizedotnetRouterData<&types::RefundsRouterData<F>>,
+ item: &AuthorizedotnetRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let payment_details = item
.router_data
@@ -1378,17 +1357,17 @@ pub struct AuthorizedotnetRefundResponse {
pub messages: ResponseMessages,
}
-impl<F> TryFrom<types::RefundsResponseRouterData<F, AuthorizedotnetRefundResponse>>
- for types::RefundsRouterData<F>
+impl<F> TryFrom<RefundsResponseRouterData<F, AuthorizedotnetRefundResponse>>
+ for RefundsRouterData<F>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<F, AuthorizedotnetRefundResponse>,
+ item: RefundsResponseRouterData<F, AuthorizedotnetRefundResponse>,
) -> Result<Self, Self::Error> {
let transaction_response = &item.response.transaction_response;
let refund_status = enums::RefundStatus::from(transaction_response.response_code.clone());
let error = transaction_response.errors.clone().and_then(|errors| {
- errors.first().map(|error| types::ErrorResponse {
+ errors.first().map(|error| ErrorResponse {
code: error.error_code.clone(),
message: error.error_text.clone(),
reason: Some(error.error_text.clone()),
@@ -1401,7 +1380,7 @@ impl<F> TryFrom<types::RefundsResponseRouterData<F, AuthorizedotnetRefundRespons
Ok(Self {
response: match error {
Some(err) => Err(err),
- None => Ok(types::RefundsResponseData {
+ None => Ok(RefundsResponseData {
connector_refund_id: transaction_response.transaction_id.clone(),
refund_status,
}),
@@ -1424,13 +1403,13 @@ pub struct AuthorizedotnetCreateSyncRequest {
get_transaction_details_request: TransactionDetails,
}
-impl<F> TryFrom<&AuthorizedotnetRouterData<&types::RefundsRouterData<F>>>
+impl<F> TryFrom<&AuthorizedotnetRouterData<&RefundsRouterData<F>>>
for AuthorizedotnetCreateSyncRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &AuthorizedotnetRouterData<&types::RefundsRouterData<F>>,
+ item: &AuthorizedotnetRouterData<&RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
let transaction_id = item.router_data.request.get_connector_refund_id()?;
let merchant_authentication =
@@ -1446,10 +1425,10 @@ impl<F> TryFrom<&AuthorizedotnetRouterData<&types::RefundsRouterData<F>>>
}
}
-impl TryFrom<&types::PaymentsSyncRouterData> for AuthorizedotnetCreateSyncRequest {
+impl TryFrom<&PaymentsSyncRouterData> for AuthorizedotnetCreateSyncRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let transaction_id = Some(
item.request
.get_connector_transaction_id()
@@ -1548,19 +1527,19 @@ impl From<RSyncStatus> for enums::RefundStatus {
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, AuthorizedotnetRSyncResponse>>
- for types::RefundsRouterData<api::RSync>
+impl TryFrom<RefundsResponseRouterData<RSync, AuthorizedotnetRSyncResponse>>
+ for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, AuthorizedotnetRSyncResponse>,
+ item: RefundsResponseRouterData<RSync, AuthorizedotnetRSyncResponse>,
) -> Result<Self, Self::Error> {
match item.response.transaction {
Some(transaction) => {
let refund_status = enums::RefundStatus::from(transaction.transaction_status);
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: transaction.transaction_id,
refund_status,
}),
@@ -1575,27 +1554,20 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, AuthorizedotnetRSyncRe
}
}
-impl<F, Req>
- TryFrom<
- types::ResponseRouterData<F, AuthorizedotnetSyncResponse, Req, types::PaymentsResponseData>,
- > for types::RouterData<F, Req, types::PaymentsResponseData>
+impl<F, Req> TryFrom<ResponseRouterData<F, AuthorizedotnetSyncResponse, Req, PaymentsResponseData>>
+ for RouterData<F, Req, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- AuthorizedotnetSyncResponse,
- Req,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, AuthorizedotnetSyncResponse, Req, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response.transaction {
Some(transaction) => {
let payment_status = enums::AttemptStatus::from(transaction.transaction_status);
Ok(Self {
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
transaction.transaction_id.clone(),
),
redirection_data: Box::new(None),
@@ -1667,12 +1639,12 @@ impl TryFrom<Option<enums::CaptureMethod>> for TransactionType {
fn get_err_response(
status_code: u16,
message: ResponseMessages,
-) -> Result<types::ErrorResponse, errors::ConnectorError> {
+) -> Result<ErrorResponse, errors::ConnectorError> {
let response_message = message
.message
.first()
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)?;
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
code: response_message.code.clone(),
message: response_message.text.clone(),
reason: Some(response_message.text.clone()),
@@ -1735,7 +1707,7 @@ pub enum AuthorizedotnetIncomingWebhookEventType {
Unknown,
}
-impl From<AuthorizedotnetIncomingWebhookEventType> for api::IncomingWebhookEvent {
+impl From<AuthorizedotnetIncomingWebhookEventType> for IncomingWebhookEvent {
fn from(event_type: AuthorizedotnetIncomingWebhookEventType) -> Self {
match event_type {
AuthorizedotnetIncomingWebhookEventType::AuthorizationCreated
@@ -1789,50 +1761,48 @@ impl TryFrom<AuthorizedotnetWebhookObjectId> for AuthorizedotnetSyncResponse {
}
fn get_wallet_data(
- wallet_data: &domain::WalletData,
+ wallet_data: &WalletData,
return_url: &Option<String>,
) -> CustomResult<PaymentDetails, errors::ConnectorError> {
match wallet_data {
- domain::WalletData::GooglePay(_) => Ok(PaymentDetails::OpaqueData(WalletDetails {
+ WalletData::GooglePay(_) => Ok(PaymentDetails::OpaqueData(WalletDetails {
data_descriptor: WalletMethod::Googlepay,
data_value: Secret::new(wallet_data.get_encoded_wallet_token()?),
})),
- domain::WalletData::ApplePay(applepay_token) => {
- Ok(PaymentDetails::OpaqueData(WalletDetails {
- data_descriptor: WalletMethod::Applepay,
- data_value: Secret::new(applepay_token.payment_data.clone()),
- }))
- }
- domain::WalletData::PaypalRedirect(_) => Ok(PaymentDetails::PayPal(PayPalDetails {
+ WalletData::ApplePay(applepay_token) => Ok(PaymentDetails::OpaqueData(WalletDetails {
+ data_descriptor: WalletMethod::Applepay,
+ data_value: Secret::new(applepay_token.payment_data.clone()),
+ })),
+ WalletData::PaypalRedirect(_) => Ok(PaymentDetails::PayPal(PayPalDetails {
success_url: return_url.to_owned(),
cancel_url: return_url.to_owned(),
})),
- domain::WalletData::AliPayQr(_)
- | domain::WalletData::AliPayRedirect(_)
- | domain::WalletData::AliPayHkRedirect(_)
- | domain::WalletData::AmazonPayRedirect(_)
- | domain::WalletData::MomoRedirect(_)
- | domain::WalletData::KakaoPayRedirect(_)
- | domain::WalletData::GoPayRedirect(_)
- | domain::WalletData::GcashRedirect(_)
- | domain::WalletData::ApplePayRedirect(_)
- | domain::WalletData::ApplePayThirdPartySdk(_)
- | domain::WalletData::DanaRedirect {}
- | domain::WalletData::GooglePayRedirect(_)
- | domain::WalletData::GooglePayThirdPartySdk(_)
- | domain::WalletData::MbWayRedirect(_)
- | domain::WalletData::MobilePayRedirect(_)
- | domain::WalletData::PaypalSdk(_)
- | domain::WalletData::Paze(_)
- | domain::WalletData::SamsungPay(_)
- | domain::WalletData::TwintRedirect {}
- | domain::WalletData::VippsRedirect {}
- | domain::WalletData::TouchNGoRedirect(_)
- | domain::WalletData::WeChatPayRedirect(_)
- | domain::WalletData::WeChatPayQr(_)
- | domain::WalletData::CashappQr(_)
- | domain::WalletData::SwishQr(_)
- | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
+ WalletData::AliPayQr(_)
+ | WalletData::AliPayRedirect(_)
+ | WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
+ | WalletData::MomoRedirect(_)
+ | WalletData::KakaoPayRedirect(_)
+ | WalletData::GoPayRedirect(_)
+ | WalletData::GcashRedirect(_)
+ | WalletData::ApplePayRedirect(_)
+ | WalletData::ApplePayThirdPartySdk(_)
+ | WalletData::DanaRedirect {}
+ | WalletData::GooglePayRedirect(_)
+ | WalletData::GooglePayThirdPartySdk(_)
+ | WalletData::MbWayRedirect(_)
+ | WalletData::MobilePayRedirect(_)
+ | WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
+ | WalletData::SamsungPay(_)
+ | WalletData::TwintRedirect {}
+ | WalletData::VippsRedirect {}
+ | WalletData::TouchNGoRedirect(_)
+ | WalletData::WeChatPayRedirect(_)
+ | WalletData::WeChatPayQr(_)
+ | WalletData::CashappQr(_)
+ | WalletData::SwishQr(_)
+ | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("authorizedotnet"),
))?,
}
@@ -1883,12 +1853,12 @@ pub struct PaypalQueryParams {
payer_id: Option<Secret<String>>,
}
-impl TryFrom<&AuthorizedotnetRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
+impl TryFrom<&AuthorizedotnetRouterData<&PaymentsCompleteAuthorizeRouterData>>
for PaypalConfirmRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &AuthorizedotnetRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
+ item: &AuthorizedotnetRouterData<&PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let params = item
.router_data
diff --git a/crates/router/src/connector/checkout.rs b/crates/hyperswitch_connectors/src/connectors/checkout.rs
similarity index 65%
rename from crates/router/src/connector/checkout.rs
rename to crates/hyperswitch_connectors/src/connectors/checkout.rs
index 96b30dc80f9..61977098476 100644
--- a/crates/router/src/connector/checkout.rs
+++ b/crates/hyperswitch_connectors/src/connectors/checkout.rs
@@ -1,39 +1,69 @@
pub mod transformers;
+use common_enums::{enums, CallConnectorAction, PaymentAction};
use common_utils::{
crypto,
+ errors::CustomResult,
ext_traits::ByteSliceExt,
- request::RequestContent,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
-use diesel_models::enums;
use error_stack::ResultExt;
-use masking::PeekInterface;
-
-use self::transformers as checkout;
-use super::utils::{
- self as conn_utils, ConnectorErrorType, ConnectorErrorTypeMapping, RefundsRequestData,
+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},
+ Accept, Defend, Evidence, Retrieve, Upload,
+ },
+ router_request_types::{
+ AcceptDisputeRequestData, AccessTokenRequestData, DefendDisputeRequestData,
+ PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
+ PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData,
+ RetrieveFileRequestData, SetupMandateRequestData, SubmitEvidenceRequestData,
+ SyncRequestType, UploadFileRequestData,
+ },
+ router_response_types::{
+ AcceptDisputeResponse, DefendDisputeResponse, PaymentsResponseData, RefundsResponseData,
+ RetrieveFileResponse, SubmitEvidenceResponse, UploadFileResponse,
+ },
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundsRouterData, TokenizationRouterData,
+ },
};
-use crate::{
- configs::settings,
- connector::utils as connector_utils,
- consts,
- core::{
- errors::{self, CustomResult},
- payments,
+use hyperswitch_interfaces::{
+ api::{
+ self,
+ disputes::{AcceptDispute, DefendDispute, Dispute, SubmitEvidence},
+ files::{FilePurpose, FileUpload, RetrieveFile, UploadFile},
+ CaptureSyncMethod, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration,
+ ConnectorSpecifications, ConnectorValidation, MandateSetup,
},
+ configs::Connectors,
+ consts,
+ disputes::DisputePayload,
+ errors,
events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
+ types::{
+ AcceptDisputeType, DefendDisputeType, PaymentsAuthorizeType, PaymentsCaptureType,
+ PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType, Response,
+ SubmitEvidenceType, TokenizationType, UploadFileType,
},
+ webhooks,
+};
+use masking::{Mask, Maskable, PeekInterface};
+use transformers::CheckoutErrorResponse;
+
+use self::transformers as checkout;
+use crate::{
+ constants::headers,
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
+ AcceptDisputeRouterData, DefendDisputeRouterData, ResponseRouterData,
+ SubmitEvidenceRouterData, UploadFileRouterData,
},
- utils::BytesExt,
+ utils::{self, ConnectorErrorType, RefundsRequestData},
};
#[derive(Clone)]
@@ -55,12 +85,12 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
+ PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)];
@@ -85,8 +115,8 @@ impl ConnectorCommon for Checkout {
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = checkout::CheckoutAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -95,15 +125,15 @@ impl ConnectorCommon for Checkout {
)])
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.checkout.base_url.as_ref()
}
fn build_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
- let response: checkout::ErrorResponse = if res.response.is_empty() {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: CheckoutErrorResponse = if res.response.is_empty() {
let (error_codes, error_type) = if res.status_code == 401 {
(
Some(vec!["Invalid api key".to_string()]),
@@ -112,7 +142,7 @@ impl ConnectorCommon for Checkout {
} else {
(None, None)
};
- checkout::ErrorResponse {
+ CheckoutErrorResponse {
request_id: None,
error_codes,
error_type,
@@ -127,14 +157,14 @@ impl ConnectorCommon for Checkout {
router_env::logger::info!(connector_response=?response);
let errors_list = response.error_codes.clone().unwrap_or_default();
- let option_error_code_message = conn_utils::get_error_code_error_message_based_on_priority(
+ let option_error_code_message = utils::get_error_code_error_message_based_on_priority(
self.clone(),
errors_list
.into_iter()
.map(|errors| errors.into())
.collect(),
);
- Ok(types::ErrorResponse {
+ Ok(ErrorResponse {
status_code: res.status_code,
code: option_error_code_message
.clone()
@@ -166,9 +196,10 @@ impl ConnectorValidation for Checkout {
| enums::CaptureMethod::SequentialAutomatic
| enums::CaptureMethod::Manual
| enums::CaptureMethod::ManualMultiple => Ok(()),
- enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_implemented_error_report(capture_method, self.id()),
- ),
+ enums::CaptureMethod::Scheduled => Err(utils::construct_not_implemented_error_report(
+ capture_method,
+ self.id(),
+ )),
}
}
}
@@ -181,24 +212,20 @@ impl api::PaymentVoid for Checkout {}
impl api::PaymentCapture for Checkout {}
impl api::PaymentSession for Checkout {}
impl api::ConnectorAccessToken for Checkout {}
-impl api::AcceptDispute for Checkout {}
+impl AcceptDispute for Checkout {}
impl api::PaymentToken for Checkout {}
-impl api::Dispute for Checkout {}
-impl api::RetrieveFile for Checkout {}
-impl api::DefendDispute for Checkout {}
-
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Checkout
+impl Dispute for Checkout {}
+impl RetrieveFile for Checkout {}
+impl DefendDispute for Checkout {}
+
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Checkout
{
fn get_headers(
&self,
- req: &types::TokenizationRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &TokenizationRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
@@ -219,16 +246,16 @@ impl
fn get_url(
&self,
- _req: &types::TokenizationRouterData,
- connectors: &settings::Connectors,
+ _req: &TokenizationRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}tokens", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::TokenizationRouterData,
- _connectors: &settings::Connectors,
+ req: &TokenizationRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = checkout::TokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -236,30 +263,28 @@ impl
fn build_request(
&self,
- req: &types::TokenizationRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &TokenizationRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::TokenizationType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::TokenizationType::get_headers(self, req, connectors)?)
- .set_body(types::TokenizationType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(TokenizationType::get_headers(self, req, connectors)?)
+ .set_body(TokenizationType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::TokenizationRouterData,
+ data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
+ res: Response,
+ ) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
where
- types::PaymentsResponseData: Clone,
+ PaymentsResponseData: Clone,
{
let response: checkout::CheckoutTokenResponse = res
.response
@@ -267,7 +292,7 @@ impl
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -277,44 +302,32 @@ impl
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Checkout
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Checkout {
// Not Implemented (R)
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Checkout
-{
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Checkout {
// Not Implemented (R)
}
-impl api::MandateSetup for Checkout {}
+impl MandateSetup for Checkout {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Checkout
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Checkout
{
// Issue: #173
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Checkout".to_string())
.into(),
@@ -322,21 +335,19 @@ impl
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Checkout
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Checkout {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.as_str();
Ok(format!(
@@ -346,10 +357,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
@@ -362,18 +373,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
+ .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -382,17 +391,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: checkout::PaymentCaptureResponse = res
.response
.parse_struct("CaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -402,32 +411,30 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Checkout
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Checkout {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let suffix = match req.request.sync_type {
- types::SyncRequestType::MultipleCaptureSync(_) => "/actions",
- types::SyncRequestType::SinglePaymentSync => "",
+ SyncRequestType::MultipleCaptureSync(_) => "/actions",
+ SyncRequestType::SinglePaymentSync => "",
};
Ok(format!(
"{}{}{}{}",
@@ -443,53 +450,53 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError>
+ res: Response,
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError>
where
- api::PSync: Clone,
- types::PaymentsSyncData: Clone,
- types::PaymentsResponseData: Clone,
+ PSync: Clone,
+ PaymentsSyncData: Clone,
+ PaymentsResponseData: Clone,
{
match &data.request.sync_type {
- types::SyncRequestType::MultipleCaptureSync(_) => {
+ SyncRequestType::MultipleCaptureSync(_) => {
let response: checkout::PaymentsResponseEnum = res
.response
.parse_struct("checkout::PaymentsResponseEnum")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
- types::SyncRequestType::SinglePaymentSync => {
+ SyncRequestType::SinglePaymentSync => {
let response: checkout::PaymentsResponse = res
.response
.parse_struct("PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -501,44 +508,42 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_multiple_capture_sync_method(
&self,
- ) -> CustomResult<services::CaptureSyncMethod, errors::ConnectorError> {
- Ok(services::CaptureSyncMethod::Bulk)
+ ) -> CustomResult<CaptureSyncMethod, errors::ConnectorError> {
+ Ok(CaptureSyncMethod::Bulk)
}
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Checkout
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Checkout {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "payments"))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
@@ -550,24 +555,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
fn build_request(
&self,
- req: &types::RouterData<
- api::Authorize,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- >,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -576,17 +573,17 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: checkout::PaymentsResponse = res
.response
.parse_struct("PaymentIntentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -596,28 +593,26 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Checkout
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Checkout {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}payments/{}/voids",
@@ -628,36 +623,34 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_request_body(
&self,
- req: &types::PaymentsCancelRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = checkout::PaymentVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&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,
- )?)
+ .headers(PaymentsVoidType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let mut response: checkout::PaymentVoidResponse = res
.response
.parse_struct("PaymentVoidResponse")
@@ -667,7 +660,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
response.status = res.status_code;
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -677,9 +670,9 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
@@ -688,14 +681,12 @@ impl api::Refund for Checkout {}
impl api::RefundExecute for Checkout {}
impl api::RefundSync for Checkout {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Checkout
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Checkout {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -705,8 +696,8 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -718,10 +709,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
@@ -734,29 +725,25 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&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,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: checkout::RefundResponse = res
.response
.parse_struct("checkout::RefundResponse")
@@ -767,7 +754,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
response,
status: res.status_code,
};
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -777,26 +764,26 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Checkout {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Checkout {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::RSync>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<RSync>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
- req: &types::RefundsRouterData<api::RSync>,
- connectors: &settings::Connectors,
+ req: &RefundsRouterData<RSync>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.clone();
Ok(format!(
@@ -808,25 +795,25 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundsRouterData<api::RSync>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundsRouterData<RSync>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::RSync>,
+ data: &RefundsRouterData<RSync>,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
- ) -> CustomResult<types::RefundsRouterData<api::RSync>, errors::ConnectorError> {
+ res: Response,
+ ) -> CustomResult<RefundsRouterData<RSync>, errors::ConnectorError> {
let refund_action_id = data.request.get_connector_refund_id()?;
let response: Vec<checkout::ActionResponse> = res
@@ -841,7 +828,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.iter()
.find(|&x| x.action_id.clone() == refund_action_id)
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -851,27 +838,22 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl
- ConnectorIntegration<api::Accept, types::AcceptDisputeRequestData, types::AcceptDisputeResponse>
- for Checkout
-{
+impl ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse> for Checkout {
fn get_headers(
&self,
- req: &types::AcceptDisputeRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &AcceptDisputeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
- types::AcceptDisputeType::get_content_type(self)
- .to_string()
- .into(),
+ AcceptDisputeType::get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
@@ -880,8 +862,8 @@ impl
fn get_url(
&self,
- req: &types::AcceptDisputeRouterData,
- connectors: &settings::Connectors,
+ req: &AcceptDisputeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}{}",
@@ -894,30 +876,28 @@ impl
fn build_request(
&self,
- req: &types::AcceptDisputeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &AcceptDisputeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::AcceptDisputeType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&AcceptDisputeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::AcceptDisputeType::get_headers(
- self, req, connectors,
- )?)
+ .headers(AcceptDisputeType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::AcceptDisputeRouterData,
+ data: &AcceptDisputeRouterData,
_event_builder: Option<&mut ConnectorEvent>,
- _res: types::Response,
- ) -> CustomResult<types::AcceptDisputeRouterData, errors::ConnectorError> {
- Ok(types::AcceptDisputeRouterData {
- response: Ok(types::AcceptDisputeResponse {
- dispute_status: api::enums::DisputeStatus::DisputeAccepted,
+ _res: Response,
+ ) -> CustomResult<AcceptDisputeRouterData, errors::ConnectorError> {
+ Ok(AcceptDisputeRouterData {
+ response: Ok(AcceptDisputeResponse {
+ dispute_status: enums::DisputeStatus::DisputeAccepted,
connector_status: None,
}),
..data.clone()
@@ -926,31 +906,27 @@ impl
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl api::UploadFile for Checkout {}
+impl UploadFile for Checkout {}
-impl
- ConnectorIntegration<api::Retrieve, types::RetrieveFileRequestData, types::RetrieveFileResponse>
- for Checkout
-{
-}
+impl ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse> for Checkout {}
#[async_trait::async_trait]
-impl api::FileUpload for Checkout {
+impl FileUpload for Checkout {
fn validate_file_upload(
&self,
- purpose: api::FilePurpose,
+ purpose: FilePurpose,
file_size: i32,
file_type: mime::Mime,
) -> CustomResult<(), errors::ConnectorError> {
match purpose {
- api::FilePurpose::DisputeEvidence => {
+ FilePurpose::DisputeEvidence => {
let supported_file_types =
["image/jpeg", "image/jpg", "image/png", "application/pdf"];
// 4 Megabytes (MB)
@@ -970,18 +946,12 @@ impl api::FileUpload for Checkout {
}
}
-impl ConnectorIntegration<api::Upload, types::UploadFileRequestData, types::UploadFileResponse>
- for Checkout
-{
+impl ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse> for Checkout {
fn get_headers(
&self,
- req: &types::RouterData<
- api::Upload,
- types::UploadFileRequestData,
- types::UploadFileResponse,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Upload, UploadFileRequestData, UploadFileResponse>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.get_auth_header(&req.connector_auth_type)
}
@@ -991,16 +961,16 @@ impl ConnectorIntegration<api::Upload, types::UploadFileRequestData, types::Uplo
fn get_url(
&self,
- _req: &types::UploadFileRouterData,
- connectors: &settings::Connectors,
+ _req: &UploadFileRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "files"))
}
fn get_request_body(
&self,
- req: &types::UploadFileRouterData,
- _connectors: &settings::Connectors,
+ req: &UploadFileRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = transformers::construct_file_upload_request(req.clone())?;
Ok(RequestContent::FormData(connector_req))
@@ -1008,29 +978,27 @@ impl ConnectorIntegration<api::Upload, types::UploadFileRequestData, types::Uplo
fn build_request(
&self,
- req: &types::UploadFileRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &UploadFileRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::UploadFileType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&UploadFileType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::UploadFileType::get_headers(self, req, connectors)?)
- .set_body(types::UploadFileType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(UploadFileType::get_headers(self, req, connectors)?)
+ .set_body(UploadFileType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::UploadFileRouterData,
+ data: &UploadFileRouterData,
event_builder: Option<&mut ConnectorEvent>,
- res: types::Response,
+ res: Response,
) -> CustomResult<
- types::RouterData<api::Upload, types::UploadFileRequestData, types::UploadFileResponse>,
+ RouterData<Upload, UploadFileRequestData, UploadFileResponse>,
errors::ConnectorError,
> {
let response: checkout::FileUploadResponse = res
@@ -1039,8 +1007,8 @@ impl ConnectorIntegration<api::Upload, types::UploadFileRequestData, types::Uplo
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- Ok(types::UploadFileRouterData {
- response: Ok(types::UploadFileResponse {
+ Ok(UploadFileRouterData {
+ response: Ok(UploadFileResponse {
provider_file_id: response.file_id,
}),
..data.clone()
@@ -1049,30 +1017,26 @@ impl ConnectorIntegration<api::Upload, types::UploadFileRequestData, types::Uplo
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl api::SubmitEvidence for Checkout {}
+impl SubmitEvidence for Checkout {}
-impl
- ConnectorIntegration<
- api::Evidence,
- types::SubmitEvidenceRequestData,
- types::SubmitEvidenceResponse,
- > for Checkout
+impl ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>
+ for Checkout
{
fn get_headers(
&self,
- req: &types::SubmitEvidenceRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &SubmitEvidenceRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
- types::SubmitEvidenceType::get_content_type(self)
+ SubmitEvidenceType::get_content_type(self)
.to_string()
.into(),
)];
@@ -1083,8 +1047,8 @@ impl
fn get_url(
&self,
- req: &types::SubmitEvidenceRouterData,
- connectors: &settings::Connectors,
+ req: &SubmitEvidenceRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}disputes/{}/evidence",
@@ -1095,8 +1059,8 @@ impl
fn get_request_body(
&self,
- req: &types::SubmitEvidenceRouterData,
- _connectors: &settings::Connectors,
+ req: &SubmitEvidenceRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = checkout::Evidence::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -1104,31 +1068,27 @@ impl
fn build_request(
&self,
- req: &types::SubmitEvidenceRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Put)
- .url(&types::SubmitEvidenceType::get_url(self, req, connectors)?)
+ req: &SubmitEvidenceRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Put)
+ .url(&SubmitEvidenceType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::SubmitEvidenceType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::SubmitEvidenceType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(SubmitEvidenceType::get_headers(self, req, connectors)?)
+ .set_body(SubmitEvidenceType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::SubmitEvidenceRouterData,
+ data: &SubmitEvidenceRouterData,
_event_builder: Option<&mut ConnectorEvent>,
- _res: types::Response,
- ) -> CustomResult<types::SubmitEvidenceRouterData, errors::ConnectorError> {
- Ok(types::SubmitEvidenceRouterData {
- response: Ok(types::SubmitEvidenceResponse {
+ _res: Response,
+ ) -> CustomResult<SubmitEvidenceRouterData, errors::ConnectorError> {
+ Ok(SubmitEvidenceRouterData {
+ response: Ok(SubmitEvidenceResponse {
dispute_status: api_models::enums::DisputeStatus::DisputeChallenged,
connector_status: None,
}),
@@ -1138,27 +1098,22 @@ impl
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
-impl
- ConnectorIntegration<api::Defend, types::DefendDisputeRequestData, types::DefendDisputeResponse>
- for Checkout
-{
+impl ConnectorIntegration<Defend, DefendDisputeRequestData, DefendDisputeResponse> for Checkout {
fn get_headers(
&self,
- req: &types::DefendDisputeRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &DefendDisputeRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
- types::DefendDisputeType::get_content_type(self)
- .to_string()
- .into(),
+ DefendDisputeType::get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
@@ -1167,8 +1122,8 @@ impl
fn get_url(
&self,
- req: &types::DefendDisputeRouterData,
- connectors: &settings::Connectors,
+ req: &DefendDisputeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}disputes/{}/evidence",
@@ -1179,30 +1134,28 @@ impl
fn build_request(
&self,
- req: &types::DefendDisputeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &DefendDisputeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::DefendDisputeType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&DefendDisputeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::DefendDisputeType::get_headers(
- self, req, connectors,
- )?)
+ .headers(DefendDisputeType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::DefendDisputeRouterData,
+ data: &DefendDisputeRouterData,
_event_builder: Option<&mut ConnectorEvent>,
- _res: types::Response,
- ) -> CustomResult<types::DefendDisputeRouterData, errors::ConnectorError> {
- Ok(types::DefendDisputeRouterData {
- response: Ok(types::DefendDisputeResponse {
- dispute_status: api::enums::DisputeStatus::DisputeChallenged,
+ _res: Response,
+ ) -> CustomResult<DefendDisputeRouterData, errors::ConnectorError> {
+ Ok(DefendDisputeRouterData {
+ response: Ok(DefendDisputeResponse {
+ dispute_status: enums::DisputeStatus::DisputeChallenged,
connector_status: None,
}),
..data.clone()
@@ -1211,33 +1164,33 @@ impl
fn get_error_response(
&self,
- res: types::Response,
+ res: Response,
event_builder: Option<&mut ConnectorEvent>,
- ) -> CustomResult<types::ErrorResponse, errors::ConnectorError> {
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Checkout {
+impl webhooks::IncomingWebhook for Checkout {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
- let signature = conn_utils::get_header_key_value("cko-signature", request.headers)
+ let signature = utils::get_header_key_value("cko-signature", request.headers)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
hex::decode(signature).change_context(errors::ConnectorError::WebhookSignatureNotFound)
}
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -1245,7 +1198,7 @@ impl api::IncomingWebhook for Checkout {
}
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let details: checkout::CheckoutWebhookBody = request
.body
@@ -1292,19 +1245,21 @@ impl api::IncomingWebhook for Checkout {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let details: checkout::CheckoutWebhookEventTypeBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
- Ok(api::IncomingWebhookEvent::from(details.transaction_type))
+ Ok(api_models::webhooks::IncomingWebhookEvent::from(
+ details.transaction_type,
+ ))
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let event_type_data: checkout::CheckoutWebhookEventTypeBody = request
.body
@@ -1326,13 +1281,13 @@ impl api::IncomingWebhook for Checkout {
fn get_dispute_details(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::disputes::DisputePayload, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<DisputePayload, errors::ConnectorError> {
let dispute_details: checkout::CheckoutDisputeWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
- Ok(api::disputes::DisputePayload {
+ Ok(DisputePayload {
amount: dispute_details.data.amount.to_string(),
currency: dispute_details.data.currency,
dispute_stage: api_models::enums::DisputeStage::from(
@@ -1349,24 +1304,24 @@ impl api::IncomingWebhook for Checkout {
}
}
-impl services::ConnectorRedirectResponse for Checkout {
+impl api::ConnectorRedirectResponse for Checkout {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
- action: services::PaymentAction,
- ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ action: PaymentAction,
+ ) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
match action {
- services::PaymentAction::PSync
- | services::PaymentAction::CompleteAuthorize
- | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
- Ok(payments::CallConnectorAction::Trigger)
+ PaymentAction::PSync
+ | PaymentAction::CompleteAuthorize
+ | PaymentAction::PaymentAuthenticateCompleteAuthorize => {
+ Ok(CallConnectorAction::Trigger)
}
}
}
}
-impl ConnectorErrorTypeMapping for Checkout {
+impl utils::ConnectorErrorTypeMapping for Checkout {
fn get_connector_error_type(
&self,
error_code: String,
diff --git a/crates/router/src/connector/checkout/transformers.rs b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
similarity index 71%
rename from crates/router/src/connector/checkout/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
index 4d9f5978b08..4630f00b1d5 100644
--- a/crates/router/src/connector/checkout/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
@@ -1,24 +1,39 @@
+use common_enums::enums::{self, AttemptStatus};
use common_utils::{
errors::{CustomResult, ParsingError},
ext_traits::ByteSliceExt,
+ request::Method,
types::MinorUnit,
};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::{PaymentMethodData, WalletData},
+ router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
+ router_flow_types::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsSyncRouterData, RefundsRouterData, TokenizationRouterData,
+ },
+};
+use hyperswitch_interfaces::{consts, errors, webhooks};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use url::Url;
use crate::{
- connector::utils::{
- self, to_connector_meta, ApplePayDecrypt, PaymentsCaptureRequestData, RouterData,
- WalletData,
+ types::{
+ PaymentsCancelResponseRouterData, PaymentsCaptureResponseRouterData,
+ PaymentsResponseRouterData, PaymentsSyncResponseRouterData, RefundsResponseRouterData,
+ ResponseRouterData, SubmitEvidenceRouterData, UploadFileRouterData,
},
- consts,
- core::errors,
- services,
- types::{self, api, domain, storage::enums, transformers::ForeignFrom},
unimplemented_payment_method,
+ utils::{
+ self, ApplePayDecrypt, PaymentsCaptureRequestData, RouterData as OtherRouterData,
+ WalletData as OtherWalletData,
+ },
};
#[derive(Debug, Serialize)]
@@ -75,70 +90,70 @@ pub struct CheckoutApplePayHeader {
transaction_id: Secret<String>,
}
-impl TryFrom<&types::TokenizationRouterData> for TokenRequest {
+impl TryFrom<&TokenizationRouterData> for TokenRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Wallet(wallet_data) => match wallet_data.clone() {
- domain::WalletData::GooglePay(_data) => {
+ PaymentMethodData::Wallet(wallet_data) => match wallet_data.clone() {
+ WalletData::GooglePay(_data) => {
let json_wallet_data: CheckoutGooglePayData =
wallet_data.get_wallet_token_as_json("Google Pay".to_string())?;
Ok(Self::Googlepay(json_wallet_data))
}
- domain::WalletData::ApplePay(_data) => {
+ WalletData::ApplePay(_data) => {
let json_wallet_data: CheckoutApplePayData =
wallet_data.get_wallet_token_as_json("Apple Pay".to_string())?;
Ok(Self::Applepay(json_wallet_data))
}
- domain::WalletData::AliPayQr(_)
- | domain::WalletData::AliPayRedirect(_)
- | domain::WalletData::AliPayHkRedirect(_)
- | domain::WalletData::AmazonPayRedirect(_)
- | domain::WalletData::MomoRedirect(_)
- | domain::WalletData::KakaoPayRedirect(_)
- | domain::WalletData::GoPayRedirect(_)
- | domain::WalletData::GcashRedirect(_)
- | domain::WalletData::ApplePayRedirect(_)
- | domain::WalletData::ApplePayThirdPartySdk(_)
- | domain::WalletData::DanaRedirect {}
- | domain::WalletData::GooglePayRedirect(_)
- | domain::WalletData::GooglePayThirdPartySdk(_)
- | domain::WalletData::MbWayRedirect(_)
- | domain::WalletData::MobilePayRedirect(_)
- | domain::WalletData::PaypalRedirect(_)
- | domain::WalletData::PaypalSdk(_)
- | domain::WalletData::Paze(_)
- | domain::WalletData::SamsungPay(_)
- | domain::WalletData::TwintRedirect {}
- | domain::WalletData::VippsRedirect {}
- | domain::WalletData::TouchNGoRedirect(_)
- | domain::WalletData::WeChatPayRedirect(_)
- | domain::WalletData::CashappQr(_)
- | domain::WalletData::SwishQr(_)
- | domain::WalletData::WeChatPayQr(_)
- | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
+ WalletData::AliPayQr(_)
+ | WalletData::AliPayRedirect(_)
+ | WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
+ | WalletData::MomoRedirect(_)
+ | WalletData::KakaoPayRedirect(_)
+ | WalletData::GoPayRedirect(_)
+ | WalletData::GcashRedirect(_)
+ | WalletData::ApplePayRedirect(_)
+ | WalletData::ApplePayThirdPartySdk(_)
+ | WalletData::DanaRedirect {}
+ | WalletData::GooglePayRedirect(_)
+ | WalletData::GooglePayThirdPartySdk(_)
+ | WalletData::MbWayRedirect(_)
+ | WalletData::MobilePayRedirect(_)
+ | WalletData::PaypalRedirect(_)
+ | WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
+ | WalletData::SamsungPay(_)
+ | WalletData::TwintRedirect {}
+ | WalletData::VippsRedirect {}
+ | WalletData::TouchNGoRedirect(_)
+ | WalletData::WeChatPayRedirect(_)
+ | WalletData::CashappQr(_)
+ | WalletData::SwishQr(_)
+ | WalletData::WeChatPayQr(_)
+ | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)
.into()),
},
- domain::PaymentMethodData::Card(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::Card(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)
@@ -153,16 +168,15 @@ pub struct CheckoutTokenResponse {
token: Secret<String>,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, CheckoutTokenResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, CheckoutTokenResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, CheckoutTokenResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, CheckoutTokenResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::PaymentsResponseData::TokenizationResponse {
+ response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.token.expose(),
}),
..item.data
@@ -262,10 +276,10 @@ pub struct CheckoutThreeDS {
version: Option<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for CheckoutAuthType {
+impl TryFrom<&ConnectorAuthType> for CheckoutAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::SignatureKey {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::SignatureKey {
api_key,
api_secret,
key1,
@@ -281,13 +295,13 @@ impl TryFrom<&types::ConnectorAuthType> for CheckoutAuthType {
}
}
}
-impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for PaymentsRequest {
+impl TryFrom<&CheckoutRouterData<&PaymentsAuthorizeRouterData>> for PaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &CheckoutRouterData<&types::PaymentsAuthorizeRouterData>,
+ item: &CheckoutRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let source_var = match item.router_data.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(ccard) => {
+ PaymentMethodData::Card(ccard) => {
let a = PaymentSource::Card(CardSource {
source_type: CheckoutSourceTypes::Card,
number: ccard.card_number.clone(),
@@ -297,32 +311,32 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
});
Ok(a)
}
- domain::PaymentMethodData::Wallet(wallet_data) => match wallet_data {
- domain::WalletData::GooglePay(_) => Ok(PaymentSource::Wallets(WalletSource {
+ PaymentMethodData::Wallet(wallet_data) => match wallet_data {
+ WalletData::GooglePay(_) => Ok(PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
token: match item.router_data.get_payment_method_token()? {
- types::PaymentMethodToken::Token(token) => token,
- types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
+ PaymentMethodToken::Token(token) => token,
+ PaymentMethodToken::ApplePayDecrypt(_) => Err(
unimplemented_payment_method!("Apple Pay", "Simplified", "Checkout"),
)?,
- types::PaymentMethodToken::PazeDecrypt(_) => {
+ PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Checkout"))?
}
- types::PaymentMethodToken::GooglePayDecrypt(_) => {
+ PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Checkout"))?
}
},
})),
- domain::WalletData::ApplePay(_) => {
+ WalletData::ApplePay(_) => {
let payment_method_token = item.router_data.get_payment_method_token()?;
match payment_method_token {
- types::PaymentMethodToken::Token(apple_pay_payment_token) => {
+ PaymentMethodToken::Token(apple_pay_payment_token) => {
Ok(PaymentSource::Wallets(WalletSource {
source_type: CheckoutSourceTypes::Token,
token: apple_pay_payment_token,
}))
}
- types::PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
+ PaymentMethodToken::ApplePayDecrypt(decrypt_data) => {
let exp_month = decrypt_data.get_expiry_month()?;
let expiry_year_4_digit = decrypt_data.get_four_digit_expiry_year()?;
Ok(PaymentSource::ApplePayPredecrypt(Box::new(
@@ -337,62 +351,62 @@ impl TryFrom<&CheckoutRouterData<&types::PaymentsAuthorizeRouterData>> for Payme
},
)))
}
- types::PaymentMethodToken::PazeDecrypt(_) => {
+ PaymentMethodToken::PazeDecrypt(_) => {
Err(unimplemented_payment_method!("Paze", "Checkout"))?
}
- types::PaymentMethodToken::GooglePayDecrypt(_) => {
+ PaymentMethodToken::GooglePayDecrypt(_) => {
Err(unimplemented_payment_method!("Google Pay", "Checkout"))?
}
}
}
- domain::WalletData::AliPayQr(_)
- | domain::WalletData::AliPayRedirect(_)
- | domain::WalletData::AliPayHkRedirect(_)
- | domain::WalletData::AmazonPayRedirect(_)
- | domain::WalletData::MomoRedirect(_)
- | domain::WalletData::KakaoPayRedirect(_)
- | domain::WalletData::GoPayRedirect(_)
- | domain::WalletData::GcashRedirect(_)
- | domain::WalletData::ApplePayRedirect(_)
- | domain::WalletData::ApplePayThirdPartySdk(_)
- | domain::WalletData::DanaRedirect {}
- | domain::WalletData::GooglePayRedirect(_)
- | domain::WalletData::GooglePayThirdPartySdk(_)
- | domain::WalletData::MbWayRedirect(_)
- | domain::WalletData::MobilePayRedirect(_)
- | domain::WalletData::PaypalRedirect(_)
- | domain::WalletData::PaypalSdk(_)
- | domain::WalletData::Paze(_)
- | domain::WalletData::SamsungPay(_)
- | domain::WalletData::TwintRedirect {}
- | domain::WalletData::VippsRedirect {}
- | domain::WalletData::TouchNGoRedirect(_)
- | domain::WalletData::WeChatPayRedirect(_)
- | domain::WalletData::CashappQr(_)
- | domain::WalletData::SwishQr(_)
- | domain::WalletData::WeChatPayQr(_)
- | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
+ WalletData::AliPayQr(_)
+ | WalletData::AliPayRedirect(_)
+ | WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
+ | WalletData::MomoRedirect(_)
+ | WalletData::KakaoPayRedirect(_)
+ | WalletData::GoPayRedirect(_)
+ | WalletData::GcashRedirect(_)
+ | WalletData::ApplePayRedirect(_)
+ | WalletData::ApplePayThirdPartySdk(_)
+ | WalletData::DanaRedirect {}
+ | WalletData::GooglePayRedirect(_)
+ | WalletData::GooglePayThirdPartySdk(_)
+ | WalletData::MbWayRedirect(_)
+ | WalletData::MobilePayRedirect(_)
+ | WalletData::PaypalRedirect(_)
+ | WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
+ | WalletData::SamsungPay(_)
+ | WalletData::TwintRedirect {}
+ | WalletData::VippsRedirect {}
+ | WalletData::TouchNGoRedirect(_)
+ | WalletData::WeChatPayRedirect(_)
+ | WalletData::CashappQr(_)
+ | WalletData::SwishQr(_)
+ | WalletData::WeChatPayQr(_)
+ | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
)),
},
- domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("checkout"),
))
@@ -520,91 +534,87 @@ impl TryFrom<CheckoutWebhookEventType> for CheckoutPaymentStatus {
}
}
-impl ForeignFrom<(CheckoutPaymentStatus, Option<enums::CaptureMethod>)> for enums::AttemptStatus {
- fn foreign_from(item: (CheckoutPaymentStatus, Option<enums::CaptureMethod>)) -> Self {
- let (status, capture_method) = item;
- match status {
- CheckoutPaymentStatus::Authorized => {
- if capture_method == Some(enums::CaptureMethod::Automatic)
- || capture_method.is_none()
- {
- Self::Pending
- } else {
- Self::Authorized
- }
+fn get_attempt_status_cap(
+ item: (CheckoutPaymentStatus, Option<enums::CaptureMethod>),
+) -> AttemptStatus {
+ let (status, capture_method) = item;
+ match status {
+ CheckoutPaymentStatus::Authorized => {
+ if capture_method == Some(enums::CaptureMethod::Automatic) || capture_method.is_none() {
+ AttemptStatus::Pending
+ } else {
+ AttemptStatus::Authorized
}
- CheckoutPaymentStatus::Captured
- | CheckoutPaymentStatus::PartiallyRefunded
- | CheckoutPaymentStatus::Refunded => Self::Charged,
- CheckoutPaymentStatus::PartiallyCaptured => Self::PartialCharged,
- CheckoutPaymentStatus::Declined
- | CheckoutPaymentStatus::Expired
- | CheckoutPaymentStatus::Canceled => Self::Failure,
- CheckoutPaymentStatus::Pending => Self::AuthenticationPending,
- CheckoutPaymentStatus::CardVerified | CheckoutPaymentStatus::RetryScheduled => {
- Self::Pending
- }
- CheckoutPaymentStatus::Voided => Self::Voided,
}
+ CheckoutPaymentStatus::Captured
+ | CheckoutPaymentStatus::PartiallyRefunded
+ | CheckoutPaymentStatus::Refunded => AttemptStatus::Charged,
+ CheckoutPaymentStatus::PartiallyCaptured => AttemptStatus::PartialCharged,
+ CheckoutPaymentStatus::Declined
+ | CheckoutPaymentStatus::Expired
+ | CheckoutPaymentStatus::Canceled => AttemptStatus::Failure,
+ CheckoutPaymentStatus::Pending => AttemptStatus::AuthenticationPending,
+ CheckoutPaymentStatus::CardVerified | CheckoutPaymentStatus::RetryScheduled => {
+ AttemptStatus::Pending
+ }
+ CheckoutPaymentStatus::Voided => AttemptStatus::Voided,
}
}
-impl ForeignFrom<(CheckoutPaymentStatus, CheckoutPaymentIntent)> for enums::AttemptStatus {
- fn foreign_from(item: (CheckoutPaymentStatus, CheckoutPaymentIntent)) -> Self {
- let (status, psync_flow) = item;
+fn get_attempt_status_intent(
+ item: (CheckoutPaymentStatus, CheckoutPaymentIntent),
+) -> AttemptStatus {
+ let (status, psync_flow) = item;
- match status {
- CheckoutPaymentStatus::Authorized => {
- if psync_flow == CheckoutPaymentIntent::Capture {
- Self::Pending
- } else {
- Self::Authorized
- }
- }
- CheckoutPaymentStatus::Captured
- | CheckoutPaymentStatus::PartiallyRefunded
- | CheckoutPaymentStatus::Refunded => Self::Charged,
- CheckoutPaymentStatus::PartiallyCaptured => Self::PartialCharged,
- CheckoutPaymentStatus::Declined
- | CheckoutPaymentStatus::Expired
- | CheckoutPaymentStatus::Canceled => Self::Failure,
- CheckoutPaymentStatus::Pending => Self::AuthenticationPending,
- CheckoutPaymentStatus::CardVerified | CheckoutPaymentStatus::RetryScheduled => {
- Self::Pending
+ match status {
+ CheckoutPaymentStatus::Authorized => {
+ if psync_flow == CheckoutPaymentIntent::Capture {
+ AttemptStatus::Pending
+ } else {
+ AttemptStatus::Authorized
}
- CheckoutPaymentStatus::Voided => Self::Voided,
}
+ CheckoutPaymentStatus::Captured
+ | CheckoutPaymentStatus::PartiallyRefunded
+ | CheckoutPaymentStatus::Refunded => AttemptStatus::Charged,
+ CheckoutPaymentStatus::PartiallyCaptured => AttemptStatus::PartialCharged,
+ CheckoutPaymentStatus::Declined
+ | CheckoutPaymentStatus::Expired
+ | CheckoutPaymentStatus::Canceled => AttemptStatus::Failure,
+ CheckoutPaymentStatus::Pending => AttemptStatus::AuthenticationPending,
+ CheckoutPaymentStatus::CardVerified | CheckoutPaymentStatus::RetryScheduled => {
+ AttemptStatus::Pending
+ }
+ CheckoutPaymentStatus::Voided => AttemptStatus::Voided,
}
}
-impl ForeignFrom<(CheckoutPaymentStatus, Option<Balances>)> for enums::AttemptStatus {
- fn foreign_from(item: (CheckoutPaymentStatus, Option<Balances>)) -> Self {
- let (status, balances) = item;
+fn get_attempt_status_bal(item: (CheckoutPaymentStatus, Option<Balances>)) -> AttemptStatus {
+ let (status, balances) = item;
- match status {
- CheckoutPaymentStatus::Authorized => {
- if let Some(Balances {
- available_to_capture: 0,
- }) = balances
- {
- Self::Charged
- } else {
- Self::Authorized
- }
+ match status {
+ CheckoutPaymentStatus::Authorized => {
+ if let Some(Balances {
+ available_to_capture: 0,
+ }) = balances
+ {
+ AttemptStatus::Charged
+ } else {
+ AttemptStatus::Authorized
}
- CheckoutPaymentStatus::Captured
- | CheckoutPaymentStatus::PartiallyRefunded
- | CheckoutPaymentStatus::Refunded => Self::Charged,
- CheckoutPaymentStatus::PartiallyCaptured => Self::PartialCharged,
- CheckoutPaymentStatus::Declined
- | CheckoutPaymentStatus::Expired
- | CheckoutPaymentStatus::Canceled => Self::Failure,
- CheckoutPaymentStatus::Pending => Self::AuthenticationPending,
- CheckoutPaymentStatus::CardVerified | CheckoutPaymentStatus::RetryScheduled => {
- Self::Pending
- }
- CheckoutPaymentStatus::Voided => Self::Voided,
}
+ CheckoutPaymentStatus::Captured
+ | CheckoutPaymentStatus::PartiallyRefunded
+ | CheckoutPaymentStatus::Refunded => AttemptStatus::Charged,
+ CheckoutPaymentStatus::PartiallyCaptured => AttemptStatus::PartialCharged,
+ CheckoutPaymentStatus::Declined
+ | CheckoutPaymentStatus::Expired
+ | CheckoutPaymentStatus::Canceled => AttemptStatus::Failure,
+ CheckoutPaymentStatus::Pending => AttemptStatus::AuthenticationPending,
+ CheckoutPaymentStatus::CardVerified | CheckoutPaymentStatus::RetryScheduled => {
+ AttemptStatus::Pending
+ }
+ CheckoutPaymentStatus::Voided => AttemptStatus::Voided,
}
}
@@ -667,25 +677,21 @@ fn get_connector_meta(
}
}
-impl TryFrom<types::PaymentsResponseRouterData<PaymentsResponse>>
- for types::PaymentsAuthorizeRouterData
-{
+impl TryFrom<PaymentsResponseRouterData<PaymentsResponse>> for PaymentsAuthorizeRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: types::PaymentsResponseRouterData<PaymentsResponse>,
- ) -> Result<Self, Self::Error> {
+ fn try_from(item: PaymentsResponseRouterData<PaymentsResponse>) -> Result<Self, Self::Error> {
let connector_meta =
get_connector_meta(item.data.request.capture_method.unwrap_or_default())?;
- let redirection_data = item.response.links.redirect.map(|href| {
- services::RedirectForm::from((href.redirection_url, services::Method::Get))
- });
- let status = enums::AttemptStatus::foreign_from((
- item.response.status,
- item.data.request.capture_method,
- ));
- let error_response = if status == enums::AttemptStatus::Failure {
- Some(types::ErrorResponse {
+ let redirection_data = item
+ .response
+ .links
+ .redirect
+ .map(|href| RedirectForm::from((href.redirection_url, Method::Get)));
+ let status =
+ get_attempt_status_cap((item.response.status, item.data.request.capture_method));
+ let error_response = if status == AttemptStatus::Failure {
+ Some(ErrorResponse {
status_code: item.http_code,
code: item
.response
@@ -703,8 +709,8 @@ impl TryFrom<types::PaymentsResponseRouterData<PaymentsResponse>>
} else {
None
};
- let payments_response_data = types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
+ let payments_response_data = PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
@@ -723,22 +729,21 @@ impl TryFrom<types::PaymentsResponseRouterData<PaymentsResponse>>
}
}
-impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponse>>
- for types::PaymentsSyncRouterData
-{
+impl TryFrom<PaymentsSyncResponseRouterData<PaymentsResponse>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::PaymentsSyncResponseRouterData<PaymentsResponse>,
+ item: PaymentsSyncResponseRouterData<PaymentsResponse>,
) -> Result<Self, Self::Error> {
- let redirection_data = item.response.links.redirect.map(|href| {
- services::RedirectForm::from((href.redirection_url, services::Method::Get))
- });
+ let redirection_data = item
+ .response
+ .links
+ .redirect
+ .map(|href| RedirectForm::from((href.redirection_url, Method::Get)));
let checkout_meta: CheckoutMeta =
- to_connector_meta(item.data.request.connector_meta.clone())?;
- let status =
- enums::AttemptStatus::foreign_from((item.response.status, checkout_meta.psync_flow));
- let error_response = if status == enums::AttemptStatus::Failure {
- Some(types::ErrorResponse {
+ utils::to_connector_meta(item.data.request.connector_meta.clone())?;
+ let status = get_attempt_status_intent((item.response.status, checkout_meta.psync_flow));
+ let error_response = if status == AttemptStatus::Failure {
+ Some(ErrorResponse {
status_code: item.http_code,
code: item
.response
@@ -756,8 +761,8 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponse>>
} else {
None
};
- let payments_response_data = types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.id.clone()),
+ let payments_response_data = PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(item.response.id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
@@ -776,13 +781,11 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponse>>
}
}
-impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponseEnum>>
- for types::PaymentsSyncRouterData
-{
+impl TryFrom<PaymentsSyncResponseRouterData<PaymentsResponseEnum>> for PaymentsSyncRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::PaymentsSyncResponseRouterData<PaymentsResponseEnum>,
+ item: PaymentsSyncResponseRouterData<PaymentsResponseEnum>,
) -> Result<Self, Self::Error> {
let capture_sync_response_list = match item.response {
PaymentsResponseEnum::PaymentResponse(payments_response) => {
@@ -795,7 +798,7 @@ impl TryFrom<types::PaymentsSyncResponseRouterData<PaymentsResponseEnum>>
}
};
Ok(Self {
- response: Ok(types::PaymentsResponseData::MultipleCaptureResponse {
+ response: Ok(PaymentsResponseData::MultipleCaptureResponse {
capture_sync_response_list,
}),
..item.data
@@ -815,7 +818,7 @@ pub struct PaymentVoidResponse {
reference: String,
}
-impl From<&PaymentVoidResponse> for enums::AttemptStatus {
+impl From<&PaymentVoidResponse> for AttemptStatus {
fn from(item: &PaymentVoidResponse) -> Self {
if item.status == 202 {
Self::Voided
@@ -825,17 +828,15 @@ impl From<&PaymentVoidResponse> for enums::AttemptStatus {
}
}
-impl TryFrom<types::PaymentsCancelResponseRouterData<PaymentVoidResponse>>
- for types::PaymentsCancelRouterData
-{
+impl TryFrom<PaymentsCancelResponseRouterData<PaymentVoidResponse>> for PaymentsCancelRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::PaymentsCancelResponseRouterData<PaymentVoidResponse>,
+ item: PaymentsCancelResponseRouterData<PaymentVoidResponse>,
) -> Result<Self, Self::Error> {
let response = &item.response;
Ok(Self {
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(response.action_id.clone()),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(response.action_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
@@ -850,9 +851,9 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<PaymentVoidResponse>>
}
}
-impl TryFrom<&types::PaymentsCancelRouterData> for PaymentVoidRequest {
+impl TryFrom<&PaymentsCancelRouterData> for PaymentVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
Ok(Self {
reference: item.request.connector_transaction_id.clone(),
})
@@ -873,10 +874,10 @@ pub struct PaymentCaptureRequest {
pub reference: Option<String>,
}
-impl TryFrom<&CheckoutRouterData<&types::PaymentsCaptureRouterData>> for PaymentCaptureRequest {
+impl TryFrom<&CheckoutRouterData<&PaymentsCaptureRouterData>> for PaymentCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &CheckoutRouterData<&types::PaymentsCaptureRouterData>,
+ item: &CheckoutRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let connector_auth = &item.router_data.connector_auth_type;
let auth_type: CheckoutAuthType = connector_auth.try_into()?;
@@ -907,23 +908,23 @@ pub struct PaymentCaptureResponse {
pub reference: Option<String>,
}
-impl TryFrom<types::PaymentsCaptureResponseRouterData<PaymentCaptureResponse>>
- for types::PaymentsCaptureRouterData
+impl TryFrom<PaymentsCaptureResponseRouterData<PaymentCaptureResponse>>
+ for PaymentsCaptureRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::PaymentsCaptureResponseRouterData<PaymentCaptureResponse>,
+ item: PaymentsCaptureResponseRouterData<PaymentCaptureResponse>,
) -> Result<Self, Self::Error> {
let connector_meta = serde_json::json!(CheckoutMeta {
psync_flow: CheckoutPaymentIntent::Capture,
});
let (status, amount_captured) = if item.http_code == 202 {
(
- enums::AttemptStatus::Charged,
+ AttemptStatus::Charged,
Some(item.data.request.amount_to_capture),
)
} else {
- (enums::AttemptStatus::Pending, None)
+ (AttemptStatus::Pending, None)
};
// if multiple capture request, return capture action_id so that it will be updated in the captures table.
@@ -935,8 +936,8 @@ impl TryFrom<types::PaymentsCaptureResponseRouterData<PaymentCaptureResponse>>
};
Ok(Self {
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(resource_id),
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(resource_id),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: Some(connector_meta),
@@ -958,11 +959,9 @@ pub struct RefundRequest {
reference: String,
}
-impl<F> TryFrom<&CheckoutRouterData<&types::RefundsRouterData<F>>> for RefundRequest {
+impl<F> TryFrom<&CheckoutRouterData<&RefundsRouterData<F>>> for RefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &CheckoutRouterData<&types::RefundsRouterData<F>>,
- ) -> Result<Self, Self::Error> {
+ fn try_from(item: &CheckoutRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let reference = item.router_data.request.refund_id.clone();
Ok(Self {
amount: Some(item.amount.to_owned()),
@@ -993,16 +992,16 @@ impl From<&CheckoutRefundResponse> for enums::RefundStatus {
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, CheckoutRefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, CheckoutRefundResponse>>
+ for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, CheckoutRefundResponse>,
+ item: RefundsResponseRouterData<Execute, CheckoutRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(&item.response);
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.response.action_id.clone(),
refund_status,
}),
@@ -1011,16 +1010,16 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, CheckoutRefundRespon
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, CheckoutRefundResponse>>
- for types::RefundsRouterData<api::RSync>
+impl TryFrom<RefundsResponseRouterData<RSync, CheckoutRefundResponse>>
+ for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, CheckoutRefundResponse>,
+ item: RefundsResponseRouterData<RSync, CheckoutRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(&item.response);
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.response.action_id.clone(),
refund_status,
}),
@@ -1030,7 +1029,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, CheckoutRefundResponse
}
#[derive(Debug, Default, Eq, PartialEq, Deserialize, Serialize)]
-pub struct ErrorResponse {
+pub struct CheckoutErrorResponse {
pub request_id: Option<String>,
pub error_type: Option<String>,
pub error_codes: Option<Vec<String>>,
@@ -1074,11 +1073,11 @@ impl utils::MultipleCaptureSyncResponse for ActionResponse {
self.action_id.clone()
}
- fn get_capture_attempt_status(&self) -> enums::AttemptStatus {
+ fn get_capture_attempt_status(&self) -> AttemptStatus {
match self.approved {
- Some(true) => enums::AttemptStatus::Charged,
- Some(false) => enums::AttemptStatus::Failure,
- None => enums::AttemptStatus::Pending,
+ Some(true) => AttemptStatus::Charged,
+ Some(false) => AttemptStatus::Failure,
+ None => AttemptStatus::Pending,
}
}
@@ -1100,8 +1099,8 @@ impl utils::MultipleCaptureSyncResponse for Box<PaymentsResponse> {
self.action_id.clone().unwrap_or("".into())
}
- fn get_capture_attempt_status(&self) -> enums::AttemptStatus {
- enums::AttemptStatus::foreign_from((self.status.clone(), self.balances.clone()))
+ fn get_capture_attempt_status(&self) -> AttemptStatus {
+ get_attempt_status_bal((self.status.clone(), self.balances.clone()))
}
fn get_connector_reference_id(&self) -> Option<String> {
@@ -1130,16 +1129,14 @@ pub struct CheckoutRedirectResponse {
pub cko_session_id: Option<String>,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, &ActionResponse>>
- for types::RefundsRouterData<api::Execute>
-{
+impl TryFrom<RefundsResponseRouterData<Execute, &ActionResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, &ActionResponse>,
+ item: RefundsResponseRouterData<Execute, &ActionResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response);
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.action_id.clone(),
refund_status,
}),
@@ -1148,16 +1145,14 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, &ActionResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, &ActionResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, &ActionResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, &ActionResponse>,
+ item: RefundsResponseRouterData<RSync, &ActionResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response);
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.action_id.clone(),
refund_status,
}),
@@ -1166,7 +1161,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, &ActionResponse>>
}
}
-impl From<CheckoutRedirectResponseStatus> for enums::AttemptStatus {
+impl From<CheckoutRedirectResponseStatus> for AttemptStatus {
fn from(item: CheckoutRedirectResponseStatus) -> Self {
match item {
CheckoutRedirectResponseStatus::Success => Self::AuthenticationSuccessful,
@@ -1298,7 +1293,7 @@ pub enum CheckoutDisputeTransactionType {
DisputeLost,
}
-impl From<CheckoutWebhookEventType> for api::IncomingWebhookEvent {
+impl From<CheckoutWebhookEventType> for api_models::webhooks::IncomingWebhookEvent {
fn from(transaction_type: CheckoutWebhookEventType) -> Self {
match transaction_type {
CheckoutWebhookEventType::AuthenticationStarted
@@ -1359,7 +1354,7 @@ pub struct CheckoutWebhookObjectResource {
}
pub fn construct_file_upload_request(
- file_upload_router_data: types::UploadFileRouterData,
+ file_upload_router_data: UploadFileRouterData,
) -> CustomResult<reqwest::multipart::Form, errors::ConnectorError> {
let request = file_upload_router_data.request;
let mut multipart = reqwest::multipart::Form::new();
@@ -1399,10 +1394,12 @@ pub struct Evidence {
pub additional_evidence_file: Option<String>,
}
-impl TryFrom<&api::IncomingWebhookRequestDetails<'_>> for PaymentsResponse {
+impl TryFrom<&webhooks::IncomingWebhookRequestDetails<'_>> for PaymentsResponse {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(request: &api::IncomingWebhookRequestDetails<'_>) -> Result<Self, Self::Error> {
+ fn try_from(
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> Result<Self, Self::Error> {
let details: CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
@@ -1427,10 +1424,12 @@ impl TryFrom<&api::IncomingWebhookRequestDetails<'_>> for PaymentsResponse {
}
}
-impl TryFrom<&api::IncomingWebhookRequestDetails<'_>> for RefundResponse {
+impl TryFrom<&webhooks::IncomingWebhookRequestDetails<'_>> for RefundResponse {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(request: &api::IncomingWebhookRequestDetails<'_>) -> Result<Self, Self::Error> {
+ fn try_from(
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> Result<Self, Self::Error> {
let details: CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
@@ -1449,9 +1448,9 @@ impl TryFrom<&api::IncomingWebhookRequestDetails<'_>> for RefundResponse {
}
}
-impl TryFrom<&types::SubmitEvidenceRouterData> for Evidence {
+impl TryFrom<&SubmitEvidenceRouterData> for Evidence {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::SubmitEvidenceRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &SubmitEvidenceRouterData) -> Result<Self, Self::Error> {
let submit_evidence_request_data = item.request.clone();
Ok(Self {
proof_of_delivery_or_service_file: submit_evidence_request_data
diff --git a/crates/router/src/connector/noon.rs b/crates/hyperswitch_connectors/src/connectors/noon.rs
similarity index 64%
rename from crates/router/src/connector/noon.rs
rename to crates/hyperswitch_connectors/src/connectors/noon.rs
index c8780af3ce5..c4f2eef275d 100644
--- a/crates/router/src/connector/noon.rs
+++ b/crates/hyperswitch_connectors/src/connectors/noon.rs
@@ -1,40 +1,58 @@
pub mod transformers;
+use api_models::webhooks::{ConnectorWebhookSecrets, IncomingWebhookEvent, ObjectReferenceId};
use base64::Engine;
+use common_enums::enums;
use common_utils::{
crypto,
+ errors::CustomResult,
ext_traits::ByteSliceExt,
- request::RequestContent,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
-use diesel_models::enums;
use error_stack::{Report, ResultExt};
-use masking::PeekInterface;
-use router_env::logger;
-use transformers as noon;
-
-use crate::{
- configs::settings,
- connector::utils::{self as connector_utils, PaymentMethodDataType},
- consts,
- core::{
- errors::{self, CustomResult},
- mandate::MandateBehaviour,
- payments,
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ mandate_revoke::MandateRevoke,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
+ router_request_types::{
+ AccessTokenRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
+ PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
+ router_response_types::{MandateRevokeResponseData, PaymentsResponseData, RefundsResponseData},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
+ PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
- utils::{self, BytesExt},
+};
+use hyperswitch_interfaces::{
+ api::{
+ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
+ ConnectorValidation,
+ },
+ configs::Connectors,
+ errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{
+ MandateRevokeType, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType,
+ PaymentsVoidType, RefundExecuteType, RefundSyncType, Response,
+ },
+ webhooks,
+};
+use masking::{Mask, PeekInterface};
+use router_env::logger;
+use transformers as noon;
+
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self as connector_utils, PaymentMethodDataType},
};
#[derive(Clone)]
@@ -64,12 +82,8 @@ impl api::RefundSync for Noon {}
impl api::PaymentToken for Noon {}
impl api::ConnectorMandateRevoke for Noon {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Noon
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Noon
{
// Not Implemented (R)
}
@@ -80,12 +94,12 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
+ PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)];
@@ -96,10 +110,10 @@ where
}
fn get_auth_header(
- auth_type: &types::ConnectorAuthType,
- connectors: &settings::Connectors,
+ auth_type: &ConnectorAuthType,
+ connectors: &Connectors,
test_mode: Option<bool>,
-) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = noon::NoonAuthType::try_from(auth_type)?;
let encoded_api_key = auth
@@ -107,7 +121,7 @@ fn get_auth_header(
.zip(auth.application_identifier)
.zip(auth.api_key)
.map(|((business_identifier, application_identifier), api_key)| {
- consts::BASE64_ENGINE.encode(format!(
+ common_utils::consts::BASE64_ENGINE.encode(format!(
"{}.{}:{}",
business_identifier, application_identifier, api_key
))
@@ -135,7 +149,7 @@ impl ConnectorCommon for Noon {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.noon.base_url.as_ref()
}
@@ -169,7 +183,7 @@ impl ConnectorCommon for Noon {
Err(error_message) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
logger::error!(deserialization_error =? error_message);
- utils::handle_json_response_deserialization_failure(res, "noon")
+ connector_utils::handle_json_response_deserialization_failure(res, "noon")
}
}
}
@@ -195,8 +209,8 @@ impl ConnectorValidation for Noon {
fn validate_mandate_payment(
&self,
- pm_type: Option<types::storage::enums::PaymentMethodType>,
- pm_data: types::domain::payments::PaymentMethodData,
+ pm_type: Option<enums::PaymentMethodType>,
+ pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
@@ -208,7 +222,7 @@ impl ConnectorValidation for Noon {
fn validate_psync_reference_id(
&self,
- _data: &hyperswitch_domain_models::router_request_types::PaymentsSyncData,
+ _data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
@@ -218,33 +232,18 @@ impl ConnectorValidation for Noon {
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Noon
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Noon {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Noon
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Noon {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Noon
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Noon {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Noon".to_string())
.into(),
@@ -252,14 +251,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Noon
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Noon {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -269,16 +266,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payment/v1/order", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
@@ -287,7 +284,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
)?;
let mandate_details =
- connector_utils::get_mandate_details(req.request.get_setup_mandate_details())?;
+ connector_utils::get_mandate_details(req.request.setup_mandate_details.clone())?;
let mandate_amount = mandate_details
.map(|mandate| {
connector_utils::convert_amount(
@@ -305,20 +302,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -327,10 +320,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: noon::NoonPaymentsResponse = res
.response
.parse_struct("Noon PaymentsAuthorizeResponse")
@@ -339,7 +332,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -355,14 +348,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Noon
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Noon {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -372,8 +363,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}payment/v1/order/getbyreference/{}",
@@ -384,25 +375,25 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: noon::NoonPaymentsResponse = res
.response
.parse_struct("noon PaymentsSyncResponse")
@@ -411,7 +402,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -427,14 +418,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Noon
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Noon {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -444,16 +433,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- _req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payment/v1/order", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
@@ -467,18 +456,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
+ .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -487,10 +474,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: noon::NoonPaymentsResponse = res
.response
.parse_struct("Noon PaymentsCaptureResponse")
@@ -499,7 +486,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -515,14 +502,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Noon
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Noon {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -532,15 +517,15 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- _req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payment/v1/order", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsCancelRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = noon::NoonPaymentsCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -548,28 +533,26 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&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,
- )?)
+ .headers(PaymentsVoidType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: noon::NoonPaymentsResponse = res
.response
.parse_struct("Noon PaymentsCancelResponse")
@@ -578,7 +561,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -594,18 +577,14 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
-impl
- ConnectorIntegration<
- api::MandateRevoke,
- types::MandateRevokeRequestData,
- types::MandateRevokeResponseData,
- > for Noon
+impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>
+ for Noon
{
fn get_headers(
&self,
- req: &types::MandateRevokeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &MandateRevokeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -613,34 +592,30 @@ impl
}
fn get_url(
&self,
- _req: &types::MandateRevokeRouterData,
- connectors: &settings::Connectors,
+ _req: &MandateRevokeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payment/v1/order", self.base_url(connectors)))
}
fn build_request(
&self,
- req: &types::MandateRevokeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &MandateRevokeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::MandateRevokeType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&MandateRevokeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::MandateRevokeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::MandateRevokeType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(MandateRevokeType::get_headers(self, req, connectors)?)
+ .set_body(MandateRevokeType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn get_request_body(
&self,
- req: &types::MandateRevokeRouterData,
- _connectors: &settings::Connectors,
+ req: &MandateRevokeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = noon::NoonRevokeMandateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -648,10 +623,10 @@ impl
fn handle_response(
&self,
- data: &types::MandateRevokeRouterData,
+ data: &MandateRevokeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::MandateRevokeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<MandateRevokeRouterData, errors::ConnectorError> {
let response: noon::NoonRevokeMandateResponse = res
.response
.parse_struct("Noon NoonRevokeMandateResponse")
@@ -660,7 +635,7 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -675,12 +650,12 @@ impl
}
}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Noon {
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Noon {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -690,16 +665,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ _req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payment/v1/order", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = connector_utils::convert_amount(
self.amount_converter,
@@ -713,29 +688,25 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&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,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: noon::RefundResponse = res
.response
.parse_struct("noon RefundResponse")
@@ -744,7 +715,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -760,12 +731,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Noon {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Noon {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -775,8 +746,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}payment/v1/order/getbyreference/{}",
@@ -787,25 +758,25 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: noon::RefundSyncResponse = res
.response
.parse_struct("noon RefundSyncResponse")
@@ -814,7 +785,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -831,52 +802,52 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
}
-impl services::ConnectorRedirectResponse for Noon {
+impl api::ConnectorRedirectResponse for Noon {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
- action: services::PaymentAction,
- ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ action: enums::PaymentAction,
+ ) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
match action {
- services::PaymentAction::PSync
- | services::PaymentAction::CompleteAuthorize
- | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
- Ok(payments::CallConnectorAction::Trigger)
+ enums::PaymentAction::PSync
+ | enums::PaymentAction::CompleteAuthorize
+ | enums::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
+ Ok(enums::CallConnectorAction::Trigger)
}
}
}
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Noon {
+impl webhooks::IncomingWebhook for Noon {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha512))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ _connector_webhook_secrets: &ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let webhook_body: noon::NoonWebhookSignature = request
.body
.parse_struct("NoonWebhookSignature")
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
let signature = webhook_body.signature;
- consts::BASE64_ENGINE
+ common_utils::consts::BASE64_ENGINE
.decode(signature)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)
}
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
- _connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
+ _connector_webhook_secrets: &ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let webhook_body: noon::NoonWebhookBody = request
.body
@@ -895,13 +866,13 @@ impl api::IncomingWebhook for Noon {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
let details: noon::NoonWebhookOrderId = request
.body
.parse_struct("NoonWebhookOrderId")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
- Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
+ Ok(ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
details.order_id.to_string(),
),
@@ -910,8 +881,8 @@ impl api::IncomingWebhook for Noon {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let details: noon::NoonWebhookEvent = request
.body
.parse_struct("NoonWebhookEvent")
@@ -920,23 +891,21 @@ impl api::IncomingWebhook for Noon {
Ok(match &details.event_type {
noon::NoonWebhookEventTypes::Sale | noon::NoonWebhookEventTypes::Capture => {
match &details.order_status {
- noon::NoonPaymentStatus::Captured => {
- api::IncomingWebhookEvent::PaymentIntentSuccess
- }
+ noon::NoonPaymentStatus::Captured => IncomingWebhookEvent::PaymentIntentSuccess,
_ => Err(errors::ConnectorError::WebhookEventTypeNotFound)?,
}
}
- noon::NoonWebhookEventTypes::Fail => api::IncomingWebhookEvent::PaymentIntentFailure,
+ noon::NoonWebhookEventTypes::Fail => IncomingWebhookEvent::PaymentIntentFailure,
noon::NoonWebhookEventTypes::Authorize
| noon::NoonWebhookEventTypes::Authenticate
| noon::NoonWebhookEventTypes::Refund
- | noon::NoonWebhookEventTypes::Unknown => api::IncomingWebhookEvent::EventNotSupported,
+ | noon::NoonWebhookEventTypes::Unknown => IncomingWebhookEvent::EventNotSupported,
})
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let resource: noon::NoonWebhookObject = request
.body
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
similarity index 72%
rename from crates/router/src/connector/noon/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
index eaf4ae18465..b2128b990c1 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
@@ -1,16 +1,30 @@
-use common_utils::{ext_traits::Encode, pii, types::StringMajorUnit};
+use common_enums::enums::{self, AttemptStatus};
+use common_utils::{ext_traits::Encode, pii, request::Method, types::StringMajorUnit};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::{PaymentMethodData, WalletData},
+ router_data::{ConnectorAuthType, ErrorResponse, RouterData},
+ router_flow_types::{Execute, RSync},
+ router_request_types::{MandateRevokeRequestData, ResponseId},
+ router_response_types::{
+ MandateReference, MandateRevokeResponseData, PaymentsResponseData, RedirectForm,
+ RefundsResponseData,
+ },
+ types::{
+ MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
+ PaymentsCaptureRouterData, RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{
- self as conn_utils, is_refund_failure, CardData, PaymentsAuthorizeRequestData,
- RevokeMandateRequestData, RouterData, WalletData,
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{
+ self, CardData, GooglePayWalletData, PaymentsAuthorizeRequestData,
+ RevokeMandateRequestData, RouterData as OtherRouterData, WalletData as OtherWalletData,
},
- core::errors,
- services,
- types::{self, api, domain, storage::enums, transformers::ForeignFrom, ErrorResponse},
};
// These needs to be accepted from SDK, need to be done after 1.0.0 stability as API contract will change
@@ -79,7 +93,7 @@ pub struct NoonBilling {
#[serde(rename_all = "camelCase")]
pub struct NoonOrder {
amount: StringMajorUnit,
- currency: Option<diesel_models::enums::Currency>,
+ currency: Option<enums::Currency>,
channel: NoonChannels,
category: Option<String>,
reference: String,
@@ -206,7 +220,7 @@ pub struct NoonApplePay {
pub struct NoonGooglePay {
api_version_minor: u8,
api_version: u8,
- payment_method_data: conn_utils::GooglePayWalletData,
+ payment_method_data: GooglePayWalletData,
}
#[derive(Debug, Serialize)]
@@ -245,11 +259,9 @@ pub struct NoonPaymentsRequest {
billing: Option<NoonBilling>,
}
-impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPaymentsRequest {
+impl TryFrom<&NoonRouterData<&PaymentsAuthorizeRouterData>> for NoonPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- data: &NoonRouterData<&types::PaymentsAuthorizeRouterData>,
- ) -> Result<Self, Self::Error> {
+ fn try_from(data: &NoonRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let item = data.router_data;
let amount = &data.amount;
let mandate_amount = &data.mandate_amount;
@@ -264,26 +276,22 @@ impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPayme
),
_ => (
match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(req_card) => {
- Ok(NoonPaymentData::Card(NoonCard {
- name_on_card: item.get_optional_billing_full_name(),
- number_plain: req_card.card_number.clone(),
- expiry_month: req_card.card_exp_month.clone(),
- expiry_year: req_card.get_expiry_year_4_digit(),
- cvv: req_card.card_cvc,
- }))
- }
- domain::PaymentMethodData::Wallet(wallet_data) => match wallet_data.clone() {
- domain::WalletData::GooglePay(google_pay_data) => {
+ PaymentMethodData::Card(req_card) => Ok(NoonPaymentData::Card(NoonCard {
+ name_on_card: item.get_optional_billing_full_name(),
+ number_plain: req_card.card_number.clone(),
+ expiry_month: req_card.card_exp_month.clone(),
+ expiry_year: req_card.get_expiry_year_4_digit(),
+ cvv: req_card.card_cvc,
+ })),
+ PaymentMethodData::Wallet(wallet_data) => match wallet_data.clone() {
+ WalletData::GooglePay(google_pay_data) => {
Ok(NoonPaymentData::GooglePay(NoonGooglePay {
api_version_minor: GOOGLEPAY_API_VERSION_MINOR,
api_version: GOOGLEPAY_API_VERSION,
- payment_method_data: conn_utils::GooglePayWalletData::from(
- google_pay_data,
- ),
+ payment_method_data: GooglePayWalletData::from(google_pay_data),
}))
}
- domain::WalletData::ApplePay(apple_pay_data) => {
+ WalletData::ApplePay(apple_pay_data) => {
let payment_token_data = NoonApplePayTokenData {
token: NoonApplePayData {
payment_data: wallet_data
@@ -306,61 +314,57 @@ impl TryFrom<&NoonRouterData<&types::PaymentsAuthorizeRouterData>> for NoonPayme
payment_info: Secret::new(payment_token),
}))
}
- domain::WalletData::PaypalRedirect(_) => {
- Ok(NoonPaymentData::PayPal(NoonPayPal {
- return_url: item.request.get_router_return_url()?,
- }))
- }
- domain::WalletData::AliPayQr(_)
- | domain::WalletData::AliPayRedirect(_)
- | domain::WalletData::AliPayHkRedirect(_)
- | domain::WalletData::AmazonPayRedirect(_)
- | domain::WalletData::MomoRedirect(_)
- | domain::WalletData::KakaoPayRedirect(_)
- | domain::WalletData::GoPayRedirect(_)
- | domain::WalletData::GcashRedirect(_)
- | domain::WalletData::ApplePayRedirect(_)
- | domain::WalletData::ApplePayThirdPartySdk(_)
- | domain::WalletData::DanaRedirect {}
- | domain::WalletData::GooglePayRedirect(_)
- | domain::WalletData::GooglePayThirdPartySdk(_)
- | domain::WalletData::MbWayRedirect(_)
- | domain::WalletData::MobilePayRedirect(_)
- | domain::WalletData::PaypalSdk(_)
- | domain::WalletData::Paze(_)
- | domain::WalletData::SamsungPay(_)
- | domain::WalletData::TwintRedirect {}
- | domain::WalletData::VippsRedirect {}
- | domain::WalletData::TouchNGoRedirect(_)
- | domain::WalletData::WeChatPayRedirect(_)
- | domain::WalletData::WeChatPayQr(_)
- | domain::WalletData::CashappQr(_)
- | domain::WalletData::SwishQr(_)
- | domain::WalletData::Mifinity(_) => {
- Err(errors::ConnectorError::NotImplemented(
- conn_utils::get_unimplemented_payment_method_error_message("Noon"),
- ))
- }
+ WalletData::PaypalRedirect(_) => Ok(NoonPaymentData::PayPal(NoonPayPal {
+ return_url: item.request.get_router_return_url()?,
+ })),
+ WalletData::AliPayQr(_)
+ | WalletData::AliPayRedirect(_)
+ | WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
+ | WalletData::MomoRedirect(_)
+ | WalletData::KakaoPayRedirect(_)
+ | WalletData::GoPayRedirect(_)
+ | WalletData::GcashRedirect(_)
+ | WalletData::ApplePayRedirect(_)
+ | WalletData::ApplePayThirdPartySdk(_)
+ | WalletData::DanaRedirect {}
+ | WalletData::GooglePayRedirect(_)
+ | WalletData::GooglePayThirdPartySdk(_)
+ | WalletData::MbWayRedirect(_)
+ | WalletData::MobilePayRedirect(_)
+ | WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
+ | WalletData::SamsungPay(_)
+ | WalletData::TwintRedirect {}
+ | WalletData::VippsRedirect {}
+ | WalletData::TouchNGoRedirect(_)
+ | WalletData::WeChatPayRedirect(_)
+ | WalletData::WeChatPayQr(_)
+ | WalletData::CashappQr(_)
+ | WalletData::SwishQr(_)
+ | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotImplemented(
+ utils::get_unimplemented_payment_method_error_message("Noon"),
+ )),
},
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment {}
- | domain::PaymentMethodData::Reward {}
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment {}
+ | PaymentMethodData::Reward {}
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
- conn_utils::get_unimplemented_payment_method_error_message("Noon"),
+ utils::get_unimplemented_payment_method_error_message("Noon"),
))
}
}?,
@@ -448,11 +452,11 @@ pub struct NoonAuthType {
pub(super) business_identifier: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for NoonAuthType {
+impl TryFrom<&ConnectorAuthType> for NoonAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::SignatureKey {
+ ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
@@ -495,28 +499,28 @@ pub enum NoonPaymentStatus {
Locked,
}
-impl ForeignFrom<(NoonPaymentStatus, Self)> for enums::AttemptStatus {
- fn foreign_from(data: (NoonPaymentStatus, Self)) -> Self {
- let (item, current_status) = data;
- match item {
- NoonPaymentStatus::Authorized => Self::Authorized,
- NoonPaymentStatus::Captured
- | NoonPaymentStatus::PartiallyCaptured
- | NoonPaymentStatus::PartiallyRefunded
- | NoonPaymentStatus::Refunded => Self::Charged,
- NoonPaymentStatus::Reversed | NoonPaymentStatus::PartiallyReversed => Self::Voided,
- NoonPaymentStatus::Cancelled | NoonPaymentStatus::Expired => Self::AuthenticationFailed,
- NoonPaymentStatus::ThreeDsEnrollInitiated | NoonPaymentStatus::ThreeDsEnrollChecked => {
- Self::AuthenticationPending
- }
- NoonPaymentStatus::ThreeDsResultVerified => Self::AuthenticationSuccessful,
- NoonPaymentStatus::Failed | NoonPaymentStatus::Rejected => Self::Failure,
- NoonPaymentStatus::Pending | NoonPaymentStatus::MarkedForReview => Self::Pending,
- NoonPaymentStatus::Initiated
- | NoonPaymentStatus::PaymentInfoAdded
- | NoonPaymentStatus::Authenticated => Self::Started,
- NoonPaymentStatus::Locked => current_status,
+fn get_payment_status(data: (NoonPaymentStatus, AttemptStatus)) -> AttemptStatus {
+ let (item, current_status) = data;
+ match item {
+ NoonPaymentStatus::Authorized => AttemptStatus::Authorized,
+ NoonPaymentStatus::Captured
+ | NoonPaymentStatus::PartiallyCaptured
+ | NoonPaymentStatus::PartiallyRefunded
+ | NoonPaymentStatus::Refunded => AttemptStatus::Charged,
+ NoonPaymentStatus::Reversed | NoonPaymentStatus::PartiallyReversed => AttemptStatus::Voided,
+ NoonPaymentStatus::Cancelled | NoonPaymentStatus::Expired => {
+ AttemptStatus::AuthenticationFailed
+ }
+ NoonPaymentStatus::ThreeDsEnrollInitiated | NoonPaymentStatus::ThreeDsEnrollChecked => {
+ AttemptStatus::AuthenticationPending
}
+ NoonPaymentStatus::ThreeDsResultVerified => AttemptStatus::AuthenticationSuccessful,
+ NoonPaymentStatus::Failed | NoonPaymentStatus::Rejected => AttemptStatus::Failure,
+ NoonPaymentStatus::Pending | NoonPaymentStatus::MarkedForReview => AttemptStatus::Pending,
+ NoonPaymentStatus::Initiated
+ | NoonPaymentStatus::PaymentInfoAdded
+ | NoonPaymentStatus::Authenticated => AttemptStatus::Started,
+ NoonPaymentStatus::Locked => current_status,
}
}
@@ -554,28 +558,29 @@ pub struct NoonPaymentsResponse {
result: NoonPaymentsResponseResult,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, NoonPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, NoonPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, NoonPaymentsResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, NoonPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let order = item.response.result.order;
- let status = enums::AttemptStatus::foreign_from((order.status, item.data.status));
- let redirection_data = item.response.result.checkout_data.map(|redirection_data| {
- services::RedirectForm::Form {
- endpoint: redirection_data.post_url.to_string(),
- method: services::Method::Post,
- form_fields: std::collections::HashMap::new(),
- }
- });
+ let status = get_payment_status((order.status, item.data.status));
+ let redirection_data =
+ item.response
+ .result
+ .checkout_data
+ .map(|redirection_data| RedirectForm::Form {
+ endpoint: redirection_data.post_url.to_string(),
+ method: Method::Post,
+ form_fields: std::collections::HashMap::new(),
+ });
let mandate_reference =
item.response
.result
.subscription
- .map(|subscription_data| types::MandateReference {
+ .map(|subscription_data| MandateReference {
connector_mandate_id: Some(subscription_data.identifier.expose()),
payment_method_id: None,
mandate_metadata: None,
@@ -595,10 +600,8 @@ impl<F, T>
_ => {
let connector_response_reference_id =
order.reference.or(Some(order.id.to_string()));
- Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- order.id.to_string(),
- ),
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(order.id.to_string()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(mandate_reference),
connector_metadata: None,
@@ -618,7 +621,7 @@ impl<F, T>
#[serde(rename_all = "camelCase")]
pub struct NoonActionTransaction {
amount: StringMajorUnit,
- currency: diesel_models::enums::Currency,
+ currency: enums::Currency,
transaction_reference: Option<String>,
}
@@ -636,11 +639,9 @@ pub struct NoonPaymentsActionRequest {
transaction: NoonActionTransaction,
}
-impl TryFrom<&NoonRouterData<&types::PaymentsCaptureRouterData>> for NoonPaymentsActionRequest {
+impl TryFrom<&NoonRouterData<&PaymentsCaptureRouterData>> for NoonPaymentsActionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- data: &NoonRouterData<&types::PaymentsCaptureRouterData>,
- ) -> Result<Self, Self::Error> {
+ fn try_from(data: &NoonRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
let item = data.router_data;
let amount = &data.amount;
let order = NoonActionOrder {
@@ -666,9 +667,9 @@ pub struct NoonPaymentsCancelRequest {
order: NoonActionOrder,
}
-impl TryFrom<&types::PaymentsCancelRouterData> for NoonPaymentsCancelRequest {
+impl TryFrom<&PaymentsCancelRouterData> for NoonPaymentsCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let order = NoonActionOrder {
id: item.request.connector_transaction_id.clone(),
};
@@ -686,9 +687,9 @@ pub struct NoonRevokeMandateRequest {
subscription: NoonSubscriptionObject,
}
-impl TryFrom<&types::MandateRevokeRouterData> for NoonRevokeMandateRequest {
+impl TryFrom<&MandateRevokeRouterData> for NoonRevokeMandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::MandateRevokeRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &MandateRevokeRouterData) -> Result<Self, Self::Error> {
Ok(Self {
api_operation: NoonApiOperations::CancelSubscription,
subscription: NoonSubscriptionObject {
@@ -698,9 +699,9 @@ impl TryFrom<&types::MandateRevokeRouterData> for NoonRevokeMandateRequest {
}
}
-impl<F> TryFrom<&NoonRouterData<&types::RefundsRouterData<F>>> for NoonPaymentsActionRequest {
+impl<F> TryFrom<&NoonRouterData<&RefundsRouterData<F>>> for NoonPaymentsActionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(data: &NoonRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ fn try_from(data: &NoonRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let item = data.router_data;
let refund_amount = &data.amount;
let order = NoonActionOrder {
@@ -740,26 +741,26 @@ pub struct NoonRevokeMandateResponse {
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
NoonRevokeMandateResponse,
- types::MandateRevokeRequestData,
- types::MandateRevokeResponseData,
+ MandateRevokeRequestData,
+ MandateRevokeResponseData,
>,
- > for types::RouterData<F, types::MandateRevokeRequestData, types::MandateRevokeResponseData>
+ > for RouterData<F, MandateRevokeRequestData, MandateRevokeResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
NoonRevokeMandateResponse,
- types::MandateRevokeRequestData,
- types::MandateRevokeResponseData,
+ MandateRevokeRequestData,
+ MandateRevokeResponseData,
>,
) -> Result<Self, Self::Error> {
match item.response.result.subscription.status {
NoonRevokeStatus::Cancelled => Ok(Self {
- response: Ok(types::MandateRevokeResponseData {
+ response: Ok(MandateRevokeResponseData {
mandate_status: common_enums::MandateStatus::Revoked,
}),
..item.data
@@ -809,17 +810,15 @@ pub struct RefundResponse {
message: String,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
-{
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
let response = &item.response;
let refund_status =
enums::RefundStatus::from(response.result.transaction.status.to_owned());
- let response = if is_refund_failure(refund_status) {
+ let response = if utils::is_refund_failure(refund_status) {
Err(ErrorResponse {
status_code: item.http_code,
code: response.result_code.to_string(),
@@ -829,7 +828,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
connector_transaction_id: Some(response.result.transaction.id.clone()),
})
} else {
- Ok(types::RefundsResponseData {
+ Ok(RefundsResponseData {
connector_refund_id: item.response.result.transaction.id,
refund_status,
})
@@ -864,12 +863,10 @@ pub struct RefundSyncResponse {
message: String,
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundSyncResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>,
+ item: RefundsResponseRouterData<RSync, RefundSyncResponse>,
) -> Result<Self, Self::Error> {
let noon_transaction: &NoonRefundResponseTransactions = item
.response
@@ -886,7 +883,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>>
})
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let refund_status = enums::RefundStatus::from(noon_transaction.status.to_owned());
- let response = if is_refund_failure(refund_status) {
+ let response = if utils::is_refund_failure(refund_status) {
let response = &item.response;
Err(ErrorResponse {
status_code: item.http_code,
@@ -897,7 +894,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundSyncResponse>>
connector_transaction_id: Some(noon_transaction.id.clone()),
})
} else {
- Ok(types::RefundsResponseData {
+ Ok(RefundsResponseData {
connector_refund_id: noon_transaction.id.to_owned(),
refund_status,
})
diff --git a/crates/router/src/connector/opayo.rs b/crates/hyperswitch_connectors/src/connectors/opayo.rs
similarity index 61%
rename from crates/router/src/connector/opayo.rs
rename to crates/hyperswitch_connectors/src/connectors/opayo.rs
index a9fc439e54c..b2aadda37f7 100644
--- a/crates/router/src/connector/opayo.rs
+++ b/crates/hyperswitch_connectors/src/connectors/opayo.rs
@@ -1,32 +1,49 @@
mod transformers;
+use common_enums::enums;
use common_utils::{
- request::RequestContent,
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
-use diesel_models::enums;
use error_stack::{report, ResultExt};
-use masking::ExposeInterface;
-use transformers as opayo;
-
-use crate::{
- configs::settings,
- connector::{utils as connector_utils, utils::convert_amount},
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
+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,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, RefundExecuteType,
+ RefundSyncType, Response,
},
- utils::BytesExt,
+ webhooks,
};
+use masking::{ExposeInterface, Mask};
+use transformers as opayo;
+
+use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount};
#[derive(Clone)]
pub struct Opayo {
@@ -54,12 +71,8 @@ impl api::RefundExecute for Opayo {}
impl api::RefundSync for Opayo {}
impl api::PaymentToken for Opayo {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Opayo
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Opayo
{
}
@@ -69,9 +82,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let content_type = ConnectorCommon::common_get_content_type(self);
let mut common_headers = self.get_auth_header(&req.connector_auth_type)?;
common_headers.push((
@@ -90,14 +103,14 @@ impl ConnectorCommon for Opayo {
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.opayo.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = opayo::OpayoAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -143,39 +156,24 @@ impl ConnectorValidation for Opayo {
| enums::CaptureMethod::Manual
| enums::CaptureMethod::SequentialAutomatic => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ crate::utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Opayo
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Opayo {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Opayo
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Opayo {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Opayo
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Opayo {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Opayo".to_string())
.into(),
@@ -183,14 +181,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Opayo
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Opayo {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -200,16 +196,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
@@ -223,20 +219,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -245,10 +237,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: opayo::OpayoPaymentsResponse = res
.response
.parse_struct("Opayo PaymentsAuthorizeResponse")
@@ -257,7 +249,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -273,14 +265,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Opayo
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Opayo {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -290,33 +280,33 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: opayo::OpayoPaymentsResponse = res
.response
.parse_struct("opayo PaymentsSyncResponse")
@@ -325,7 +315,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -341,14 +331,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Opayo
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Opayo {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -358,34 +346,32 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
+ .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -394,10 +380,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: opayo::OpayoPaymentsResponse = res
.response
.parse_struct("Opayo PaymentsCaptureResponse")
@@ -406,7 +392,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -422,17 +408,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Opayo
-{
-}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Opayo {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Opayo {
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Opayo {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -442,16 +425,16 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ _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: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
@@ -466,29 +449,25 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&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,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: opayo::RefundResponse = res
.response
.parse_struct("opayo RefundResponse")
@@ -497,7 +476,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -513,12 +492,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Opayo {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Opayo {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -528,33 +507,33 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- _req: &types::RefundSyncRouterData,
- _connectors: &settings::Connectors,
+ _req: &RefundSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: opayo::RefundResponse = res
.response
.parse_struct("opayo RefundSyncResponse")
@@ -563,7 +542,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -580,24 +559,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Opayo {
+impl webhooks::IncomingWebhook for Opayo {
fn get_webhook_object_reference_id(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/hyperswitch_connectors/src/connectors/opayo/transformers.rs
similarity index 65%
rename from crates/router/src/connector/opayo/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/opayo/transformers.rs
index 992acfb5ef0..819f8e10402 100644
--- a/crates/router/src/connector/opayo/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/opayo/transformers.rs
@@ -1,12 +1,22 @@
+use common_enums::enums;
use common_utils::types::MinorUnit;
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::{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::{
- connector::utils::{self, PaymentsAuthorizeRequestData, RouterData},
- core::errors,
- types::{self, api, domain, storage::enums},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
+
#[derive(Debug, Serialize)]
pub struct OpayoRouterData<T> {
pub amount: MinorUnit,
@@ -38,14 +48,14 @@ pub struct OpayoCard {
complete: bool,
}
-impl TryFrom<&OpayoRouterData<&types::PaymentsAuthorizeRouterData>> for OpayoPaymentsRequest {
+impl TryFrom<&OpayoRouterData<&PaymentsAuthorizeRouterData>> for OpayoPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item_data: &OpayoRouterData<&types::PaymentsAuthorizeRouterData>,
+ item_data: &OpayoRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let item = item_data.router_data.clone();
match item.request.payment_method_data.clone() {
- domain::PaymentMethodData::Card(req_card) => {
+ PaymentMethodData::Card(req_card) => {
let card = OpayoCard {
name: item
.get_optional_billing_full_name()
@@ -61,26 +71,26 @@ impl TryFrom<&OpayoRouterData<&types::PaymentsAuthorizeRouterData>> for OpayoPay
card,
})
}
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankRedirect(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankRedirect(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
- utils::get_unimplemented_payment_method_error_message("Opayo"),
+ crate::utils::get_unimplemented_payment_method_error_message("Opayo"),
)
.into())
}
@@ -93,11 +103,11 @@ pub struct OpayoAuthType {
pub(super) api_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for OpayoAuthType {
+impl TryFrom<&ConnectorAuthType> for OpayoAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
@@ -131,18 +141,17 @@ pub struct OpayoPaymentsResponse {
transaction_id: String,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, OpayoPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, OpayoPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, OpayoPaymentsResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, OpayoPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
@@ -165,9 +174,9 @@ pub struct OpayoRefundRequest {
pub amount: MinorUnit,
}
-impl<F> TryFrom<&OpayoRouterData<&types::RefundsRouterData<F>>> for OpayoRefundRequest {
+impl<F> TryFrom<&OpayoRouterData<&RefundsRouterData<F>>> for OpayoRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &OpayoRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ fn try_from(item: &OpayoRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.amount,
})
@@ -202,15 +211,13 @@ pub struct RefundResponse {
status: RefundStatus,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
-{
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
@@ -219,15 +226,13 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
diff --git a/crates/router/src/connector/opennode.rs b/crates/hyperswitch_connectors/src/connectors/opennode.rs
similarity index 63%
rename from crates/router/src/connector/opennode.rs
rename to crates/hyperswitch_connectors/src/connectors/opennode.rs
index 1c11da05712..fefd2f77768 100644
--- a/crates/router/src/connector/opennode.rs
+++ b/crates/hyperswitch_connectors/src/connectors/opennode.rs
@@ -2,29 +2,47 @@ pub mod transformers;
use std::fmt::Debug;
-use common_utils::{crypto, request::RequestContent};
+use common_utils::{
+ crypto,
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
+};
use error_stack::ResultExt;
-use transformers as opennode;
-
-use self::opennode::OpennodeWebhookDetails;
-use crate::{
- configs::settings,
- consts,
- core::errors::{self, CustomResult},
- events::connector_api_logs::ConnectorEvent,
- headers,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
+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::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
+ RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{
+ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
+ ConnectorValidation,
},
- utils::BytesExt,
+ configs::Connectors,
+ consts, errors,
+ events::connector_api_logs::ConnectorEvent,
+ types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
+ webhooks::{self, IncomingWebhook},
};
+use masking::{Mask, Maskable};
+use transformers as opennode;
+
+use self::opennode::OpennodeWebhookDetails;
+use crate::{constants::headers, types::ResponseRouterData};
#[derive(Debug, Clone)]
pub struct Opennode;
@@ -49,9 +67,9 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
@@ -81,14 +99,14 @@ impl ConnectorCommon for Opennode {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.opennode.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = opennode::OpennodeAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -123,43 +141,26 @@ impl ConnectorCommon for Opennode {
impl ConnectorValidation for Opennode {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Opennode
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Opennode
{
// Not Implemented (R)
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Opennode
-{
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Opennode {
//TODO: implement sessions flow
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Opennode
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Opennode {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Opennode
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Opennode
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Opennode".to_string())
.into(),
@@ -167,14 +168,12 @@ impl
}
}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Opennode
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Opennode {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -184,16 +183,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- _req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/v1/charges", self.base_url(_connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = opennode::OpennodeRouterData::try_from((
&self.get_currency_unit(),
@@ -207,19 +206,15 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -228,10 +223,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: opennode::OpennodePaymentsResponse = res
.response
.parse_struct("Opennode PaymentsAuthorizeResponse")
@@ -240,7 +235,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -257,14 +252,12 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Opennode
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Opennode {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -274,8 +267,8 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- _req: &types::PaymentsSyncRouterData,
- _connectors: &settings::Connectors,
+ _req: &PaymentsSyncRouterData,
+ _connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_id = _req
.request
@@ -291,24 +284,24 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: opennode::OpennodePaymentsResponse = res
.response
.parse_struct("opennode PaymentsSyncResponse")
@@ -317,7 +310,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -334,14 +327,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Opennode
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Opennode {
fn build_request(
&self,
- _req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Opennode".to_string(),
@@ -350,19 +341,14 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Opennode
-{
-}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Opennode {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Opennode
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Opennode {
fn build_request(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Refund flow not Implemented".to_string())
.into(),
@@ -370,22 +356,22 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Opennode {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Opennode {
// default implementation of build_request method will be executed
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Opennode {
+impl IncomingWebhook for Opennode {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notif = serde_urlencoded::from_bytes::<OpennodeWebhookDetails>(request.body)
@@ -397,7 +383,7 @@ impl api::IncomingWebhook for Opennode {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -408,7 +394,7 @@ impl api::IncomingWebhook for Opennode {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif = serde_urlencoded::from_bytes::<OpennodeWebhookDetails>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
@@ -419,29 +405,29 @@ impl api::IncomingWebhook for Opennode {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif = serde_urlencoded::from_bytes::<OpennodeWebhookDetails>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
match notif.status {
opennode::OpennodePaymentStatus::Paid => {
- Ok(api::IncomingWebhookEvent::PaymentIntentSuccess)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
opennode::OpennodePaymentStatus::Underpaid
| opennode::OpennodePaymentStatus::Expired => {
- Ok(api::IncomingWebhookEvent::PaymentActionRequired)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
opennode::OpennodePaymentStatus::Processing => {
- Ok(api::IncomingWebhookEvent::PaymentIntentProcessing)
+ Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
- _ => Ok(api::IncomingWebhookEvent::EventNotSupported),
+ _ => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),
}
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif = serde_urlencoded::from_bytes::<OpennodeWebhookDetails>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
diff --git a/crates/router/src/connector/opennode/transformers.rs b/crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs
similarity index 73%
rename from crates/router/src/connector/opennode/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs
index 067237bc3e2..3aa6c63ba51 100644
--- a/crates/router/src/connector/opennode/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs
@@ -1,13 +1,21 @@
use std::collections::HashMap;
+use common_enums::{enums, AttemptStatus};
+use common_utils::request::Method;
+use hyperswitch_domain_models::{
+ router_data::{ConnectorAuthType, RouterData},
+ router_flow_types::refunds::{Execute, RSync},
+ router_request_types::ResponseId,
+ router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
+ types::{PaymentsAuthorizeRouterData, RefundsRouterData},
+};
+use hyperswitch_interfaces::{api::CurrencyUnit, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{PaymentsAuthorizeRequestData, RouterData},
- core::errors,
- services,
- types::{self, api, storage::enums},
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{PaymentsAuthorizeRequestData, RouterData as OtherRouterData},
};
#[derive(Debug, Serialize)]
@@ -16,16 +24,11 @@ pub struct OpennodeRouterData<T> {
pub router_data: T,
}
-impl<T> TryFrom<(&api::CurrencyUnit, enums::Currency, i64, T)> for OpennodeRouterData<T> {
+impl<T> TryFrom<(&CurrencyUnit, enums::Currency, i64, T)> for OpennodeRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- (_currency_unit, _currency, amount, router_data): (
- &api::CurrencyUnit,
- enums::Currency,
- i64,
- T,
- ),
+ (_currency_unit, _currency, amount, router_data): (&CurrencyUnit, enums::Currency, i64, T),
) -> Result<Self, Self::Error> {
Ok(Self {
amount,
@@ -46,10 +49,10 @@ pub struct OpennodePaymentsRequest {
order_id: String,
}
-impl TryFrom<&OpennodeRouterData<&types::PaymentsAuthorizeRouterData>> for OpennodePaymentsRequest {
+impl TryFrom<&OpennodeRouterData<&PaymentsAuthorizeRouterData>> for OpennodePaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &OpennodeRouterData<&types::PaymentsAuthorizeRouterData>,
+ item: &OpennodeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
get_crypto_specific_payment_data(item)
}
@@ -61,11 +64,11 @@ pub struct OpennodeAuthType {
pub(super) api_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for OpennodeAuthType {
+impl TryFrom<&ConnectorAuthType> for OpennodeAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
api_key: api_key.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
@@ -88,7 +91,7 @@ pub enum OpennodePaymentStatus {
Unknown,
}
-impl From<OpennodePaymentStatus> for enums::AttemptStatus {
+impl From<OpennodePaymentStatus> for AttemptStatus {
fn from(item: OpennodePaymentStatus) -> Self {
match item {
OpennodePaymentStatus::Unpaid => Self::AuthenticationPending,
@@ -114,29 +117,23 @@ pub struct OpennodePaymentsResponse {
data: OpennodePaymentsResponseData,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, OpennodePaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, OpennodePaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- OpennodePaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, OpennodePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let form_fields = HashMap::new();
- let redirection_data = services::RedirectForm::Form {
+ let redirection_data = RedirectForm::Form {
endpoint: item.response.data.hosted_checkout_url.to_string(),
- method: services::Method::Get,
+ method: Method::Get,
form_fields,
};
- let connector_id = types::ResponseId::ConnectorTransactionId(item.response.data.id);
+ let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id);
let attempt_status = item.response.data.status;
let response_data = if attempt_status != OpennodePaymentStatus::Underpaid {
- Ok(types::PaymentsResponseData::TransactionResponse {
+ Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id,
redirection_data: Box::new(Some(redirection_data)),
mandate_reference: Box::new(None),
@@ -147,9 +144,9 @@ impl<F, T>
charges: None,
})
} else {
- Ok(types::PaymentsResponseData::TransactionUnresolvedResponse {
+ Ok(PaymentsResponseData::TransactionUnresolvedResponse {
resource_id: connector_id,
- reason: Some(api::enums::UnresolvedResponseReason {
+ reason: Some(api_models::enums::UnresolvedResponseReason {
code: "UNDERPAID".to_string(),
message:
"Please check the transaction in opennode dashboard and resolve manually"
@@ -159,7 +156,7 @@ impl<F, T>
})
};
Ok(Self {
- status: enums::AttemptStatus::from(attempt_status),
+ status: AttemptStatus::from(attempt_status),
response: response_data,
..item.data
})
@@ -174,11 +171,9 @@ pub struct OpennodeRefundRequest {
pub amount: i64,
}
-impl<F> TryFrom<&OpennodeRouterData<&types::RefundsRouterData<F>>> for OpennodeRefundRequest {
+impl<F> TryFrom<&OpennodeRouterData<&RefundsRouterData<F>>> for OpennodeRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &OpennodeRouterData<&types::RefundsRouterData<F>>,
- ) -> Result<Self, Self::Error> {
+ fn try_from(item: &OpennodeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.router_data.request.refund_amount,
})
@@ -211,15 +206,13 @@ pub struct RefundResponse {
status: RefundStatus,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
- for types::RefundsRouterData<api::Execute>
-{
+impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ item: RefundsResponseRouterData<Execute, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
@@ -228,15 +221,13 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
}
}
-impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
- for types::RefundsRouterData<api::RSync>
-{
+impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ item: RefundsResponseRouterData<RSync, RefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
- response: Ok(types::RefundsResponseData {
+ response: Ok(RefundsResponseData {
connector_refund_id: item.response.id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
@@ -252,7 +243,7 @@ pub struct OpennodeErrorResponse {
}
fn get_crypto_specific_payment_data(
- item: &OpennodeRouterData<&types::PaymentsAuthorizeRouterData>,
+ item: &OpennodeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<OpennodePaymentsRequest, error_stack::Report<errors::ConnectorError>> {
let amount = item.amount;
let currency = item.router_data.request.currency.to_string();
diff --git a/crates/router/src/connector/payme.rs b/crates/hyperswitch_connectors/src/connectors/payme.rs
similarity index 66%
rename from crates/router/src/connector/payme.rs
rename to crates/hyperswitch_connectors/src/connectors/payme.rs
index 10a0fe67562..9c1a94ad3c0 100644
--- a/crates/router/src/connector/payme.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payme.rs
@@ -1,38 +1,61 @@
pub mod transformers;
use api_models::enums::AuthenticationType;
+use common_enums::enums;
use common_utils::{
crypto,
- request::RequestContent,
+ errors::CustomResult,
+ ext_traits::BytesExt,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{
AmountConvertor, MinorUnit, MinorUnitForConnector, StringMajorUnit,
StringMajorUnitForConnector,
},
};
-use diesel_models::enums;
use error_stack::{Report, ResultExt};
-use masking::{ExposeInterface, Secret};
-use transformers as payme;
-
-use crate::{
- configs::settings,
- connector::utils::{self as connector_utils, PaymentMethodDataType, PaymentsPreProcessingData},
- core::{
- errors::{self, CustomResult},
- payments,
+use hyperswitch_domain_models::{
+ payment_method_data::PaymentMethodData,
+ router_data::{AccessToken, ErrorResponse, RouterData},
+ router_flow_types::{
+ access_token_auth::AccessTokenAuth,
+ payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
+ refunds::{Execute, RSync},
+ CompleteAuthorize, InitPayment, PreProcessing,
+ },
+ router_request_types::{
+ AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData,
+ PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, RefundsRouterData,
+ TokenizationRouterData,
+ },
+};
+use hyperswitch_interfaces::{
+ api::{
+ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
+ ConnectorSpecifications, ConnectorValidation, PaymentsPreProcessing,
},
+ configs::Connectors,
+ disputes::DisputePayload,
+ errors,
events::connector_api_logs::ConnectorEvent,
- headers,
- services::{self, request, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation},
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- domain,
- transformers::ForeignTryFrom,
- ErrorResponse, Response,
+ PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType,
+ PaymentsPreProcessingType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType,
+ RefundSyncType, Response, TokenizationType,
},
- // transformers::{ForeignFrom, ForeignTryFrom},
- utils::{handle_json_response_deserialization_failure, BytesExt},
+ webhooks,
+};
+use masking::{ExposeInterface, Secret};
+use transformers as payme;
+
+use crate::{
+ types::ResponseRouterData,
+ utils::{self, ForeignTryFrom, PaymentsPreProcessingRequestData},
};
#[derive(Clone)]
@@ -70,11 +93,11 @@ where
{
fn build_headers(
&self,
- _req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ _req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let header = vec![(
- headers::CONTENT_TYPE.to_string(),
+ crate::constants::headers::CONTENT_TYPE.to_string(),
Self::get_content_type(self).to_string().into(),
)];
Ok(header)
@@ -94,7 +117,7 @@ impl ConnectorCommon for Payme {
"application/json"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.payme.base_url.as_ref()
}
@@ -131,7 +154,7 @@ impl ConnectorCommon for Payme {
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
router_env::logger::error!(deserialization_error =? error_msg);
- handle_json_response_deserialization_failure(res, "payme")
+ utils::handle_json_response_deserialization_failure(res, "payme")
}
}
}
@@ -150,36 +173,32 @@ impl ConnectorValidation for Payme {
| enums::CaptureMethod::Manual
| enums::CaptureMethod::SequentialAutomatic => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
- connector_utils::construct_not_supported_error_report(capture_method, self.id()),
+ utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
fn validate_mandate_payment(
&self,
- pm_type: Option<types::storage::enums::PaymentMethodType>,
- pm_data: domain::payments::PaymentMethodData,
+ pm_type: Option<enums::PaymentMethodType>,
+ pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
- PaymentMethodDataType::Card,
- PaymentMethodDataType::ApplePayThirdPartySdk,
+ utils::PaymentMethodDataType::Card,
+ utils::PaymentMethodDataType::ApplePayThirdPartySdk,
]);
- connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
+ utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Payme
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Payme
{
fn get_headers(
&self,
- req: &types::TokenizationRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &TokenizationRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -189,8 +208,8 @@ impl
fn get_url(
&self,
- _req: &types::TokenizationRouterData,
- connectors: &settings::Connectors,
+ _req: &TokenizationRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}api/capture-buyer-token",
@@ -200,8 +219,8 @@ impl
fn get_request_body(
&self,
- req: &types::TokenizationRouterData,
- _connectors: &settings::Connectors,
+ req: &TokenizationRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payme::CaptureBuyerRequest::try_from(req)?;
@@ -210,19 +229,17 @@ impl
fn build_request(
&self,
- req: &types::TokenizationRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &TokenizationRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(match req.auth_type {
AuthenticationType::ThreeDs => Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::TokenizationType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::TokenizationType::get_headers(self, req, connectors)?)
- .set_body(types::TokenizationType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(TokenizationType::get_headers(self, req, connectors)?)
+ .set_body(TokenizationType::get_request_body(self, req, connectors)?)
.build(),
),
AuthenticationType::NoThreeDs => None,
@@ -231,12 +248,12 @@ impl
fn handle_response(
&self,
- data: &types::TokenizationRouterData,
+ data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::TokenizationRouterData, errors::ConnectorError>
+ ) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
where
- types::PaymentsResponseData: Clone,
+ PaymentsResponseData: Clone,
{
let response: payme::CaptureBuyerResponse = res
.response
@@ -246,7 +263,7 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -271,25 +288,18 @@ impl
}
}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Payme
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Payme {}
-impl api::PaymentsPreProcessing for Payme {}
+impl PaymentsPreProcessing for Payme {}
-impl
- ConnectorIntegration<
- api::PreProcessing,
- types::PaymentsPreProcessingData,
- types::PaymentsResponseData,
- > for Payme
+impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
+ for Payme
{
fn get_headers(
&self,
- req: &types::PaymentsPreProcessingRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsPreProcessingRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -299,21 +309,20 @@ impl
fn get_url(
&self,
- _req: &types::PaymentsPreProcessingRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsPreProcessingRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/generate-sale", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsPreProcessingRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsPreProcessingRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_amount = req.request.get_minor_amount()?;
let req_currency = req.request.get_currency()?;
- let amount =
- connector_utils::convert_amount(self.amount_converter, req_amount, req_currency)?;
+ let amount = utils::convert_amount(self.amount_converter, req_amount, req_currency)?;
let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?;
let connector_req = payme::GenerateSaleRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -321,20 +330,18 @@ impl
fn build_request(
&self,
- req: &types::PaymentsPreProcessingRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsPreProcessingRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
let req = Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.attach_default_headers()
- .headers(types::PaymentsPreProcessingType::get_headers(
- self, req, connectors,
- )?)
- .url(&types::PaymentsPreProcessingType::get_url(
+ .headers(PaymentsPreProcessingType::get_headers(
self, req, connectors,
)?)
- .set_body(types::PaymentsPreProcessingType::get_request_body(
+ .url(&PaymentsPreProcessingType::get_url(self, req, connectors)?)
+ .set_body(PaymentsPreProcessingType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -344,10 +351,10 @@ impl
fn handle_response(
&self,
- data: &types::PaymentsPreProcessingRouterData,
+ data: &PaymentsPreProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: payme::GenerateSaleResponse = res
.response
.parse_struct("Payme GenerateSaleResponse")
@@ -356,7 +363,7 @@ impl
let req_amount = data.request.get_minor_amount()?;
let req_currency = data.request.get_currency()?;
- let apple_pay_amount = connector_utils::convert_amount(
+ let apple_pay_amount = utils::convert_amount(
self.apple_pay_google_pay_amount_converter,
req_amount,
req_currency,
@@ -365,8 +372,8 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::foreign_try_from((
- types::ResponseRouterData {
+ RouterData::foreign_try_from((
+ ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -393,27 +400,14 @@ impl
}
}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Payme
-{
-}
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Payme {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Payme
-{
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Payme {
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Payme".to_string())
.into(),
@@ -421,35 +415,31 @@ impl
}
}
-impl services::ConnectorRedirectResponse for Payme {
+impl ConnectorRedirectResponse for Payme {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
- action: services::PaymentAction,
- ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ action: enums::PaymentAction,
+ ) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
match action {
- services::PaymentAction::PSync
- | services::PaymentAction::CompleteAuthorize
- | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
- Ok(payments::CallConnectorAction::Trigger)
+ enums::PaymentAction::PSync
+ | enums::PaymentAction::CompleteAuthorize
+ | enums::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
+ Ok(enums::CallConnectorAction::Trigger)
}
}
}
}
-impl
- ConnectorIntegration<
- api::CompleteAuthorize,
- types::CompleteAuthorizeData,
- types::PaymentsResponseData,
- > for Payme
+impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
+ for Payme
{
fn get_headers(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -457,35 +447,35 @@ impl
}
fn get_url(
&self,
- _req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/pay-sale", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCompleteAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payme::Pay3dsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
- req: &types::PaymentsCompleteAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCompleteAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCompleteAuthorizeType::get_url(
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
- .headers(types::PaymentsCompleteAuthorizeType::get_headers(
+ .headers(PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
- .set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
+ .set_body(PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -493,10 +483,10 @@ impl
}
fn handle_response(
&self,
- data: &types::PaymentsCompleteAuthorizeRouterData,
+ data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: payme::PaymePaySaleResponse = res
.response
.parse_struct("Payme PaymePaySaleResponse")
@@ -505,7 +495,7 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -529,23 +519,14 @@ impl
}
}
-impl
- ConnectorIntegration<
- api::InitPayment,
- types::PaymentsAuthorizeData,
- types::PaymentsResponseData,
- > for Payme
-{
-}
+impl ConnectorIntegration<InitPayment, PaymentsAuthorizeData, PaymentsResponseData> for Payme {}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Payme
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Payme {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -555,8 +536,8 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
if req.request.mandate_id.is_some() {
// For recurring mandate payments
@@ -569,10 +550,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
@@ -584,20 +565,16 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -606,10 +583,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: payme::PaymePaySaleResponse = res
.response
.parse_struct("Payme PaymentsAuthorizeResponse")
@@ -618,7 +595,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -643,13 +620,11 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
}
}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Payme
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Payme {
fn get_url(
&self,
- _req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
- connectors: &settings::Connectors,
+ _req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/get-sales", self.base_url(connectors)))
}
@@ -660,16 +635,16 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_headers(
&self,
- req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
- req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
- _connectors: &settings::Connectors,
+ req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payme::PaymeQuerySaleRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -677,35 +652,33 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
- .set_body(types::PaymentsSyncType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsSyncType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
+ data: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
- types::RouterData<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>,
+ RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
errors::ConnectorError,
>
where
- api::PSync: Clone,
- types::PaymentsSyncData: Clone,
- types::PaymentsResponseData: Clone,
+ PSync: Clone,
+ PaymentsSyncData: Clone,
+ PaymentsResponseData: Clone,
{
let response: payme::PaymePaymentsResponse = res
.response
@@ -715,7 +688,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -732,14 +705,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Payme
-{
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Payme {
fn get_headers(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -749,18 +720,18 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn get_url(
&self,
- _req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/capture-sale", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::PaymentsCaptureRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCaptureRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
@@ -772,18 +743,16 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn build_request(
&self,
- req: &types::PaymentsCaptureRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsCaptureRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsCaptureType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsCaptureType::get_request_body(
+ .headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -792,10 +761,10 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
fn handle_response(
&self,
- data: &types::PaymentsCaptureRouterData,
+ data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: payme::PaymePaySaleResponse = res
.response
.parse_struct("Payme PaymentsCaptureResponse")
@@ -804,7 +773,7 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -829,14 +798,12 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
}
}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Payme
-{
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Payme {
fn get_headers(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -846,8 +813,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_url(
&self,
- _req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
// for void, same endpoint is used as refund for payme
Ok(format!("{}api/refund-sale", self.base_url(connectors)))
@@ -855,8 +822,8 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn get_request_body(
&self,
- req: &types::PaymentsCancelRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsCancelRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_amount =
req.request
@@ -870,8 +837,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "amount",
})?;
- let amount =
- connector_utils::convert_amount(self.amount_converter, req_amount, req_currency)?;
+ let amount = utils::convert_amount(self.amount_converter, req_amount, req_currency)?;
let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?;
let connector_req = payme::PaymeVoidRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -879,27 +845,25 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
fn build_request(
&self,
- req: &types::PaymentsCancelRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
+ req: &PaymentsCancelRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&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,
- )?)
+ .headers(PaymentsVoidType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::PaymentsCancelRouterData,
+ data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: payme::PaymeVoidResponse = res
.response
.parse_struct("PaymeVoidResponse")
@@ -908,7 +872,7 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -933,12 +897,12 @@ impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsR
}
}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData> for Payme {
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Payme {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -948,18 +912,18 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ _req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/refund-sale", self.base_url(connectors)))
}
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
@@ -971,29 +935,25 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&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,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: payme::PaymeRefundResponse = res
.response
.parse_struct("PaymeRefundResponse")
@@ -1002,7 +962,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -1027,20 +987,20 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Payme {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Payme {
fn get_url(
&self,
- _req: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
- connectors: &settings::Connectors,
+ _req: &RouterData<RSync, RefundsData, RefundsResponseData>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/get-transactions", self.base_url(connectors)))
}
fn get_headers(
&self,
- req: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<RSync, RefundsData, RefundsResponseData>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -1050,8 +1010,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_request_body(
&self,
- req: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
- _connectors: &settings::Connectors,
+ req: &RouterData<RSync, RefundsData, RefundsResponseData>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payme::PaymeQueryTransactionRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
@@ -1059,34 +1019,29 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ req: &RouterData<RSync, RefundsData, RefundsResponseData>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&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,
- )?)
+ .headers(RefundSyncType::get_headers(self, req, connectors)?)
+ .set_body(RefundSyncType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
+ data: &RouterData<RSync, RefundsData, RefundsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<
- types::RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
- errors::ConnectorError,
- >
+ ) -> CustomResult<RouterData<RSync, RefundsData, RefundsResponseData>, errors::ConnectorError>
where
- api::RSync: Clone,
- types::RefundsData: Clone,
- types::RefundsResponseData: Clone,
+ RSync: Clone,
+ RefundsData: Clone,
+ RefundsResponseData: Clone,
{
let response: payme::PaymeQueryTransactionResponse = res
.response
@@ -1096,7 +1051,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -1122,17 +1077,17 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Payme {
+impl webhooks::IncomingWebhook for Payme {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::Md5))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let resource =
@@ -1143,7 +1098,7 @@ impl api::IncomingWebhook for Payme {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -1162,7 +1117,7 @@ impl api::IncomingWebhook for Payme {
async fn verify_webhook_source(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
@@ -1215,8 +1170,8 @@ impl api::IncomingWebhook for Payme {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let resource =
serde_urlencoded::from_bytes::<payme::WebhookEventDataResource>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
@@ -1226,13 +1181,13 @@ impl api::IncomingWebhook for Payme {
| transformers::NotifyType::SaleFailure
| transformers::NotifyType::SaleChargeback
| transformers::NotifyType::SaleChargebackRefund => {
- api::webhooks::ObjectReferenceId::PaymentId(
+ api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
resource.payme_sale_id,
),
)
}
- transformers::NotifyType::Refund => api::webhooks::ObjectReferenceId::RefundId(
+ transformers::NotifyType::Refund => api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(
resource.payme_transaction_id,
),
@@ -1243,17 +1198,19 @@ impl api::IncomingWebhook for Payme {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let resource =
serde_urlencoded::from_bytes::<payme::WebhookEventDataResourceEvent>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
- Ok(api::IncomingWebhookEvent::from(resource.notify_type))
+ Ok(api_models::webhooks::IncomingWebhookEvent::from(
+ resource.notify_type,
+ ))
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let resource =
serde_urlencoded::from_bytes::<payme::WebhookEventDataResource>(request.body)
@@ -1275,13 +1232,13 @@ impl api::IncomingWebhook for Payme {
fn get_dispute_details(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::disputes::DisputePayload, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<DisputePayload, errors::ConnectorError> {
let webhook_object =
serde_urlencoded::from_bytes::<payme::WebhookEventDataResource>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
- Ok(api::disputes::DisputePayload {
+ Ok(DisputePayload {
amount: webhook_object.price.to_string(),
currency: webhook_object.currency,
dispute_stage: api_models::enums::DisputeStage::Dispute,
diff --git a/crates/router/src/connector/payme/transformers.rs b/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
similarity index 75%
rename from crates/router/src/connector/payme/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
index ec9991b4815..8dd83d1ebd7 100644
--- a/crates/router/src/connector/payme/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/payme/transformers.rs
@@ -1,33 +1,40 @@
use std::collections::HashMap;
use api_models::enums::{AuthenticationType, PaymentMethod};
+use common_enums::enums;
use common_utils::{
pii,
types::{MinorUnit, StringMajorUnit},
};
use error_stack::ResultExt;
+use hyperswitch_domain_models::{
+ payment_method_data::{PaymentMethodData, WalletData},
+ router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
+ router_flow_types::{Execute, Void},
+ router_request_types::{PaymentsCancelData, PaymentsPreProcessingData, ResponseId},
+ router_response_types::{
+ MandateReference, PaymentsResponseData, PreprocessingResponseId, RedirectForm,
+ RefundsResponseData,
+ },
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
+ PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData,
+ PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData,
+ },
+};
+use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
- connector::utils::{
- self, is_payment_failure, is_refund_failure, missing_field_err, AddressDetailsData,
- CardData, PaymentsAuthorizeRequestData, PaymentsCancelRequestData,
- PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingData, PaymentsSyncRequestData,
- RouterData,
- },
- consts,
- core::errors,
- services,
- types::{
- self, api, domain,
- domain::PaymentMethodData,
- storage::enums,
- transformers::{ForeignFrom, ForeignTryFrom},
- MandateReference,
- },
+ types::{PaymentsCancelResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
+ utils::{
+ self, AddressDetailsData, CardData, PaymentsAuthorizeRequestData,
+ PaymentsCancelRequestData, PaymentsCompleteAuthorizeRequestData,
+ PaymentsPreProcessingRequestData, PaymentsSyncRequestData, RouterData as OtherRouterData,
+ },
};
const LANGUAGE: &str = "en";
@@ -155,18 +162,17 @@ pub struct GenerateSaleResponse {
payme_sale_id: String,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, PaymePaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, PaymePaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, PaymePaymentsResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, PaymePaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
match item.response {
// To handle webhook response
PaymePaymentsResponse::PaymePaySaleResponse(response) => {
- Self::try_from(types::ResponseRouterData {
+ Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
@@ -174,7 +180,7 @@ impl<F, T>
}
// To handle PSync response
PaymePaymentsResponse::SaleQueryResponse(response) => {
- Self::try_from(types::ResponseRouterData {
+ Self::try_from(ResponseRouterData {
response,
data: item.data,
http_code: item.http_code,
@@ -184,23 +190,22 @@ impl<F, T>
}
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, PaymePaySaleResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, PaymePaySaleResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, PaymePaySaleResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, PaymePaySaleResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.sale_status.clone());
- let response = if is_payment_failure(status) {
+ let response = if utils::is_payment_failure(status) {
// To populate error message in case of failure
- Err(types::ErrorResponse::foreign_from((
+ Err(get_pay_sale_error_response((
&item.response,
item.http_code,
)))
} else {
- Ok(types::PaymentsResponseData::try_from(&item.response)?)
+ Ok(PaymentsResponseData::try_from(&item.response)?)
};
Ok(Self {
status,
@@ -210,42 +215,39 @@ impl<F, T>
}
}
-impl ForeignFrom<(&PaymePaySaleResponse, u16)> for types::ErrorResponse {
- fn foreign_from((pay_sale_response, http_code): (&PaymePaySaleResponse, u16)) -> Self {
- let code = pay_sale_response
- .status_error_code
- .map(|error_code| error_code.to_string())
- .unwrap_or(consts::NO_ERROR_CODE.to_string());
- Self {
- code,
- message: pay_sale_response
- .status_error_details
- .clone()
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
- reason: pay_sale_response.status_error_details.to_owned(),
- status_code: http_code,
- attempt_status: None,
- connector_transaction_id: Some(pay_sale_response.payme_sale_id.clone()),
- }
+fn get_pay_sale_error_response(
+ (pay_sale_response, http_code): (&PaymePaySaleResponse, u16),
+) -> ErrorResponse {
+ let code = pay_sale_response
+ .status_error_code
+ .map(|error_code| error_code.to_string())
+ .unwrap_or(consts::NO_ERROR_CODE.to_string());
+ ErrorResponse {
+ code,
+ message: pay_sale_response
+ .status_error_details
+ .clone()
+ .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ reason: pay_sale_response.status_error_details.to_owned(),
+ status_code: http_code,
+ attempt_status: None,
+ connector_transaction_id: Some(pay_sale_response.payme_sale_id.clone()),
}
}
-impl TryFrom<&PaymePaySaleResponse> for types::PaymentsResponseData {
+impl TryFrom<&PaymePaySaleResponse> for PaymentsResponseData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(value: &PaymePaySaleResponse) -> Result<Self, Self::Error> {
let redirection_data = match value.sale_3ds {
- Some(true) => value
- .redirect_url
- .clone()
- .map(|url| services::RedirectForm::Form {
- endpoint: url.to_string(),
- method: services::Method::Get,
- form_fields: HashMap::<String, String>::new(),
- }),
+ Some(true) => value.redirect_url.clone().map(|url| RedirectForm::Form {
+ endpoint: url.to_string(),
+ method: common_utils::request::Method::Get,
+ form_fields: HashMap::<String, String>::new(),
+ }),
_ => None,
};
Ok(Self::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(value.payme_sale_id.clone()),
+ resource_id: ResponseId::ConnectorTransactionId(value.payme_sale_id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(value.buyer_key.clone().map(|buyer_key| {
MandateReference {
@@ -264,12 +266,12 @@ impl TryFrom<&PaymePaySaleResponse> for types::PaymentsResponseData {
}
}
-impl<F, T> TryFrom<types::ResponseRouterData<F, SaleQueryResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, SaleQueryResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, SaleQueryResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, SaleQueryResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
// Only one element would be present since we are passing one transaction id in the PSync request
let transaction_response = item
@@ -279,14 +281,14 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SaleQueryResponse, T, types::Pay
.cloned()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let status = enums::AttemptStatus::from(transaction_response.sale_status.clone());
- let response = if is_payment_failure(status) {
+ let response = if utils::is_payment_failure(status) {
// To populate error message in case of failure
- Err(types::ErrorResponse::foreign_from((
+ Err(get_sale_query_error_response((
&transaction_response,
item.http_code,
)))
} else {
- Ok(types::PaymentsResponseData::from(&transaction_response))
+ Ok(PaymentsResponseData::from(&transaction_response))
};
Ok(Self {
status,
@@ -296,29 +298,29 @@ impl<F, T> TryFrom<types::ResponseRouterData<F, SaleQueryResponse, T, types::Pay
}
}
-impl ForeignFrom<(&SaleQuery, u16)> for types::ErrorResponse {
- fn foreign_from((sale_query_response, http_code): (&SaleQuery, u16)) -> Self {
- Self {
- code: sale_query_response
- .sale_error_code
- .clone()
- .unwrap_or(consts::NO_ERROR_CODE.to_string()),
- message: sale_query_response
- .sale_error_text
- .clone()
- .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
- reason: sale_query_response.sale_error_text.clone(),
- status_code: http_code,
- attempt_status: None,
- connector_transaction_id: Some(sale_query_response.sale_payme_id.clone()),
- }
+fn get_sale_query_error_response(
+ (sale_query_response, http_code): (&SaleQuery, u16),
+) -> ErrorResponse {
+ ErrorResponse {
+ code: sale_query_response
+ .sale_error_code
+ .clone()
+ .unwrap_or(consts::NO_ERROR_CODE.to_string()),
+ message: sale_query_response
+ .sale_error_text
+ .clone()
+ .unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
+ reason: sale_query_response.sale_error_text.clone(),
+ status_code: http_code,
+ attempt_status: None,
+ connector_transaction_id: Some(sale_query_response.sale_payme_id.clone()),
}
}
-impl From<&SaleQuery> for types::PaymentsResponseData {
+impl From<&SaleQuery> for PaymentsResponseData {
fn from(value: &SaleQuery) -> Self {
Self::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(value.sale_payme_id.clone()),
+ resource_id: ResponseId::ConnectorTransactionId(value.sale_payme_id.clone()),
redirection_data: Box::new(None),
// mandate reference will be updated with webhooks only. That has been handled with PaymePaySaleResponse struct
mandate_reference: Box::new(None),
@@ -346,10 +348,10 @@ pub enum SalePaymentMethod {
ApplePay,
}
-impl TryFrom<&PaymeRouterData<&types::PaymentsPreProcessingRouterData>> for GenerateSaleRequest {
+impl TryFrom<&PaymeRouterData<&PaymentsPreProcessingRouterData>> for GenerateSaleRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &PaymeRouterData<&types::PaymentsPreProcessingRouterData>,
+ item: &PaymeRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<Self, Self::Error> {
let sale_type = SaleType::try_from(item.router_data)?;
let seller_payme_id =
@@ -358,7 +360,7 @@ impl TryFrom<&PaymeRouterData<&types::PaymentsPreProcessingRouterData>> for Gene
let services = get_services(item.router_data);
let product_name = order_details
.first()
- .ok_or_else(missing_field_err("order_details"))?
+ .ok_or_else(utils::missing_field_err("order_details"))?
.product_name
.clone();
let pmd = item
@@ -366,7 +368,7 @@ impl TryFrom<&PaymeRouterData<&types::PaymentsPreProcessingRouterData>> for Gene
.request
.payment_method_data
.to_owned()
- .ok_or_else(missing_field_err("payment_method_data"))?;
+ .ok_or_else(utils::missing_field_err("payment_method_data"))?;
Ok(Self {
seller_payme_id,
sale_price: item.amount.to_owned(),
@@ -389,35 +391,35 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod {
match item {
PaymentMethodData::Card(_) => Ok(Self::CreditCard),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
- domain::WalletData::ApplePayThirdPartySdk(_) => Ok(Self::ApplePay),
- domain::WalletData::AliPayQr(_)
- | domain::WalletData::AliPayRedirect(_)
- | domain::WalletData::AliPayHkRedirect(_)
- | domain::WalletData::AmazonPayRedirect(_)
- | domain::WalletData::MomoRedirect(_)
- | domain::WalletData::KakaoPayRedirect(_)
- | domain::WalletData::GoPayRedirect(_)
- | domain::WalletData::GcashRedirect(_)
- | domain::WalletData::ApplePayRedirect(_)
- | domain::WalletData::DanaRedirect {}
- | domain::WalletData::GooglePay(_)
- | domain::WalletData::GooglePayRedirect(_)
- | domain::WalletData::GooglePayThirdPartySdk(_)
- | domain::WalletData::MbWayRedirect(_)
- | domain::WalletData::MobilePayRedirect(_)
- | domain::WalletData::PaypalRedirect(_)
- | domain::WalletData::PaypalSdk(_)
- | domain::WalletData::Paze(_)
- | domain::WalletData::SamsungPay(_)
- | domain::WalletData::TwintRedirect {}
- | domain::WalletData::VippsRedirect {}
- | domain::WalletData::TouchNGoRedirect(_)
- | domain::WalletData::WeChatPayRedirect(_)
- | domain::WalletData::WeChatPayQr(_)
- | domain::WalletData::CashappQr(_)
- | domain::WalletData::ApplePay(_)
- | domain::WalletData::SwishQr(_)
- | domain::WalletData::Mifinity(_) => Err(errors::ConnectorError::NotSupported {
+ WalletData::ApplePayThirdPartySdk(_) => Ok(Self::ApplePay),
+ WalletData::AliPayQr(_)
+ | WalletData::AliPayRedirect(_)
+ | WalletData::AliPayHkRedirect(_)
+ | WalletData::AmazonPayRedirect(_)
+ | WalletData::MomoRedirect(_)
+ | WalletData::KakaoPayRedirect(_)
+ | WalletData::GoPayRedirect(_)
+ | WalletData::GcashRedirect(_)
+ | WalletData::ApplePayRedirect(_)
+ | WalletData::DanaRedirect {}
+ | WalletData::GooglePay(_)
+ | WalletData::GooglePayRedirect(_)
+ | WalletData::GooglePayThirdPartySdk(_)
+ | WalletData::MbWayRedirect(_)
+ | WalletData::MobilePayRedirect(_)
+ | WalletData::PaypalRedirect(_)
+ | WalletData::PaypalSdk(_)
+ | WalletData::Paze(_)
+ | WalletData::SamsungPay(_)
+ | WalletData::TwintRedirect {}
+ | WalletData::VippsRedirect {}
+ | WalletData::TouchNGoRedirect(_)
+ | WalletData::WeChatPayRedirect(_)
+ | WalletData::WeChatPayQr(_)
+ | WalletData::CashappQr(_)
+ | WalletData::ApplePay(_)
+ | WalletData::SwishQr(_)
+ | WalletData::Mifinity(_) => Err(errors::ConnectorError::NotSupported {
message: "Wallet".to_string(),
connector: "payme",
}
@@ -446,10 +448,10 @@ impl TryFrom<&PaymentMethodData> for SalePaymentMethod {
}
}
-impl TryFrom<&PaymeRouterData<&types::PaymentsAuthorizeRouterData>> for PaymePaymentRequest {
+impl TryFrom<&PaymeRouterData<&PaymentsAuthorizeRouterData>> for PaymePaymentRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- value: &PaymeRouterData<&types::PaymentsAuthorizeRouterData>,
+ value: &PaymeRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payme_request = if value.router_data.request.mandate_id.is_some() {
Self::MandateRequest(MandateRequest::try_from(value)?)
@@ -460,9 +462,9 @@ impl TryFrom<&PaymeRouterData<&types::PaymentsAuthorizeRouterData>> for PaymePay
}
}
-impl TryFrom<&types::PaymentsSyncRouterData> for PaymeQuerySaleRequest {
+impl TryFrom<&PaymentsSyncRouterData> for PaymeQuerySaleRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: &types::PaymentsSyncRouterData) -> Result<Self, Self::Error> {
+ fn try_from(value: &PaymentsSyncRouterData) -> Result<Self, Self::Error> {
let seller_payme_id = PaymeAuthType::try_from(&value.connector_auth_type)?.seller_payme_id;
Ok(Self {
sale_payme_id: value.request.get_connector_transaction_id()?,
@@ -471,9 +473,9 @@ impl TryFrom<&types::PaymentsSyncRouterData> for PaymeQuerySaleRequest {
}
}
-impl TryFrom<&types::RefundSyncRouterData> for PaymeQueryTransactionRequest {
+impl TryFrom<&RefundSyncRouterData> for PaymeQueryTransactionRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: &types::RefundSyncRouterData) -> Result<Self, Self::Error> {
+ fn try_from(value: &RefundSyncRouterData) -> Result<Self, Self::Error> {
let seller_payme_id = PaymeAuthType::try_from(&value.connector_auth_type)?.seller_payme_id;
Ok(Self {
payme_transaction_id: value
@@ -487,24 +489,24 @@ impl TryFrom<&types::RefundSyncRouterData> for PaymeQueryTransactionRequest {
}
impl<F>
- ForeignTryFrom<(
- types::ResponseRouterData<
+ utils::ForeignTryFrom<(
+ ResponseRouterData<
F,
GenerateSaleResponse,
- types::PaymentsPreProcessingData,
- types::PaymentsResponseData,
+ PaymentsPreProcessingData,
+ PaymentsResponseData,
>,
StringMajorUnit,
- )> for types::RouterData<F, types::PaymentsPreProcessingData, types::PaymentsResponseData>
+ )> for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, apple_pay_amount): (
- types::ResponseRouterData<
+ ResponseRouterData<
F,
GenerateSaleResponse,
- types::PaymentsPreProcessingData,
- types::PaymentsResponseData,
+ PaymentsPreProcessingData,
+ PaymentsResponseData,
>,
StringMajorUnit,
),
@@ -518,11 +520,10 @@ impl<F>
// then move to authorize flow
status: enums::AttemptStatus::Pending,
preprocessing_id: Some(item.response.payme_sale_id.to_owned()),
- response: Ok(types::PaymentsResponseData::PreProcessingResponse {
- pre_processing_id:
- types::PreprocessingResponseId::ConnectorTransactionId(
- item.response.payme_sale_id,
- ),
+ response: Ok(PaymentsResponseData::PreProcessingResponse {
+ pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(
+ item.response.payme_sale_id,
+ ),
connector_metadata: None,
session_token: None,
connector_response_reference_id: None,
@@ -537,11 +538,11 @@ impl<F>
// status is made authentication_pending to show redirection
status: enums::AttemptStatus::AuthenticationPending,
preprocessing_id: Some(item.response.payme_sale_id.to_owned()),
- response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
item.response.payme_sale_id.to_owned(),
),
- redirection_data: Box::new(Some(services::RedirectForm::Payme)),
+ redirection_data: Box::new(Some(RedirectForm::Payme)),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
@@ -559,7 +560,7 @@ impl<F>
let payme_auth_type = PaymeAuthType::try_from(&item.data.connector_auth_type)?;
let session_token = match pmd {
- Some(PaymentMethodData::Wallet(domain::WalletData::ApplePayThirdPartySdk(
+ Some(PaymentMethodData::Wallet(WalletData::ApplePayThirdPartySdk(
_,
))) => Some(api_models::payments::SessionToken::ApplePay(Box::new(
api_models::payments::ApplepaySessionTokenResponse {
@@ -603,8 +604,8 @@ impl<F>
// We don't get any status from payme, so defaulting it to pending
status: enums::AttemptStatus::Pending,
preprocessing_id: Some(item.response.payme_sale_id.to_owned()),
- response: Ok(types::PaymentsResponseData::PreProcessingResponse {
- pre_processing_id: types::PreprocessingResponseId::ConnectorTransactionId(
+ response: Ok(PaymentsResponseData::PreProcessingResponse {
+ pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(
item.response.payme_sale_id,
),
connector_metadata: None,
@@ -618,17 +619,15 @@ impl<F>
}
}
-impl TryFrom<&PaymeRouterData<&types::PaymentsAuthorizeRouterData>> for MandateRequest {
+impl TryFrom<&PaymeRouterData<&PaymentsAuthorizeRouterData>> for MandateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &PaymeRouterData<&types::PaymentsAuthorizeRouterData>,
- ) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymeRouterData<&PaymentsAuthorizeRouterData>) -> Result<Self, Self::Error> {
let seller_payme_id =
PaymeAuthType::try_from(&item.router_data.connector_auth_type)?.seller_payme_id;
let order_details = item.router_data.request.get_order_details()?;
let product_name = order_details
.first()
- .ok_or_else(missing_field_err("order_details"))?
+ .ok_or_else(utils::missing_field_err("order_details"))?
.product_name
.clone();
Ok(Self {
@@ -645,9 +644,9 @@ impl TryFrom<&PaymeRouterData<&types::PaymentsAuthorizeRouterData>> for MandateR
}
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for PayRequest {
+impl TryFrom<&PaymentsAuthorizeRouterData> for PayRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let card = PaymeCard {
@@ -701,9 +700,9 @@ pub struct PaymeRedirectResponseData {
meta_data: String,
}
-impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest {
+impl TryFrom<&PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymentsCompleteAuthorizeRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
Some(PaymentMethodData::Card(_)) => {
let buyer_email = item.request.get_email()?;
@@ -722,18 +721,19 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest {
.clone()
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?;
let pm_token = item.get_payment_method_token()?;
- let buyer_key = match pm_token {
- types::PaymentMethodToken::Token(token) => token,
- types::PaymentMethodToken::ApplePayDecrypt(_) => Err(
- unimplemented_payment_method!("Apple Pay", "Simplified", "Payme"),
- )?,
- types::PaymentMethodToken::PazeDecrypt(_) => {
- Err(unimplemented_payment_method!("Paze", "Payme"))?
- }
- types::PaymentMethodToken::GooglePayDecrypt(_) => {
- Err(unimplemented_payment_method!("Google Pay", "Payme"))?
- }
- };
+ let buyer_key =
+ match pm_token {
+ PaymentMethodToken::Token(token) => token,
+ PaymentMethodToken::ApplePayDecrypt(_) => Err(
+ unimplemented_payment_method!("Apple Pay", "Simplified", "Payme"),
+ )?,
+ PaymentMethodToken::PazeDecrypt(_) => {
+ Err(unimplemented_payment_method!("Paze", "Payme"))?
+ }
+ PaymentMethodToken::GooglePayDecrypt(_) => {
+ Err(unimplemented_payment_method!("Google Pay", "Payme"))?
+ }
+ };
Ok(Self {
buyer_email,
buyer_key,
@@ -767,9 +767,9 @@ impl TryFrom<&types::PaymentsCompleteAuthorizeRouterData> for Pay3dsRequest {
}
}
-impl TryFrom<&types::TokenizationRouterData> for CaptureBuyerRequest {
+impl TryFrom<&TokenizationRouterData> for CaptureBuyerRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::TokenizationRouterData) -> Result<Self, Self::Error> {
+ fn try_from(item: &TokenizationRouterData) -> Result<Self, Self::Error> {
match item.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
let seller_payme_id =
@@ -817,16 +817,16 @@ pub struct PaymeAuthType {
pub(super) payme_merchant_id: Option<Secret<String>>,
}
-impl TryFrom<&types::ConnectorAuthType> for PaymeAuthType {
+impl TryFrom<&ConnectorAuthType> for PaymeAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
- types::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
+ ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
seller_payme_id: api_key.to_owned(),
payme_public_key: key1.to_owned(),
payme_merchant_id: None,
}),
- types::ConnectorAuthType::SignatureKey {
+ ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
@@ -840,9 +840,9 @@ impl TryFrom<&types::ConnectorAuthType> for PaymeAuthType {
}
}
-impl TryFrom<&types::PaymentsPreProcessingRouterData> for SaleType {
+impl TryFrom<&PaymentsPreProcessingRouterData> for SaleType {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(value: &types::PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
+ fn try_from(value: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
let sale_type = if value.request.setup_mandate_details.is_some() {
// First mandate
Self::Token
@@ -922,19 +922,16 @@ pub struct PaymeMetadata {
payme_transaction_id: Option<String>,
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, CaptureBuyerResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, CaptureBuyerResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<F, CaptureBuyerResponse, T, types::PaymentsResponseData>,
+ item: ResponseRouterData<F, CaptureBuyerResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
- payment_method_token: Some(types::PaymentMethodToken::Token(
- item.response.buyer_key.clone(),
- )),
- response: Ok(types::PaymentsResponseData::TokenizationResponse {
+ payment_method_token: Some(PaymentMethodToken::Token(item.response.buyer_key.clone())),
+ response: Ok(PaymentsResponseData::TokenizationResponse {
token: item.response.buyer_key.expose(),
}),
..item.data
@@ -948,11 +945,9 @@ pub struct PaymentCaptureRequest {
sale_price: MinorUnit,
}
-impl TryFrom<&PaymeRouterData<&types::PaymentsCaptureRouterData>> for PaymentCaptureRequest {
+impl TryFrom<&PaymeRouterData<&PaymentsCaptureRouterData>> for PaymentCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(
- item: &PaymeRouterData<&types::PaymentsCaptureRouterData>,
- ) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymeRouterData<&PaymentsCaptureRouterData>) -> Result<Self, Self::Error> {
if item.router_data.request.minor_amount_to_capture
!= item.router_data.request.minor_payment_amount
{
@@ -978,9 +973,9 @@ pub struct PaymeRefundRequest {
language: String,
}
-impl<F> TryFrom<&PaymeRouterData<&types::RefundsRouterData<F>>> for PaymeRefundRequest {
+impl<F> TryFrom<&PaymeRouterData<&RefundsRouterData<F>>> for PaymeRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &PaymeRouterData<&types::RefundsRouterData<F>>) -> Result<Self, Self::Error> {
+ fn try_from(item: &PaymeRouterData<&RefundsRouterData<F>>) -> 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(),
@@ -1014,20 +1009,20 @@ pub struct PaymeRefundResponse {
status_error_code: Option<u32>,
}
-impl TryFrom<types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse>>
- for types::RefundsRouterData<api::Execute>
+impl TryFrom<RefundsResponseRouterData<Execute, PaymeRefundResponse>>
+ for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse>,
+ item: RefundsResponseRouterData<Execute, PaymeRefundResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::try_from(item.response.sale_status.clone())?;
- let response = if is_refund_failure(refund_status) {
+ let response = if utils::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 {
+ Err(ErrorResponse {
code: status_error_code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
@@ -1040,7 +1035,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, PaymeRefundResponse>
connector_transaction_id: payme_response.payme_transaction_id.clone(),
})
} else {
- Ok(types::RefundsResponseData {
+ Ok(RefundsResponseData {
connector_refund_id: item
.response
.payme_transaction_id
@@ -1063,18 +1058,12 @@ pub struct PaymeVoidRequest {
language: String,
}
-impl
- TryFrom<
- &PaymeRouterData<
- &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
- >,
- > for PaymeVoidRequest
+impl TryFrom<&PaymeRouterData<&RouterData<Void, PaymentsCancelData, PaymentsResponseData>>>
+ for PaymeVoidRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: &PaymeRouterData<
- &types::RouterData<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>,
- >,
+ item: &PaymeRouterData<&RouterData<Void, PaymentsCancelData, PaymentsResponseData>>,
) -> Result<Self, Self::Error> {
let auth_type = PaymeAuthType::try_from(&item.router_data.connector_auth_type)?;
Ok(Self {
@@ -1093,20 +1082,18 @@ pub struct PaymeVoidResponse {
status_error_code: Option<u32>,
}
-impl TryFrom<types::PaymentsCancelResponseRouterData<PaymeVoidResponse>>
- for types::PaymentsCancelRouterData
-{
+impl TryFrom<PaymentsCancelResponseRouterData<PaymeVoidResponse>> for PaymentsCancelRouterData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::PaymentsCancelResponseRouterData<PaymeVoidResponse>,
+ item: PaymentsCancelResponseRouterData<PaymeVoidResponse>,
) -> Result<Self, Self::Error> {
let status = enums::AttemptStatus::from(item.response.sale_status.clone());
- let response = if is_payment_failure(status) {
+ let response = if utils::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 {
+ Err(ErrorResponse {
code: status_error_code
.clone()
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
@@ -1120,8 +1107,8 @@ impl TryFrom<types::PaymentsCancelResponseRouterData<PaymeVoidResponse>>
})
} 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,
+ Ok(PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
@@ -1150,19 +1137,12 @@ pub struct TransactionQuery {
payme_transaction_id: String,
}
-impl<F, T>
- TryFrom<
- types::ResponseRouterData<F, PaymeQueryTransactionResponse, T, types::RefundsResponseData>,
- > for types::RouterData<F, T, types::RefundsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, PaymeQueryTransactionResponse, T, RefundsResponseData>>
+ for RouterData<F, T, RefundsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
- item: types::ResponseRouterData<
- F,
- PaymeQueryTransactionResponse,
- T,
- types::RefundsResponseData,
- >,
+ item: ResponseRouterData<F, PaymeQueryTransactionResponse, T, RefundsResponseData>,
) -> Result<Self, Self::Error> {
let pay_sale_response = item
.response
@@ -1170,8 +1150,8 @@ impl<F, T>
.first()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let refund_status = enums::RefundStatus::try_from(pay_sale_response.sale_status.clone())?;
- let response = if is_refund_failure(refund_status) {
- Err(types::ErrorResponse {
+ let response = if utils::is_refund_failure(refund_status) {
+ Err(ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(),
message: consts::NO_ERROR_CODE.to_string(),
reason: None,
@@ -1180,7 +1160,7 @@ impl<F, T>
connector_transaction_id: Some(pay_sale_response.payme_transaction_id.clone()),
})
} else {
- Ok(types::RefundsResponseData {
+ Ok(RefundsResponseData {
refund_status,
connector_refund_id: pay_sale_response.payme_transaction_id.clone(),
})
@@ -1192,7 +1172,7 @@ impl<F, T>
}
}
-fn get_services(item: &types::PaymentsPreProcessingRouterData) -> Option<ThreeDs> {
+fn get_services(item: &PaymentsPreProcessingRouterData) -> Option<ThreeDs> {
match item.auth_type {
AuthenticationType::ThreeDs => {
let settings = ThreeDsSettings { active: true };
@@ -1275,7 +1255,7 @@ impl From<WebhookEventDataResource> for PaymeQueryTransactionResponse {
}
}
-impl From<NotifyType> for api::IncomingWebhookEvent {
+impl From<NotifyType> for api_models::webhooks::IncomingWebhookEvent {
fn from(value: NotifyType) -> Self {
match value {
NotifyType::SaleComplete => Self::PaymentIntentSuccess,
diff --git a/crates/router/src/connector/trustpay.rs b/crates/hyperswitch_connectors/src/connectors/trustpay.rs
similarity index 72%
rename from crates/router/src/connector/trustpay.rs
rename to crates/hyperswitch_connectors/src/connectors/trustpay.rs
index 10c71a5d375..b3f2c1f9c3e 100644
--- a/crates/router/src/connector/trustpay.rs
+++ b/crates/hyperswitch_connectors/src/connectors/trustpay.rs
@@ -1,42 +1,57 @@
pub mod transformers;
use base64::Engine;
+use common_enums::{enums, PaymentAction};
use common_utils::{
crypto,
- errors::ReportSwitchExt,
+ errors::{CustomResult, ReportSwitchExt},
ext_traits::ByteSliceExt,
- request::RequestContent,
+ request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{Report, ResultExt};
-use masking::PeekInterface;
-use transformers as trustpay;
-
-use super::utils::{
- self as connector_utils, collect_and_sort_values_by_removing_signature,
- get_error_code_error_message_based_on_priority, ConnectorErrorType, ConnectorErrorTypeMapping,
- PaymentsPreProcessingData,
+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},
+ PreProcessing,
+ },
+ router_request_types::{
+ AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
+ PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData,
+ PaymentsSyncData, RefundsData, SetupMandateRequestData,
+ },
+ router_response_types::{PaymentsResponseData, RefundsResponseData},
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData,
+ RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData,
+ },
};
-use crate::{
- configs::settings,
- consts,
- core::{
- errors::{self, CustomResult},
- payments,
+use hyperswitch_interfaces::{
+ api::{
+ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
+ ConnectorSpecifications, ConnectorValidation,
},
+ configs::Connectors,
+ consts,
+ disputes::DisputePayload,
+ errors,
events::connector_api_logs::ConnectorEvent,
- headers, logger,
- services::{
- self,
- request::{self, Mask},
- ConnectorIntegration, ConnectorSpecifications, ConnectorValidation,
- },
types::{
- self,
- api::{self, ConnectorCommon, ConnectorCommonExt},
- ErrorResponse, Response,
+ PaymentsAuthorizeType, PaymentsPreProcessingType, PaymentsSyncType, RefreshTokenType,
+ RefundExecuteType, RefundSyncType, Response,
},
- utils::{self, BytesExt},
+ webhooks,
+};
+use masking::{Mask, PeekInterface};
+use transformers as trustpay;
+
+use crate::{
+ constants::headers,
+ types::ResponseRouterData,
+ utils::{self, ConnectorErrorType, PaymentsPreProcessingRequestData},
};
#[derive(Clone)]
@@ -58,11 +73,11 @@ where
{
fn build_headers(
&self,
- req: &types::RouterData<Flow, Request, Response>,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RouterData<Flow, Request, Response>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
match req.payment_method {
- diesel_models::enums::PaymentMethod::BankRedirect => {
+ enums::PaymentMethod::BankRedirect => {
let token = req
.access_token
.clone()
@@ -104,14 +119,14 @@ impl ConnectorCommon for Trustpay {
"application/x-www-form-urlencoded"
}
- fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.trustpay.base_url.as_ref()
}
fn get_auth_header(
&self,
- auth_type: &types::ConnectorAuthType,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = trustpay::TrustpayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
@@ -135,10 +150,11 @@ impl ConnectorCommon for Trustpay {
event_builder.map(|i| i.set_error_response_body(&response_data));
router_env::logger::info!(connector_response=?response_data);
let error_list = response_data.errors.clone().unwrap_or_default();
- let option_error_code_message = get_error_code_error_message_based_on_priority(
- self.clone(),
- error_list.into_iter().map(|errors| errors.into()).collect(),
- );
+ let option_error_code_message =
+ utils::get_error_code_error_message_based_on_priority(
+ self.clone(),
+ error_list.into_iter().map(|errors| errors.into()).collect(),
+ );
let reason = response_data.errors.map(|errors| {
errors
.iter()
@@ -165,7 +181,7 @@ impl ConnectorCommon for Trustpay {
}
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
- logger::error!(deserialization_error =? error_msg);
+ router_env::logger::error!(deserialization_error =? error_msg);
utils::handle_json_response_deserialization_failure(res, "trustpay")
}
}
@@ -178,33 +194,21 @@ impl api::Payment for Trustpay {}
impl api::PaymentToken for Trustpay {}
-impl
- ConnectorIntegration<
- api::PaymentMethodToken,
- types::PaymentMethodTokenizationData,
- types::PaymentsResponseData,
- > for Trustpay
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Trustpay
{
// Not Implemented (R)
}
impl api::MandateSetup for Trustpay {}
-impl
- ConnectorIntegration<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- > for Trustpay
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Trustpay
{
fn build_request(
&self,
- _req: &types::RouterData<
- api::SetupMandate,
- types::SetupMandateRequestData,
- types::PaymentsResponseData,
- >,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ _req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
+ _connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Trustpay".to_string())
.into(),
@@ -214,20 +218,15 @@ impl
impl api::PaymentVoid for Trustpay {}
-impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
- for Trustpay
-{
-}
+impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Trustpay {}
impl api::ConnectorAccessToken for Trustpay {}
-impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
- for Trustpay
-{
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Trustpay {
fn get_url(
&self,
- _req: &types::RefreshTokenRouterData,
- connectors: &settings::Connectors,
+ _req: &RefreshTokenRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
@@ -241,9 +240,9 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn get_headers(
&self,
- req: &types::RefreshTokenRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefreshTokenRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = trustpay::TrustpayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_value = auth
@@ -252,15 +251,14 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
.map(|(project_id, secret_key)| {
format!(
"Basic {}",
- consts::BASE64_ENGINE.encode(format!("{}:{}", project_id, secret_key))
+ common_utils::consts::BASE64_ENGINE
+ .encode(format!("{}:{}", project_id, secret_key))
)
});
Ok(vec![
(
headers::CONTENT_TYPE.to_string(),
- types::RefreshTokenType::get_content_type(self)
- .to_string()
- .into(),
+ RefreshTokenType::get_content_type(self).to_string().into(),
),
(headers::AUTHORIZATION.to_string(), auth_value.into_masked()),
])
@@ -268,8 +266,8 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn get_request_body(
&self,
- req: &types::RefreshTokenRouterData,
- _connectors: &settings::Connectors,
+ req: &RefreshTokenRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = trustpay::TrustpayAuthUpdateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
@@ -277,18 +275,16 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn build_request(
&self,
- req: &types::RefreshTokenRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefreshTokenRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
let req = Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.attach_default_headers()
- .headers(types::RefreshTokenType::get_headers(self, req, connectors)?)
- .url(&types::RefreshTokenType::get_url(self, req, connectors)?)
- .set_body(types::RefreshTokenType::get_request_body(
- self, req, connectors,
- )?)
+ .headers(RefreshTokenType::get_headers(self, req, connectors)?)
+ .url(&RefreshTokenType::get_url(self, req, connectors)?)
+ .set_body(RefreshTokenType::get_request_body(self, req, connectors)?)
.build(),
);
Ok(req)
@@ -296,10 +292,10 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
fn handle_response(
&self,
- data: &types::RefreshTokenRouterData,
+ data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefreshTokenRouterData, errors::ConnectorError> {
+ ) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: trustpay::TrustpayAuthUpdateResponse = res
.response
.parse_struct("trustpay TrustpayAuthUpdateResponse")
@@ -308,7 +304,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -342,14 +338,12 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
}
impl api::PaymentSync for Trustpay {}
-impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
- for Trustpay
-{
+impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Trustpay {
fn get_headers(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -359,12 +353,12 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn get_url(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.clone();
match req.payment_method {
- diesel_models::enums::PaymentMethod::BankRedirect => Ok(format!(
+ enums::PaymentMethod::BankRedirect => Ok(format!(
"{}{}/{}",
connectors.trustpay.base_url_bank_redirects,
"api/Payments/Payment",
@@ -383,15 +377,15 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn build_request(
&self,
- req: &types::PaymentsSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
@@ -406,10 +400,10 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
fn handle_response(
&self,
- data: &types::PaymentsSyncRouterData,
+ data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: trustpay::TrustpayPaymentsResponse = res
.response
.parse_struct("trustpay PaymentsResponse")
@@ -418,7 +412,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -428,28 +422,21 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
}
impl api::PaymentCapture for Trustpay {}
-impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
- for Trustpay
-{
-}
+impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Trustpay {}
impl api::PaymentsPreProcessing for Trustpay {}
-impl
- ConnectorIntegration<
- api::PreProcessing,
- types::PaymentsPreProcessingData,
- types::PaymentsResponseData,
- > for Trustpay
+impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
+ for Trustpay
{
fn get_headers(
&self,
- req: &types::PaymentsPreProcessingRouterData,
- _connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsPreProcessingRouterData,
+ _connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
- types::PaymentsPreProcessingType::get_content_type(self)
+ PaymentsPreProcessingType::get_content_type(self)
.to_string()
.into(),
)];
@@ -464,22 +451,21 @@ impl
fn get_url(
&self,
- _req: &types::PaymentsPreProcessingRouterData,
- connectors: &settings::Connectors,
+ _req: &PaymentsPreProcessingRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "api/v1/intent"))
}
fn get_request_body(
&self,
- req: &types::PaymentsPreProcessingRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsPreProcessingRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_currency = req.request.get_currency()?;
let req_amount = req.request.get_minor_amount()?;
- let amount =
- connector_utils::convert_amount(self.amount_converter, req_amount, req_currency)?;
+ let amount = utils::convert_amount(self.amount_converter, req_amount, req_currency)?;
let connector_router_data = trustpay::TrustpayRouterData::try_from((amount, req))?;
let connector_req =
@@ -489,20 +475,18 @@ impl
fn build_request(
&self,
- req: &types::PaymentsPreProcessingRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsPreProcessingRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
let req = Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
+ RequestBuilder::new()
+ .method(Method::Post)
.attach_default_headers()
- .headers(types::PaymentsPreProcessingType::get_headers(
+ .headers(PaymentsPreProcessingType::get_headers(
self, req, connectors,
)?)
- .url(&types::PaymentsPreProcessingType::get_url(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsPreProcessingType::get_request_body(
+ .url(&PaymentsPreProcessingType::get_url(self, req, connectors)?)
+ .set_body(PaymentsPreProcessingType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -512,10 +496,10 @@ impl
fn handle_response(
&self,
- data: &types::PaymentsPreProcessingRouterData,
+ data: &PaymentsPreProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsPreProcessingRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: trustpay::TrustpayCreateIntentResponse = res
.response
.parse_struct("TrustpayCreateIntentResponse")
@@ -524,7 +508,7 @@ impl
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -543,21 +527,16 @@ impl
impl api::PaymentSession for Trustpay {}
-impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
- for Trustpay
-{
-}
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Trustpay {}
impl api::PaymentAuthorize for Trustpay {}
-impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
- for Trustpay
-{
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Trustpay {
fn get_headers(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -567,11 +546,11 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_url(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
match req.payment_method {
- diesel_models::enums::PaymentMethod::BankRedirect => Ok(format!(
+ enums::PaymentMethod::BankRedirect => Ok(format!(
"{}{}",
connectors.trustpay.base_url_bank_redirects, "api/Payments/Payment"
)),
@@ -585,10 +564,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn get_request_body(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- _connectors: &settings::Connectors,
+ req: &PaymentsAuthorizeRouterData,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
@@ -596,29 +575,23 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
let connector_router_data = trustpay::TrustpayRouterData::try_from((amount, req))?;
let connector_req = trustpay::TrustpayPaymentsRequest::try_from(&connector_router_data)?;
match req.payment_method {
- diesel_models::enums::PaymentMethod::BankRedirect => {
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
+ enums::PaymentMethod::BankRedirect => Ok(RequestContent::Json(Box::new(connector_req))),
_ => Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))),
}
}
fn build_request(
&self,
- req: &types::PaymentsAuthorizeRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &PaymentsAuthorizeRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::PaymentsAuthorizeType::get_url(
- self, req, connectors,
- )?)
+ RequestBuilder::new()
+ .method(Method::Post)
+ .url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::PaymentsAuthorizeType::get_headers(
- self, req, connectors,
- )?)
- .set_body(types::PaymentsAuthorizeType::get_request_body(
+ .headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
+ .set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
@@ -627,10 +600,10 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
fn handle_response(
&self,
- data: &types::PaymentsAuthorizeRouterData,
+ data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ ) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: trustpay::TrustpayPaymentsResponse = res
.response
.parse_struct("trustpay PaymentsResponse")
@@ -639,7 +612,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -660,14 +633,12 @@ impl api::Refund for Trustpay {}
impl api::RefundExecute for Trustpay {}
impl api::RefundSync for Trustpay {}
-impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
- for Trustpay
-{
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Trustpay {
fn get_headers(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -677,11 +648,11 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
match req.payment_method {
- diesel_models::enums::PaymentMethod::BankRedirect => Ok(format!(
+ enums::PaymentMethod::BankRedirect => Ok(format!(
"{}{}{}{}",
connectors.trustpay.base_url_bank_redirects,
"api/Payments/Payment/",
@@ -694,10 +665,10 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_request_body(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &RefundsRouterData<Execute>,
+ _connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
- let amount = connector_utils::convert_amount(
+ let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
@@ -706,38 +677,32 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
let connector_router_data = trustpay::TrustpayRouterData::try_from((amount, req))?;
let connector_req = trustpay::TrustpayRefundRequest::try_from(&connector_router_data)?;
match req.payment_method {
- diesel_models::enums::PaymentMethod::BankRedirect => {
- Ok(RequestContent::Json(Box::new(connector_req)))
- }
+ enums::PaymentMethod::BankRedirect => Ok(RequestContent::Json(Box::new(connector_req))),
_ => Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))),
}
}
fn build_request(
&self,
- req: &types::RefundsRouterData<api::Execute>,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
- let request = services::RequestBuilder::new()
- .method(services::Method::Post)
- .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ req: &RefundsRouterData<Execute>,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
+ let request = RequestBuilder::new()
+ .method(Method::Post)
+ .url(&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,
- )?)
+ .headers(RefundExecuteType::get_headers(self, req, connectors)?)
+ .set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
- data: &types::RefundsRouterData<api::Execute>,
+ data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ ) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: trustpay::RefundResponse = res
.response
.parse_struct("trustpay RefundResponse")
@@ -746,7 +711,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -763,12 +728,12 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
}
}
-impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData> for Trustpay {
+impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Trustpay {
fn get_headers(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
@@ -778,8 +743,8 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req
.request
@@ -787,7 +752,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
.to_owned()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
match req.payment_method {
- diesel_models::enums::PaymentMethod::BankRedirect => Ok(format!(
+ enums::PaymentMethod::BankRedirect => Ok(format!(
"{}{}/{}",
connectors.trustpay.base_url_bank_redirects, "api/Payments/Payment", id
)),
@@ -802,25 +767,25 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn build_request(
&self,
- req: &types::RefundSyncRouterData,
- connectors: &settings::Connectors,
- ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ req: &RefundSyncRouterData,
+ connectors: &Connectors,
+ ) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
- services::RequestBuilder::new()
- .method(services::Method::Get)
- .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ RequestBuilder::new()
+ .method(Method::Get)
+ .url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
- .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
- data: &types::RefundSyncRouterData,
+ data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
- ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ ) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: trustpay::RefundResponse = res
.response
.parse_struct("trustpay RefundResponse")
@@ -829,7 +794,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
- types::RouterData::try_from(types::ResponseRouterData {
+ RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
@@ -847,10 +812,10 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
}
#[async_trait::async_trait]
-impl api::IncomingWebhook for Trustpay {
+impl webhooks::IncomingWebhook for Trustpay {
fn get_webhook_object_reference_id(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let details: trustpay::TrustpayWebhookResponse = request
.body
@@ -884,8 +849,8 @@ impl api::IncomingWebhook for Trustpay {
fn get_webhook_event_type(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let response: trustpay::TrustpayWebhookResponse = request
.body
.parse_struct("TrustpayWebhookResponse")
@@ -916,19 +881,19 @@ impl api::IncomingWebhook for Trustpay {
(
trustpay::CreditDebitIndicator::Dbit | trustpay::CreditDebitIndicator::Crdt,
trustpay::WebhookStatus::Unknown,
- ) => Ok(api::IncomingWebhookEvent::EventNotSupported),
+ ) => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),
(trustpay::CreditDebitIndicator::Crdt, trustpay::WebhookStatus::Refunded) => {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
(trustpay::CreditDebitIndicator::Crdt, trustpay::WebhookStatus::Chargebacked) => {
- Ok(api::IncomingWebhookEvent::EventNotSupported)
+ Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
}
}
fn get_webhook_resource_object(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let details: trustpay::TrustpayWebhookResponse = request
.body
@@ -939,14 +904,14 @@ impl api::IncomingWebhook for Trustpay {
fn get_webhook_source_verification_algorithm(
&self,
- _request: &api::IncomingWebhookRequestDetails<'_>,
+ _request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let response: trustpay::TrustpayWebhookResponse = request
@@ -959,7 +924,7 @@ impl api::IncomingWebhook for Trustpay {
fn get_webhook_source_verification_message(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -968,16 +933,18 @@ impl api::IncomingWebhook for Trustpay {
.parse_struct("TrustpayWebhookResponse")
.switch()?;
let response: serde_json::Value = request.body.parse_struct("Webhook Value").switch()?;
- let values =
- collect_and_sort_values_by_removing_signature(&response, &trustpay_response.signature);
+ let values = utils::collect_and_sort_values_by_removing_signature(
+ &response,
+ &trustpay_response.signature,
+ );
let payload = values.join("/");
Ok(payload.into_bytes())
}
fn get_dispute_details(
&self,
- request: &api::IncomingWebhookRequestDetails<'_>,
- ) -> CustomResult<api::disputes::DisputePayload, errors::ConnectorError> {
+ request: &webhooks::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<DisputePayload, errors::ConnectorError> {
let trustpay_response: trustpay::TrustpayWebhookResponse = request
.body
.parse_struct("TrustpayWebhookResponse")
@@ -988,7 +955,7 @@ impl api::IncomingWebhook for Trustpay {
.references
.payment_id
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?;
- Ok(api::disputes::DisputePayload {
+ Ok(DisputePayload {
amount: payment_info.amount.amount.to_string(),
currency: payment_info.amount.currency,
dispute_stage: api_models::enums::DisputeStage::Dispute,
@@ -1003,24 +970,24 @@ impl api::IncomingWebhook for Trustpay {
}
}
-impl services::ConnectorRedirectResponse for Trustpay {
+impl ConnectorRedirectResponse for Trustpay {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
- action: services::PaymentAction,
- ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ action: PaymentAction,
+ ) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
match action {
- services::PaymentAction::PSync
- | services::PaymentAction::CompleteAuthorize
- | services::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
- Ok(payments::CallConnectorAction::Trigger)
+ PaymentAction::PSync
+ | PaymentAction::CompleteAuthorize
+ | PaymentAction::PaymentAuthenticateCompleteAuthorize => {
+ Ok(enums::CallConnectorAction::Trigger)
}
}
}
}
-impl ConnectorErrorTypeMapping for Trustpay {
+impl utils::ConnectorErrorTypeMapping for Trustpay {
fn get_connector_error_type(
&self,
error_code: String,
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
similarity index 86%
rename from crates/router/src/connector/trustpay/transformers.rs
rename to crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
index b7cb7a91f20..52181738579 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
@@ -1,24 +1,37 @@
use std::collections::HashMap;
+use api_models::payments::SessionToken;
+use common_enums::enums;
use common_utils::{
errors::CustomResult,
pii::{self, Email},
+ request::Method,
types::StringMajorUnit,
};
use error_stack::{report, ResultExt};
+use hyperswitch_domain_models::{
+ payment_method_data::{BankRedirectData, Card, PaymentMethodData},
+ router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
+ router_request_types::{BrowserInformation, PaymentsPreProcessingData, ResponseId},
+ router_response_types::{
+ PaymentsResponseData, PreprocessingResponseId, RedirectForm, RefundsResponseData,
+ },
+ types::{
+ PaymentsAuthorizeRouterData, PaymentsPreProcessingRouterData, RefreshTokenRouterData,
+ RefundsRouterData,
+ },
+};
+use hyperswitch_interfaces::{consts, errors};
use masking::{ExposeInterface, PeekInterface, Secret};
use reqwest::Url;
use serde::{Deserialize, Serialize};
use crate::{
- connector::utils::{
+ types::{RefundsResponseRouterData, ResponseRouterData},
+ utils::{
self, AddressDetailsData, BrowserInformationData, CardData, PaymentsAuthorizeRequestData,
- PaymentsPreProcessingData, RouterData,
+ PaymentsPreProcessingRequestData, RouterData as OtherRouterData,
},
- consts,
- core::errors,
- services,
- types::{self, domain, storage::enums, BrowserInformation},
};
type Error = error_stack::Report<errors::ConnectorError>;
@@ -45,10 +58,10 @@ pub struct TrustpayAuthType {
pub(super) secret_key: Secret<String>,
}
-impl TryFrom<&types::ConnectorAuthType> for TrustpayAuthType {
+impl TryFrom<&ConnectorAuthType> for TrustpayAuthType {
type Error = Error;
- fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
- if let types::ConnectorAuthType::SignatureKey {
+ fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
+ if let ConnectorAuthType::SignatureKey {
api_key,
key1,
api_secret,
@@ -214,28 +227,28 @@ pub struct TrustpayMandatoryParams {
pub billing_first_name: Secret<String>,
}
-impl TryFrom<&domain::BankRedirectData> for TrustpayPaymentMethod {
+impl TryFrom<&BankRedirectData> for TrustpayPaymentMethod {
type Error = Error;
- fn try_from(value: &domain::BankRedirectData) -> Result<Self, Self::Error> {
+ fn try_from(value: &BankRedirectData) -> Result<Self, Self::Error> {
match value {
- domain::BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
- domain::BankRedirectData::Eps { .. } => Ok(Self::Eps),
- domain::BankRedirectData::Ideal { .. } => Ok(Self::IDeal),
- domain::BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
- domain::BankRedirectData::Blik { .. } => Ok(Self::Blik),
- domain::BankRedirectData::BancontactCard { .. }
- | domain::BankRedirectData::Bizum {}
- | domain::BankRedirectData::Interac { .. }
- | domain::BankRedirectData::OnlineBankingCzechRepublic { .. }
- | domain::BankRedirectData::OnlineBankingFinland { .. }
- | domain::BankRedirectData::OnlineBankingPoland { .. }
- | domain::BankRedirectData::OnlineBankingSlovakia { .. }
- | domain::BankRedirectData::OpenBankingUk { .. }
- | domain::BankRedirectData::Przelewy24 { .. }
- | domain::BankRedirectData::Trustly { .. }
- | domain::BankRedirectData::OnlineBankingFpx { .. }
- | domain::BankRedirectData::OnlineBankingThailand { .. }
- | domain::BankRedirectData::LocalBankRedirect {} => {
+ BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
+ BankRedirectData::Eps { .. } => Ok(Self::Eps),
+ BankRedirectData::Ideal { .. } => Ok(Self::IDeal),
+ BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
+ BankRedirectData::Blik { .. } => Ok(Self::Blik),
+ BankRedirectData::BancontactCard { .. }
+ | BankRedirectData::Bizum {}
+ | BankRedirectData::Interac { .. }
+ | BankRedirectData::OnlineBankingCzechRepublic { .. }
+ | BankRedirectData::OnlineBankingFinland { .. }
+ | BankRedirectData::OnlineBankingPoland { .. }
+ | BankRedirectData::OnlineBankingSlovakia { .. }
+ | BankRedirectData::OpenBankingUk { .. }
+ | BankRedirectData::Przelewy24 { .. }
+ | BankRedirectData::Trustly { .. }
+ | BankRedirectData::OnlineBankingFpx { .. }
+ | BankRedirectData::OnlineBankingThailand { .. }
+ | BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("trustpay"),
)
@@ -246,7 +259,7 @@ impl TryFrom<&domain::BankRedirectData> for TrustpayPaymentMethod {
}
fn get_mandatory_fields(
- item: &types::PaymentsAuthorizeRouterData,
+ item: &PaymentsAuthorizeRouterData,
) -> Result<TrustpayMandatoryParams, Error> {
let billing_address = item
.get_billing()?
@@ -263,11 +276,11 @@ fn get_mandatory_fields(
}
fn get_card_request_data(
- item: &types::PaymentsAuthorizeRouterData,
+ item: &PaymentsAuthorizeRouterData,
browser_info: &BrowserInformation,
params: TrustpayMandatoryParams,
amount: StringMajorUnit,
- ccard: &domain::payments::Card,
+ ccard: &Card,
return_url: String,
) -> Result<TrustpayPaymentsRequest, Error> {
let email = item.request.get_email()?;
@@ -321,7 +334,7 @@ fn get_full_name(
}
fn get_debtor_info(
- item: &types::PaymentsAuthorizeRouterData,
+ item: &PaymentsAuthorizeRouterData,
pm: TrustpayPaymentMethod,
params: TrustpayMandatoryParams,
) -> CustomResult<Option<DebtorInformation>, errors::ConnectorError> {
@@ -343,8 +356,8 @@ fn get_debtor_info(
}
fn get_bank_redirection_request_data(
- item: &types::PaymentsAuthorizeRouterData,
- bank_redirection_data: &domain::BankRedirectData,
+ item: &PaymentsAuthorizeRouterData,
+ bank_redirection_data: &BankRedirectData,
params: TrustpayMandatoryParams,
amount: StringMajorUnit,
auth: TrustpayAuthType,
@@ -376,10 +389,10 @@ fn get_bank_redirection_request_data(
Ok(payment_request)
}
-impl TryFrom<&TrustpayRouterData<&types::PaymentsAuthorizeRouterData>> for TrustpayPaymentsRequest {
+impl TryFrom<&TrustpayRouterData<&PaymentsAuthorizeRouterData>> for TrustpayPaymentsRequest {
type Error = Error;
fn try_from(
- item: &TrustpayRouterData<&types::PaymentsAuthorizeRouterData>,
+ item: &TrustpayRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let browser_info = item
.router_data
@@ -408,7 +421,7 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsAuthorizeRouterData>> for Trust
let auth = TrustpayAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
match item.router_data.request.payment_method_data {
- domain::PaymentMethodData::Card(ref ccard) => Ok(get_card_request_data(
+ PaymentMethodData::Card(ref ccard) => Ok(get_card_request_data(
item.router_data,
&default_browser_info,
params,
@@ -416,7 +429,7 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsAuthorizeRouterData>> for Trust
ccard,
item.router_data.request.get_router_return_url()?,
)?),
- domain::PaymentMethodData::BankRedirect(ref bank_redirection_data) => {
+ PaymentMethodData::BankRedirect(ref bank_redirection_data) => {
get_bank_redirection_request_data(
item.router_data,
bank_redirection_data,
@@ -425,23 +438,23 @@ impl TryFrom<&TrustpayRouterData<&types::PaymentsAuthorizeRouterData>> for Trust
auth,
)
}
- domain::PaymentMethodData::CardRedirect(_)
- | domain::PaymentMethodData::Wallet(_)
- | domain::PaymentMethodData::PayLater(_)
- | domain::PaymentMethodData::BankDebit(_)
- | domain::PaymentMethodData::BankTransfer(_)
- | domain::PaymentMethodData::Crypto(_)
- | domain::PaymentMethodData::MandatePayment
- | domain::PaymentMethodData::Reward
- | domain::PaymentMethodData::RealTimePayment(_)
- | domain::PaymentMethodData::MobilePayment(_)
- | domain::PaymentMethodData::Upi(_)
- | domain::PaymentMethodData::Voucher(_)
- | domain::PaymentMethodData::GiftCard(_)
- | domain::PaymentMethodData::OpenBanking(_)
- | domain::PaymentMethodData::CardToken(_)
- | domain::PaymentMethodData::NetworkToken(_)
- | domain::PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
+ PaymentMethodData::CardRedirect(_)
+ | PaymentMethodData::Wallet(_)
+ | PaymentMethodData::PayLater(_)
+ | PaymentMethodData::BankDebit(_)
+ | PaymentMethodData::BankTransfer(_)
+ | PaymentMethodData::Crypto(_)
+ | PaymentMethodData::MandatePayment
+ | PaymentMethodData::Reward
+ | PaymentMethodData::RealTimePayment(_)
+ | PaymentMethodData::MobilePayment(_)
+ | PaymentMethodData::Upi(_)
+ | PaymentMethodData::Voucher(_)
+ | PaymentMethodData::GiftCard(_)
+ | PaymentMethodData::OpenBanking(_)
+ | PaymentMethodData::CardToken(_)
+ | PaymentMethodData::NetworkToken(_)
+ | PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("trustpay"),
)
@@ -667,18 +680,12 @@ pub enum TrustpayPaymentsResponse {
WebhookResponse(Box<WebhookPaymentInformation>),
}
-impl<F, T>
- TryFrom<types::ResponseRouterData<F, TrustpayPaymentsResponse, T, types::PaymentsResponseData>>
- for types::RouterData<F, T, types::PaymentsResponseData>
+impl<F, T> TryFrom<ResponseRouterData<F, TrustpayPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
- item: types::ResponseRouterData<
- F,
- TrustpayPaymentsResponse,
- T,
- types::PaymentsResponseData,
- >,
+ item: ResponseRouterData<F, TrustpayPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let (status, error, payment_response_data) =
get_trustpay_response(item.response, item.http_code)?;
@@ -696,8 +703,8 @@ fn handle_cards_response(
) -> CustomResult<
(
enums::AttemptStatus,
- Option<types::ErrorResponse>,
- types::PaymentsResponseData,
+ Option<ErrorResponse>,
+ PaymentsResponseData,
),
errors::ConnectorError,
> {
@@ -707,15 +714,13 @@ fn handle_cards_response(
)?;
let form_fields = response.redirect_params.unwrap_or_default();
- let redirection_data = response
- .redirect_url
- .map(|url| services::RedirectForm::Form {
- endpoint: url.to_string(),
- method: services::Method::Post,
- form_fields,
- });
+ let redirection_data = response.redirect_url.map(|url| RedirectForm::Form {
+ endpoint: url.to_string(),
+ method: Method::Post,
+ form_fields,
+ });
let error = if msg.is_some() {
- Some(types::ErrorResponse {
+ Some(ErrorResponse {
code: response
.payment_status
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
@@ -730,8 +735,8 @@ fn handle_cards_response(
} else {
None
};
- let payment_response_data = types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(response.instance_id.clone()),
+ let payment_response_data = PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(response.instance_id.clone()),
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: None,
@@ -748,20 +753,18 @@ fn handle_bank_redirects_response(
) -> CustomResult<
(
enums::AttemptStatus,
- Option<types::ErrorResponse>,
- types::PaymentsResponseData,
+ Option<ErrorResponse>,
+ PaymentsResponseData,
),
errors::ConnectorError,
> {
let status = enums::AttemptStatus::AuthenticationPending;
let error = None;
- let payment_response_data = types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
- response.payment_request_id.to_string(),
- ),
- redirection_data: Box::new(Some(services::RedirectForm::from((
+ let payment_response_data = PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(response.payment_request_id.to_string()),
+ redirection_data: Box::new(Some(RedirectForm::from((
response.gateway_url,
- services::Method::Get,
+ Method::Get,
)))),
mandate_reference: Box::new(None),
connector_metadata: None,
@@ -779,13 +782,13 @@ fn handle_bank_redirects_error_response(
) -> CustomResult<
(
enums::AttemptStatus,
- Option<types::ErrorResponse>,
- types::PaymentsResponseData,
+ Option<ErrorResponse>,
+ PaymentsResponseData,
),
errors::ConnectorError,
> {
let status = enums::AttemptStatus::AuthorizationFailed;
- let error = Some(types::ErrorResponse {
+ let error = Some(ErrorResponse {
code: response.payment_result_info.result_code.to_string(),
// message vary for the same code, so relying on code alone as it is unique
message: response.payment_result_info.result_code.to_string(),
@@ -794,8 +797,8 @@ fn handle_bank_redirects_error_response(
attempt_status: None,
connector_transaction_id: None,
});
- let payment_response_data = types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
+ let payment_response_data = PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
@@ -813,8 +816,8 @@ fn handle_bank_redirects_sync_response(
) -> CustomResult<
(
enums::AttemptStatus,
- Option<types::ErrorResponse>,
- types::PaymentsResponseData,
+ Option<ErrorResponse>,
+ PaymentsResponseData,
),
errors::ConnectorError,
> {
@@ -824,7 +827,7 @@ fn handle_bank_redirects_sync_response(
.payment_information
.status_reason_information
.unwrap_or_default();
- Some(types::ErrorResponse {
+ Some(ErrorResponse {
code: reason_info
.reason
.code
@@ -849,8 +852,8 @@ fn handle_bank_redirects_sync_response(
} else {
None
};
- let payment_response_data = types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(
+ let payment_response_data = PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::ConnectorTransactionId(
response
.payment_information
.references
@@ -874,8 +877,8 @@ pub fn handle_webhook_response(
) -> CustomResult<
(
enums::AttemptStatus,
- Option<types::ErrorResponse>,
- types::PaymentsResponseData,
+ Option<ErrorResponse>,
+ PaymentsResponseData,
),
errors::ConnectorError,
> {
@@ -884,7 +887,7 @@ pub fn handle_webhook_response(
let reason_info = payment_information
.status_reason_information
.unwrap_or_default();
- Some(types::ErrorResponse {
+ Some(ErrorResponse {
code: reason_info
.reason
.code
@@ -903,8 +906,8 @@ pub fn handle_webhook_response(
} else {
None
};
- let payment_response_data = types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::NoResponseId,
+ let payment_response_data = PaymentsResponseData::TransactionResponse {
+ resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
@@ -922,8 +925,8 @@ pub fn get_trustpay_response(
) -> CustomResult<
(
enums::AttemptStatus,
- Option<types::ErrorResponse>,
- types::PaymentsResponseData,
+ Option<ErrorResponse>,
+ PaymentsResponseData,
),
errors::ConnectorError,
> {
@@ -951,9 +954,9 @@ pub struct TrustpayAuthUpdateRequest {
pub grant_type: String,
}
-impl TryFrom<&types::RefreshTokenRouterData> for TrustpayAuthUpdateRequest {
+impl TryFrom<&RefreshTokenRouterData> for TrustpayAuthUpdateRequest {
type Error = Error;
- fn try_from(_item: &types::RefreshTokenRouterData) -> Result<Self, Self::Error> {
+ fn try_from(_item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
grant_type: "client_credentials".to_string(),
})
@@ -983,23 +986,23 @@ pub struct TrustpayAccessTokenErrorResponse {
pub result_info: ResultInfo,
}
-impl<F, T> TryFrom<types::ResponseRouterData<F, TrustpayAuthUpdateResponse, T, types::AccessToken>>
- for types::RouterData<F, T, types::AccessToken>
+impl<F, T> TryFrom<ResponseRouterData<F, TrustpayAuthUpdateResponse, T, AccessToken>>
+ for RouterData<F, T, AccessToken>
{
type Error = Error;
fn try_from(
- item: types::ResponseRouterData<F, TrustpayAuthUpdateResponse, T, types::AccessToken>,
+ item: ResponseRouterData<F, TrustpayAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
match (item.response.access_token, item.response.expires_in) {
(Some(access_token), Some(expires_in)) => Ok(Self {
- response: Ok(types::AccessToken {
+ response: Ok(AccessToken {
token: access_token,
expires: expires_in,
}),
..item.data
}),
_ => Ok(Self {
- response: Err(types::ErrorResponse {
+ response: Err(ErrorResponse {
code: item.response.result_info.result_code.to_string(),
// message vary for the same code, so relying on code alone as it is unique
message: item.response.result_info.result_code.to_string(),
@@ -1026,26 +1029,26 @@ pub struct TrustpayCreateIntentRequest {
pub reference: String,
}
-impl TryFrom<&TrustpayRouterData<&types::PaymentsPreProcessingRouterData>>
+impl TryFrom<&TrustpayRouterData<&PaymentsPreProcessingRouterData>>
for TrustpayCreateIntentRequest
{
type Error = Error;
fn try_from(
- item: &TrustpayRouterData<&types::PaymentsPreProcessingRouterData>,
+ item: &TrustpayRouterData<&PaymentsPreProcessingRouterData>,
) -> Result<Self, Self::Error> {
let is_apple_pay = item
.router_data
.request
.payment_method_type
.as_ref()
- .map(|pmt| matches!(pmt, diesel_models::enums::PaymentMethodType::ApplePay));
+ .map(|pmt| matches!(pmt, enums::PaymentMethodType::ApplePay));
let is_google_pay = item
.router_data
.request
.payment_method_type
.as_ref()
- .map(|pmt| matches!(pmt, diesel_models::enums::PaymentMethodType::GooglePay));
+ .map(|pmt| matches!(pmt, enums::PaymentMethodType::GooglePay));
let currency = item.router_data.request.get_currency()?;
let amount = item.amount.to_owned();
@@ -1161,21 +1164,21 @@ pub struct ApplePayTotalInfo {
impl<F>
TryFrom<
- types::ResponseRouterData<
+ ResponseRouterData<
F,
TrustpayCreateIntentResponse,
- types::PaymentsPreProcessingData,
- types::PaymentsResponseData,
+ PaymentsPreProcessingData,
+ PaymentsResponseData,
>,
- > for types::RouterData<F, types::PaymentsPreProcessingData, types::PaymentsResponseData>
+ > for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>
{
type Error = Error;
fn try_from(
- item: types::ResponseRouterData<
+ item: ResponseRouterData<
F,
TrustpayCreateIntentResponse,
- types::PaymentsPreProcessingData,
- types::PaymentsResponseData,
+ PaymentsPreProcessingData,
+ PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let create_intent_response = item.response.init_result_data.to_owned();
@@ -1185,11 +1188,11 @@ impl<F>
match (pmt, create_intent_response) {
(
- diesel_models::enums::PaymentMethodType::ApplePay,
+ enums::PaymentMethodType::ApplePay,
InitResultData::AppleInitResultData(apple_pay_response),
) => get_apple_pay_session(instance_id, &secrets, apple_pay_response, item),
(
- diesel_models::enums::PaymentMethodType::GooglePay,
+ enums::PaymentMethodType::GooglePay,
InitResultData::GoogleInitResultData(google_pay_response),
) => get_google_pay_session(instance_id, &secrets, google_pay_response, item),
_ => Err(report!(errors::ConnectorError::InvalidWallet)),
@@ -1201,21 +1204,13 @@ pub fn get_apple_pay_session<F, T>(
instance_id: String,
secrets: &SdkSecretInfo,
apple_pay_init_result: TrustpayApplePayResponse,
- item: types::ResponseRouterData<
- F,
- TrustpayCreateIntentResponse,
- T,
- types::PaymentsResponseData,
- >,
-) -> Result<
- types::RouterData<F, T, types::PaymentsResponseData>,
- error_stack::Report<errors::ConnectorError>,
-> {
- Ok(types::RouterData {
- response: Ok(types::PaymentsResponseData::PreProcessingResponse {
+ item: ResponseRouterData<F, TrustpayCreateIntentResponse, T, PaymentsResponseData>,
+) -> Result<RouterData<F, T, PaymentsResponseData>, error_stack::Report<errors::ConnectorError>> {
+ Ok(RouterData {
+ response: Ok(PaymentsResponseData::PreProcessingResponse {
connector_metadata: None,
- pre_processing_id: types::PreprocessingResponseId::ConnectorTransactionId(instance_id),
- session_token: Some(types::api::SessionToken::ApplePay(Box::new(
+ pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(instance_id),
+ session_token: Some(SessionToken::ApplePay(Box::new(
api_models::payments::ApplepaySessionTokenResponse {
session_token_data: Some(
api_models::payments::ApplePaySessionResponse::ThirdPartySdk(
@@ -1252,7 +1247,7 @@ pub fn get_apple_pay_session<F, T>(
connector_response_reference_id: None,
}),
// We don't get status from TrustPay but status should be AuthenticationPending by default for session response
- status: diesel_models::enums::AttemptStatus::AuthenticationPending,
+ status: enums::AttemptStatus::AuthenticationPending,
..item.data
})
}
@@ -1261,21 +1256,13 @@ pub fn get_google_pay_session<F, T>(
instance_id: String,
secrets: &SdkSecretInfo,
google_pay_init_result: TrustpayGooglePayResponse,
- item: types::ResponseRouterData<
- F,
- TrustpayCreateIntentResponse,
- T,
- types::PaymentsResponseData,
- >,
-) -> Result<
- types::RouterData<F, T, types::PaymentsResponseData>,
- error_stack::Report<errors::ConnectorError>,
-> {
- Ok(types::RouterData {
- response: Ok(types::PaymentsResponseData::PreProcessingResponse {
+ item: ResponseRouterData<F, TrustpayCreateIntentResponse, T, PaymentsResponseData>,
+) -> Result<RouterData<F, T, PaymentsResponseData>, error_stack::Report<errors::ConnectorError>> {
+ Ok(RouterData {
+ response: Ok(PaymentsResponseData::PreProcessingResponse {
connector_metadata: None,
- pre_processing_id: types::PreprocessingResponseId::ConnectorTransactionId(instance_id),
- session_token: Some(types::api::SessionToken::GooglePay(Box::new(
+ pre_processing_id: PreprocessingResponseId::ConnectorTransactionId(instance_id),
+ session_token: Some(SessionToken::GooglePay(Box::new(
api_models::payments::GpaySessionTokenResponse::GooglePaySession(
api_models::payments::GooglePaySessionResponse {
connector: "trustpay".to_string(),
@@ -1305,7 +1292,7 @@ pub fn get_google_pay_session<F, T>(
connector_response_reference_id: None,
}),
// We don't get status from TrustPay but status should be AuthenticationPending by default for session response
- status: diesel_models::enums::AttemptStatus::AuthenticationPending,
+ status: enums::AttemptStatus::AuthenticationPending,
..item.data
})
}
@@ -1416,14 +1403,12 @@ pub enum TrustpayRefundRequest {
BankRedirectRefund(Box<TrustpayRefundRequestBankRedirect>),
}
-impl<F> TryFrom<&TrustpayRouterData<&types::RefundsRouterData<F>>> for TrustpayRefundRequest {
+impl<F> TryFrom<&TrustpayRouterData<&RefundsRouterData<F>>> for TrustpayRefundRequest {
type Error = Error;
- fn try_from(
- item: &TrustpayRouterData<&types::RefundsRouterData<F>>,
- ) -> Result<Self, Self::Error> {
+ fn try_from(item: &TrustpayRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let amount = item.amount.to_owned();
match item.router_data.payment_method {
- diesel_models::enums::PaymentMethod::BankRedirect => {
+ enums::PaymentMethod::BankRedirect => {
let auth = TrustpayAuthType::try_from(&item.router_data.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(Self::BankRedirectRefund(Box::new(
@@ -1484,11 +1469,10 @@ pub enum RefundResponse {
fn handle_cards_refund_response(
response: CardsRefundResponse,
status_code: u16,
-) -> CustomResult<(Option<types::ErrorResponse>, types::RefundsResponseData), errors::ConnectorError>
-{
+) -> CustomResult<(Option<ErrorResponse>, RefundsResponseData), errors::ConnectorError> {
let (refund_status, msg) = get_refund_status(&response.payment_status)?;
let error = if msg.is_some() {
- Some(types::ErrorResponse {
+ Some(ErrorResponse {
code: response.payment_status,
message: msg
.clone()
@@ -1501,7 +1485,7 @@ fn handle_cards_refund_response(
} else {
None
};
- let refund_response_data = types::RefundsResponseData {
+ let refund_response_data = RefundsResponseData {
connector_refund_id: response.instance_id,
refund_status,
};
@@ -1511,12 +1495,11 @@ fn handle_cards_refund_response(
fn handle_webhooks_refund_response(
response: WebhookPaymentInformation,
status_code: u16,
-) -> CustomResult<(Option<types::ErrorResponse>, types::RefundsResponseData), errors::ConnectorError>
-{
- let refund_status = diesel_models::enums::RefundStatus::try_from(response.status)?;
+) -> CustomResult<(Option<ErrorResponse>, RefundsResponseData), errors::ConnectorError> {
+ let refund_status = enums::RefundStatus::try_from(response.status)?;
let error = if utils::is_refund_failure(refund_status) {
let reason_info = response.status_reason_information.unwrap_or_default();
- Some(types::ErrorResponse {
+ Some(ErrorResponse {
code: reason_info
.reason
.code
@@ -1535,7 +1518,7 @@ fn handle_webhooks_refund_response(
} else {
None
};
- let refund_response_data = types::RefundsResponseData {
+ let refund_response_data = RefundsResponseData {
connector_refund_id: response
.references
.payment_request_id
@@ -1548,10 +1531,10 @@ fn handle_webhooks_refund_response(
fn handle_bank_redirects_refund_response(
response: BankRedirectRefundResponse,
status_code: u16,
-) -> (Option<types::ErrorResponse>, types::RefundsResponseData) {
+) -> (Option<ErrorResponse>, RefundsResponseData) {
let (refund_status, msg) = get_refund_status_from_result_info(response.result_info.result_code);
let error = if msg.is_some() {
- Some(types::ErrorResponse {
+ Some(ErrorResponse {
code: response.result_info.result_code.to_string(),
// message vary for the same code, so relying on code alone as it is unique
message: response.result_info.result_code.to_string(),
@@ -1563,7 +1546,7 @@ fn handle_bank_redirects_refund_response(
} else {
None
};
- let refund_response_data = types::RefundsResponseData {
+ let refund_response_data = RefundsResponseData {
connector_refund_id: response.payment_request_id.to_string(),
refund_status,
};
@@ -1573,14 +1556,14 @@ fn handle_bank_redirects_refund_response(
fn handle_bank_redirects_refund_sync_response(
response: SyncResponseBankRedirect,
status_code: u16,
-) -> (Option<types::ErrorResponse>, types::RefundsResponseData) {
+) -> (Option<ErrorResponse>, RefundsResponseData) {
let refund_status = enums::RefundStatus::from(response.payment_information.status);
let error = if utils::is_refund_failure(refund_status) {
let reason_info = response
.payment_information
.status_reason_information
.unwrap_or_default();
- Some(types::ErrorResponse {
+ Some(ErrorResponse {
code: reason_info
.reason
.code
@@ -1599,7 +1582,7 @@ fn handle_bank_redirects_refund_sync_response(
} else {
None
};
- let refund_response_data = types::RefundsResponseData {
+ let refund_response_data = RefundsResponseData {
connector_refund_id: response.payment_information.references.payment_request_id,
refund_status,
};
@@ -1609,8 +1592,8 @@ fn handle_bank_redirects_refund_sync_response(
fn handle_bank_redirects_refund_sync_error_response(
response: ErrorResponseBankRedirect,
status_code: u16,
-) -> (Option<types::ErrorResponse>, types::RefundsResponseData) {
- let error = Some(types::ErrorResponse {
+) -> (Option<ErrorResponse>, RefundsResponseData) {
+ let error = Some(ErrorResponse {
code: response.payment_result_info.result_code.to_string(),
// message vary for the same code, so relying on code alone as it is unique
message: response.payment_result_info.result_code.to_string(),
@@ -1620,20 +1603,16 @@ fn handle_bank_redirects_refund_sync_error_response(
connector_transaction_id: None,
});
//unreachable case as we are sending error as Some()
- let refund_response_data = types::RefundsResponseData {
+ let refund_response_data = RefundsResponseData {
connector_refund_id: "".to_string(),
refund_status: enums::RefundStatus::Failure,
};
(error, refund_response_data)
}
-impl<F> TryFrom<types::RefundsResponseRouterData<F, RefundResponse>>
- for types::RefundsRouterData<F>
-{
+impl<F> TryFrom<RefundsResponseRouterData<F, RefundResponse>> for RefundsRouterData<F> {
type Error = Error;
- fn try_from(
- item: types::RefundsResponseRouterData<F, RefundResponse>,
- ) -> Result<Self, Self::Error> {
+ fn try_from(item: RefundsResponseRouterData<F, RefundResponse>) -> Result<Self, Self::Error> {
let (error, response) = match item.response {
RefundResponse::CardsRefund(response) => {
handle_cards_refund_response(*response, item.http_code)?
@@ -1773,7 +1752,7 @@ impl TryFrom<WebhookStatus> for enums::AttemptStatus {
}
}
-impl TryFrom<WebhookStatus> for diesel_models::enums::RefundStatus {
+impl TryFrom<WebhookStatus> for enums::RefundStatus {
type Error = errors::ConnectorError;
fn try_from(item: WebhookStatus) -> Result<Self, Self::Error> {
match item {
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index 86bed027071..f64f624187a 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -100,6 +100,7 @@ default_imp_for_authorize_session_token!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -110,6 +111,7 @@ default_imp_for_authorize_session_token!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -134,11 +136,15 @@ default_imp_for_authorize_session_token!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -158,6 +164,7 @@ default_imp_for_authorize_session_token!(
connectors::UnifiedAuthenticationService,
connectors::Volt,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::Worldline,
connectors::Worldpay,
@@ -186,6 +193,7 @@ default_imp_for_calculate_tax!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -196,6 +204,7 @@ default_imp_for_calculate_tax!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -225,11 +234,15 @@ default_imp_for_calculate_tax!(
connectors::Multisafepay,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Paybox,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nuvei,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -243,6 +256,7 @@ default_imp_for_calculate_tax!(
connectors::Square,
connectors::Stripebilling,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Volt,
@@ -273,6 +287,7 @@ default_imp_for_session_update!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -283,6 +298,7 @@ default_imp_for_session_update!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -314,12 +330,16 @@ default_imp_for_session_update!(
connectors::Moneris,
connectors::Multisafepay,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -337,6 +357,7 @@ default_imp_for_session_update!(
connectors::Powertranz,
connectors::Prophetpay,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::Deutschebank,
connectors::Volt,
@@ -361,6 +382,7 @@ default_imp_for_post_session_tokens!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -371,6 +393,7 @@ default_imp_for_post_session_tokens!(
connectors::Billwerk,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -402,12 +425,16 @@ default_imp_for_post_session_tokens!(
connectors::Moneris,
connectors::Multisafepay,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -422,6 +449,7 @@ default_imp_for_post_session_tokens!(
connectors::Powertranz,
connectors::Prophetpay,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Deutschebank,
@@ -457,6 +485,7 @@ default_imp_for_complete_authorize!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -480,8 +509,11 @@ default_imp_for_complete_authorize!(
connectors::Moneris,
connectors::Multisafepay,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Payeezy,
connectors::Paystack,
connectors::Payu,
@@ -494,6 +526,7 @@ default_imp_for_complete_authorize!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Wellsfargo,
@@ -524,6 +557,7 @@ default_imp_for_incremental_authorization!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -534,6 +568,7 @@ default_imp_for_incremental_authorization!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -557,12 +592,16 @@ default_imp_for_incremental_authorization!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -581,6 +620,7 @@ default_imp_for_incremental_authorization!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -611,6 +651,7 @@ default_imp_for_create_customer!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -621,6 +662,7 @@ default_imp_for_create_customer!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -648,12 +690,16 @@ default_imp_for_create_customer!(
connectors::Moneris,
connectors::Multisafepay,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -667,6 +713,7 @@ default_imp_for_create_customer!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -732,6 +779,8 @@ default_imp_for_connector_redirect_response!(
connectors::Multisafepay,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Payeezy,
connectors::Paystack,
connectors::Payu,
@@ -774,6 +823,7 @@ macro_rules! default_imp_for_pre_processing_steps{
default_imp_for_pre_processing_steps!(
connectors::Aci,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -784,6 +834,7 @@ default_imp_for_pre_processing_steps!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -806,8 +857,11 @@ default_imp_for_pre_processing_steps!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Paybox,
connectors::Payeezy,
connectors::Paystack,
@@ -857,6 +911,7 @@ default_imp_for_post_processing_steps!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -867,6 +922,7 @@ default_imp_for_post_processing_steps!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -891,12 +947,16 @@ default_imp_for_post_processing_steps!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -915,6 +975,7 @@ default_imp_for_post_processing_steps!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -946,6 +1007,7 @@ default_imp_for_approve!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -956,6 +1018,7 @@ default_imp_for_approve!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -980,12 +1043,16 @@ default_imp_for_approve!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1004,6 +1071,7 @@ default_imp_for_approve!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1035,6 +1103,7 @@ default_imp_for_reject!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1045,6 +1114,7 @@ default_imp_for_reject!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1069,12 +1139,16 @@ default_imp_for_reject!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1093,6 +1167,7 @@ default_imp_for_reject!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1124,6 +1199,7 @@ default_imp_for_webhook_source_verification!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1134,6 +1210,7 @@ default_imp_for_webhook_source_verification!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1158,12 +1235,16 @@ default_imp_for_webhook_source_verification!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1182,6 +1263,7 @@ default_imp_for_webhook_source_verification!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1214,6 +1296,7 @@ default_imp_for_accept_dispute!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1248,12 +1331,16 @@ default_imp_for_accept_dispute!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1272,6 +1359,7 @@ default_imp_for_accept_dispute!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1303,6 +1391,7 @@ default_imp_for_submit_evidence!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1337,12 +1426,16 @@ default_imp_for_submit_evidence!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1361,6 +1454,7 @@ default_imp_for_submit_evidence!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1392,6 +1486,7 @@ default_imp_for_defend_dispute!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1426,12 +1521,16 @@ default_imp_for_defend_dispute!(
connectors::Klarna,
connectors::Helcim,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1450,6 +1549,7 @@ default_imp_for_defend_dispute!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1490,6 +1590,7 @@ default_imp_for_file_upload!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1524,12 +1625,16 @@ default_imp_for_file_upload!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1548,6 +1653,7 @@ default_imp_for_file_upload!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1572,6 +1678,7 @@ default_imp_for_payouts!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1582,6 +1689,7 @@ default_imp_for_payouts!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Cryptopay,
connectors::Datatrans,
connectors::Coinbase,
@@ -1610,10 +1718,14 @@ default_imp_for_payouts!(
connectors::Multisafepay,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Paybox,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nuvei,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1627,6 +1739,7 @@ default_imp_for_payouts!(
connectors::Stax,
connectors::Stripebilling,
connectors::Taxjar,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Volt,
@@ -1660,6 +1773,7 @@ default_imp_for_payouts_create!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1670,6 +1784,7 @@ default_imp_for_payouts_create!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1693,12 +1808,16 @@ default_imp_for_payouts_create!(
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Klarna,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1717,6 +1836,7 @@ default_imp_for_payouts_create!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1750,6 +1870,7 @@ default_imp_for_payouts_retrieve!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1760,6 +1881,7 @@ default_imp_for_payouts_retrieve!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1783,12 +1905,16 @@ default_imp_for_payouts_retrieve!(
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Klarna,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1807,6 +1933,7 @@ default_imp_for_payouts_retrieve!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1840,6 +1967,7 @@ default_imp_for_payouts_eligibility!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1850,6 +1978,7 @@ default_imp_for_payouts_eligibility!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1873,12 +2002,16 @@ default_imp_for_payouts_eligibility!(
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Klarna,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1897,6 +2030,7 @@ default_imp_for_payouts_eligibility!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1930,6 +2064,7 @@ default_imp_for_payouts_fulfill!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1940,6 +2075,7 @@ default_imp_for_payouts_fulfill!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1962,12 +2098,16 @@ default_imp_for_payouts_fulfill!(
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Klarna,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1986,6 +2126,7 @@ default_imp_for_payouts_fulfill!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -2019,6 +2160,7 @@ default_imp_for_payouts_cancel!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -2029,6 +2171,7 @@ default_imp_for_payouts_cancel!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -2052,12 +2195,16 @@ default_imp_for_payouts_cancel!(
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Klarna,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -2076,6 +2223,7 @@ default_imp_for_payouts_cancel!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -2109,6 +2257,7 @@ default_imp_for_payouts_quote!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -2119,6 +2268,7 @@ default_imp_for_payouts_quote!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -2142,12 +2292,16 @@ default_imp_for_payouts_quote!(
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Klarna,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -2166,6 +2320,7 @@ default_imp_for_payouts_quote!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -2199,6 +2354,7 @@ default_imp_for_payouts_recipient!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -2209,6 +2365,7 @@ default_imp_for_payouts_recipient!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -2232,12 +2389,16 @@ default_imp_for_payouts_recipient!(
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Klarna,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -2256,6 +2417,7 @@ default_imp_for_payouts_recipient!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -2289,6 +2451,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -2299,6 +2462,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -2322,12 +2486,16 @@ default_imp_for_payouts_recipient_account!(
connectors::Itaubank,
connectors::Jpmorgan,
connectors::Klarna,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -2346,6 +2514,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -2379,6 +2548,7 @@ default_imp_for_frm_sale!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -2389,6 +2559,7 @@ default_imp_for_frm_sale!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -2413,12 +2584,16 @@ default_imp_for_frm_sale!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -2437,6 +2612,7 @@ default_imp_for_frm_sale!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -2470,6 +2646,7 @@ default_imp_for_frm_checkout!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -2480,6 +2657,7 @@ default_imp_for_frm_checkout!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -2504,12 +2682,16 @@ default_imp_for_frm_checkout!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -2528,6 +2710,7 @@ default_imp_for_frm_checkout!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -2561,6 +2744,7 @@ default_imp_for_frm_transaction!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -2571,6 +2755,7 @@ default_imp_for_frm_transaction!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -2595,12 +2780,16 @@ default_imp_for_frm_transaction!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -2619,6 +2808,7 @@ default_imp_for_frm_transaction!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -2652,6 +2842,7 @@ default_imp_for_frm_fulfillment!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -2662,6 +2853,7 @@ default_imp_for_frm_fulfillment!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -2686,12 +2878,16 @@ default_imp_for_frm_fulfillment!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -2710,6 +2906,7 @@ default_imp_for_frm_fulfillment!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -2743,6 +2940,7 @@ default_imp_for_frm_record_return!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -2753,6 +2951,7 @@ default_imp_for_frm_record_return!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -2777,12 +2976,16 @@ default_imp_for_frm_record_return!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -2801,6 +3004,7 @@ default_imp_for_frm_record_return!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -2831,6 +3035,7 @@ default_imp_for_revoking_mandates!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -2841,6 +3046,7 @@ default_imp_for_revoking_mandates!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -2867,9 +3073,12 @@ default_imp_for_revoking_mandates!(
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -2888,6 +3097,7 @@ default_imp_for_revoking_mandates!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -2918,6 +3128,7 @@ default_imp_for_uas_pre_authentication!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -2928,6 +3139,7 @@ default_imp_for_uas_pre_authentication!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -2953,11 +3165,15 @@ default_imp_for_uas_pre_authentication!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Powertranz,
@@ -2977,6 +3193,7 @@ default_imp_for_uas_pre_authentication!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::Worldline,
connectors::Worldpay,
@@ -3005,6 +3222,7 @@ default_imp_for_uas_post_authentication!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -3015,6 +3233,7 @@ default_imp_for_uas_post_authentication!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -3040,11 +3259,15 @@ default_imp_for_uas_post_authentication!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Powertranz,
@@ -3064,6 +3287,7 @@ default_imp_for_uas_post_authentication!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::Worldline,
connectors::Worldpay,
@@ -3092,6 +3316,7 @@ default_imp_for_uas_authentication!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -3102,6 +3327,7 @@ default_imp_for_uas_authentication!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -3127,11 +3353,15 @@ default_imp_for_uas_authentication!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Powertranz,
@@ -3151,6 +3381,7 @@ default_imp_for_uas_authentication!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::Wellsfargo,
connectors::Worldline,
@@ -3180,6 +3411,7 @@ default_imp_for_uas_authentication_confirmation!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -3190,6 +3422,7 @@ default_imp_for_uas_authentication_confirmation!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -3215,10 +3448,13 @@ default_imp_for_uas_authentication_confirmation!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
connectors::Nuvei,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Payeezy,
connectors::Paystack,
connectors::Payu,
@@ -3229,6 +3465,7 @@ default_imp_for_uas_authentication_confirmation!(
connectors::Moneris,
connectors::Multisafepay,
connectors::Paybox,
+ connectors::Payme,
connectors::Placetopay,
connectors::Rapyd,
connectors::Razorpay,
@@ -3239,6 +3476,7 @@ default_imp_for_uas_authentication_confirmation!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::Worldline,
connectors::Worldpay,
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index ef339c22a4b..f333800480b 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -207,6 +207,7 @@ macro_rules! default_imp_for_new_connector_integration_payment {
default_imp_for_new_connector_integration_payment!(
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -217,6 +218,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -242,12 +244,16 @@ default_imp_for_new_connector_integration_payment!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -266,6 +272,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -297,6 +304,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -307,6 +315,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -332,12 +341,16 @@ default_imp_for_new_connector_integration_refund!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -356,6 +369,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Wellsfargo,
@@ -382,6 +396,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -392,6 +407,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -417,12 +433,16 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -441,6 +461,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -473,6 +494,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -483,6 +505,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -507,12 +530,16 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -531,6 +558,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -562,6 +590,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -572,6 +601,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -596,12 +626,16 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -620,6 +654,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -651,6 +686,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -661,6 +697,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -686,12 +723,16 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -710,6 +751,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -751,6 +793,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -761,6 +804,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -786,12 +830,16 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -810,6 +858,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -843,6 +892,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -853,6 +903,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -878,12 +929,16 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -902,6 +957,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -935,6 +991,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -945,6 +1002,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -970,12 +1028,16 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -994,6 +1056,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1027,6 +1090,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1037,6 +1101,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1062,12 +1127,16 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1086,6 +1155,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1119,6 +1189,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1129,6 +1200,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1154,12 +1226,16 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1178,6 +1254,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1211,6 +1288,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1221,6 +1299,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1246,12 +1325,16 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1270,6 +1353,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1303,6 +1387,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1313,6 +1398,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1338,12 +1424,16 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1362,6 +1452,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1395,6 +1486,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1405,6 +1497,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1430,12 +1523,16 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1454,6 +1551,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1487,6 +1585,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1497,6 +1596,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1522,12 +1622,16 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1546,6 +1650,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1577,6 +1682,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1587,6 +1693,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1612,12 +1719,16 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1636,6 +1747,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1669,6 +1781,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1679,6 +1792,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1704,12 +1818,16 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1728,6 +1846,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1761,6 +1880,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1771,6 +1891,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1796,12 +1917,16 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1820,6 +1945,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1853,6 +1979,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1863,6 +1990,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1888,12 +2016,16 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -1912,6 +2044,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -1945,6 +2078,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -1955,6 +2089,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -1980,12 +2115,16 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -2004,6 +2143,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -2037,6 +2177,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -2047,6 +2188,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -2072,12 +2214,16 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -2096,6 +2242,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
@@ -2126,6 +2273,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Aci,
connectors::Airwallex,
connectors::Amazonpay,
+ connectors::Authorizedotnet,
connectors::Bambora,
connectors::Bamboraapac,
connectors::Bankofamerica,
@@ -2136,6 +2284,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Boku,
connectors::Cashtocode,
connectors::Chargebee,
+ connectors::Checkout,
connectors::Coinbase,
connectors::Coingate,
connectors::Cryptopay,
@@ -2161,12 +2310,16 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Jpmorgan,
connectors::Klarna,
connectors::Nomupay,
+ connectors::Noon,
connectors::Novalnet,
connectors::Nexinets,
connectors::Nexixpay,
+ connectors::Opayo,
+ connectors::Opennode,
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Payme,
connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
@@ -2185,6 +2338,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Stripebilling,
connectors::Taxjar,
connectors::Thunes,
+ connectors::Trustpay,
connectors::Tsys,
connectors::UnifiedAuthenticationService,
connectors::Worldline,
diff --git a/crates/hyperswitch_connectors/src/types.rs b/crates/hyperswitch_connectors/src/types.rs
index e893238fd8d..63b857e7ca2 100644
--- a/crates/hyperswitch_connectors/src/types.rs
+++ b/crates/hyperswitch_connectors/src/types.rs
@@ -2,12 +2,20 @@
use hyperswitch_domain_models::types::{PayoutsData, PayoutsResponseData};
use hyperswitch_domain_models::{
router_data::{AccessToken, RouterData},
- router_flow_types::{AccessTokenAuth, Authorize, Capture, PSync, PreProcessing, Session, Void},
+ router_flow_types::{
+ Accept, AccessTokenAuth, Authorize, Capture, Defend, Evidence, PSync, PreProcessing,
+ Session, Upload, Void,
+ },
router_request_types::{
- AccessTokenRequestData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
- PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData, RefundsData,
+ AcceptDisputeRequestData, AccessTokenRequestData, DefendDisputeRequestData,
+ PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData,
+ PaymentsSessionData, PaymentsSyncData, RefundsData, SubmitEvidenceRequestData,
+ UploadFileRequestData,
+ },
+ router_response_types::{
+ AcceptDisputeResponse, DefendDisputeResponse, PaymentsResponseData, RefundsResponseData,
+ SubmitEvidenceResponse, UploadFileResponse,
},
- router_response_types::{PaymentsResponseData, RefundsResponseData},
};
pub(crate) type PaymentsSyncResponseRouterData<R> =
@@ -28,6 +36,15 @@ pub(crate) type PaymentsPreprocessingResponseRouterData<R> =
pub(crate) type PaymentsSessionResponseRouterData<R> =
ResponseRouterData<Session, R, PaymentsSessionData, PaymentsResponseData>;
+pub(crate) type AcceptDisputeRouterData =
+ RouterData<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>;
+pub(crate) type SubmitEvidenceRouterData =
+ RouterData<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>;
+pub(crate) type UploadFileRouterData =
+ RouterData<Upload, UploadFileRequestData, UploadFileResponse>;
+pub(crate) type DefendDisputeRouterData =
+ RouterData<Defend, DefendDisputeRequestData, DefendDisputeResponse>;
+
#[cfg(feature = "payouts")]
pub type PayoutsResponseRouterData<F, R> =
ResponseRouterData<F, R, PayoutsData, PayoutsResponseData>;
diff --git a/crates/hyperswitch_connectors/src/utils.rs b/crates/hyperswitch_connectors/src/utils.rs
index 05657216d9d..67529f14d91 100644
--- a/crates/hyperswitch_connectors/src/utils.rs
+++ b/crates/hyperswitch_connectors/src/utils.rs
@@ -36,6 +36,7 @@ use common_utils::{
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
address::{Address, AddressDetails, PhoneDetails},
+ mandates,
network_tokenization::NetworkTokenNumber,
payment_method_data::{self, Card, CardDetailsForNetworkTransactionId, PaymentMethodData},
router_data::{
@@ -5043,6 +5044,62 @@ pub fn is_mandate_supported(
}
}
+pub fn get_mandate_details(
+ setup_mandate_details: Option<mandates::MandateData>,
+) -> Result<Option<mandates::MandateAmountData>, error_stack::Report<errors::ConnectorError>> {
+ setup_mandate_details
+ .map(|mandate_data| match &mandate_data.mandate_type {
+ Some(mandates::MandateDataType::SingleUse(mandate))
+ | Some(mandates::MandateDataType::MultiUse(Some(mandate))) => Ok(mandate.clone()),
+ Some(mandates::MandateDataType::MultiUse(None)) => {
+ Err(errors::ConnectorError::MissingRequiredField {
+ field_name: "setup_future_usage.mandate_data.mandate_type.multi_use.amount",
+ }
+ .into())
+ }
+ None => Err(errors::ConnectorError::MissingRequiredField {
+ field_name: "setup_future_usage.mandate_data.mandate_type",
+ }
+ .into()),
+ })
+ .transpose()
+}
+
+pub fn collect_values_by_removing_signature(value: &Value, signature: &String) -> Vec<String> {
+ match value {
+ Value::Null => vec!["null".to_owned()],
+ Value::Bool(b) => vec![b.to_string()],
+ Value::Number(n) => match n.as_f64() {
+ Some(f) => vec![format!("{f:.2}")],
+ None => vec![n.to_string()],
+ },
+ Value::String(s) => {
+ if signature == s {
+ vec![]
+ } else {
+ vec![s.clone()]
+ }
+ }
+ Value::Array(arr) => arr
+ .iter()
+ .flat_map(|v| collect_values_by_removing_signature(v, signature))
+ .collect(),
+ Value::Object(obj) => obj
+ .values()
+ .flat_map(|v| collect_values_by_removing_signature(v, signature))
+ .collect(),
+ }
+}
+
+pub fn collect_and_sort_values_by_removing_signature(
+ value: &Value,
+ signature: &String,
+) -> Vec<String> {
+ let mut values = collect_values_by_removing_signature(value, signature);
+ values.sort();
+ values
+}
+
#[derive(Debug, strum::Display, Eq, PartialEq, Hash)]
pub enum PaymentMethodDataType {
Card,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index c4720f60ff6..9f99b4c61a3 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -1,17 +1,11 @@
pub mod adyen;
pub mod adyenplatform;
-pub mod authorizedotnet;
-pub mod checkout;
#[cfg(feature = "dummy_connector")]
pub mod dummyconnector;
pub mod ebanx;
pub mod gpayments;
pub mod netcetera;
pub mod nmi;
-pub mod noon;
-pub mod opayo;
-pub mod opennode;
-pub mod payme;
pub mod payone;
pub mod paypal;
pub mod plaid;
@@ -19,34 +13,34 @@ pub mod riskified;
pub mod signifyd;
pub mod stripe;
pub mod threedsecureio;
-pub mod trustpay;
pub mod utils;
pub mod wellsfargopayout;
pub mod wise;
pub use hyperswitch_connectors::connectors::{
- aci, aci::Aci, airwallex, airwallex::Airwallex, amazonpay, amazonpay::Amazonpay, bambora,
- bambora::Bambora, bamboraapac, bamboraapac::Bamboraapac, bankofamerica,
- bankofamerica::Bankofamerica, billwerk, billwerk::Billwerk, bitpay, bitpay::Bitpay, bluesnap,
- bluesnap::Bluesnap, boku, boku::Boku, braintree, braintree::Braintree, cashtocode,
- cashtocode::Cashtocode, chargebee::Chargebee, coinbase, coinbase::Coinbase, 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,
- getnet, getnet::Getnet, globalpay, globalpay::Globalpay, globepay, globepay::Globepay,
- gocardless, gocardless::Gocardless, helcim, helcim::Helcim, iatapay, iatapay::Iatapay, inespay,
- inespay::Inespay, itaubank, itaubank::Itaubank, jpmorgan, jpmorgan::Jpmorgan, klarna,
- klarna::Klarna, mifinity, mifinity::Mifinity, mollie, mollie::Mollie, moneris,
- moneris::Moneris, multisafepay, multisafepay::Multisafepay, nexinets, nexinets::Nexinets,
- nexixpay, nexixpay::Nexixpay, nomupay, nomupay::Nomupay, novalnet, novalnet::Novalnet, nuvei,
- nuvei::Nuvei, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, paystack, paystack::Paystack,
- 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,
- stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, thunes, thunes::Thunes,
- tsys, tsys::Tsys, unified_authentication_service,
+ aci, aci::Aci, airwallex, airwallex::Airwallex, amazonpay, amazonpay::Amazonpay,
+ authorizedotnet, authorizedotnet::Authorizedotnet, bambora, bambora::Bambora, bamboraapac,
+ bamboraapac::Bamboraapac, bankofamerica, bankofamerica::Bankofamerica, billwerk,
+ billwerk::Billwerk, bitpay, bitpay::Bitpay, bluesnap, bluesnap::Bluesnap, boku, boku::Boku,
+ braintree, braintree::Braintree, cashtocode, cashtocode::Cashtocode, chargebee::Chargebee,
+ checkout, checkout::Checkout, coinbase, coinbase::Coinbase, 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, getnet, getnet::Getnet, globalpay, globalpay::Globalpay,
+ globepay, globepay::Globepay, gocardless, gocardless::Gocardless, helcim, helcim::Helcim,
+ iatapay, iatapay::Iatapay, inespay, inespay::Inespay, itaubank, itaubank::Itaubank, jpmorgan,
+ jpmorgan::Jpmorgan, klarna, klarna::Klarna, mifinity, mifinity::Mifinity, mollie,
+ mollie::Mollie, moneris, moneris::Moneris, multisafepay, multisafepay::Multisafepay, nexinets,
+ nexinets::Nexinets, nexixpay, nexixpay::Nexixpay, nomupay, nomupay::Nomupay, noon, noon::Noon,
+ novalnet, novalnet::Novalnet, nuvei, nuvei::Nuvei, opayo, opayo::Opayo, opennode,
+ opennode::Opennode, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, payme, payme::Payme,
+ paystack, paystack::Paystack, 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, stripebilling, stripebilling::Stripebilling, taxjar, taxjar::Taxjar, thunes,
+ thunes::Thunes, trustpay, trustpay::Trustpay, 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,
@@ -55,10 +49,8 @@ pub use hyperswitch_connectors::connectors::{
#[cfg(feature = "dummy_connector")]
pub use self::dummyconnector::DummyConnector;
pub use self::{
- adyen::Adyen, adyenplatform::Adyenplatform, authorizedotnet::Authorizedotnet,
- checkout::Checkout, ebanx::Ebanx, gpayments::Gpayments, netcetera::Netcetera, nmi::Nmi,
- noon::Noon, opayo::Opayo, opennode::Opennode, payme::Payme, payone::Payone, paypal::Paypal,
- plaid::Plaid, riskified::Riskified, signifyd::Signifyd, stripe::Stripe,
- threedsecureio::Threedsecureio, trustpay::Trustpay, wellsfargopayout::Wellsfargopayout,
- wise::Wise,
+ adyen::Adyen, adyenplatform::Adyenplatform, ebanx::Ebanx, gpayments::Gpayments,
+ netcetera::Netcetera, nmi::Nmi, payone::Payone, paypal::Paypal, plaid::Plaid,
+ riskified::Riskified, signifyd::Signifyd, stripe::Stripe, threedsecureio::Threedsecureio,
+ wellsfargopayout::Wellsfargopayout, wise::Wise,
};
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 d19afa5368e..4f963755b1b 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -700,22 +700,15 @@ macro_rules! default_imp_for_new_connector_integration_payment {
default_imp_for_new_connector_integration_payment!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wellsfargopayout,
connector::Wise,
@@ -741,22 +734,15 @@ macro_rules! default_imp_for_new_connector_integration_refund {
default_imp_for_new_connector_integration_refund!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -776,22 +762,15 @@ macro_rules! default_imp_for_new_connector_integration_connector_access_token {
default_imp_for_new_connector_integration_connector_access_token!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -833,22 +812,15 @@ macro_rules! default_imp_for_new_connector_integration_submit_evidence {
default_imp_for_new_connector_integration_accept_dispute!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -872,22 +844,15 @@ macro_rules! default_imp_for_new_connector_integration_defend_dispute {
default_imp_for_new_connector_integration_defend_dispute!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -895,22 +860,15 @@ default_imp_for_new_connector_integration_defend_dispute!(
default_imp_for_new_connector_integration_submit_evidence!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -945,22 +903,15 @@ macro_rules! default_imp_for_new_connector_integration_file_upload {
default_imp_for_new_connector_integration_file_upload!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1023,7 +974,6 @@ default_imp_for_new_connector_integration_payouts!(
connector::Nomupay,
connector::Noon,
connector::Novalnet,
- connector::Opayo,
connector::Opennode,
connector::Paybox,
connector::Payeezy,
@@ -1079,22 +1029,15 @@ macro_rules! default_imp_for_new_connector_integration_payouts_create {
default_imp_for_new_connector_integration_payouts_create!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1121,22 +1064,15 @@ macro_rules! default_imp_for_new_connector_integration_payouts_eligibility {
default_imp_for_new_connector_integration_payouts_eligibility!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1163,22 +1099,15 @@ macro_rules! default_imp_for_new_connector_integration_payouts_fulfill {
default_imp_for_new_connector_integration_payouts_fulfill!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1205,22 +1134,15 @@ macro_rules! default_imp_for_new_connector_integration_payouts_cancel {
default_imp_for_new_connector_integration_payouts_cancel!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1247,22 +1169,15 @@ macro_rules! default_imp_for_new_connector_integration_payouts_quote {
default_imp_for_new_connector_integration_payouts_quote!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1289,22 +1204,15 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient {
default_imp_for_new_connector_integration_payouts_recipient!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1331,23 +1239,16 @@ macro_rules! default_imp_for_new_connector_integration_payouts_sync {
default_imp_for_new_connector_integration_payouts_sync!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wise,
connector::Plaid
);
@@ -1373,22 +1274,15 @@ macro_rules! default_imp_for_new_connector_integration_payouts_recipient_account
default_imp_for_new_connector_integration_payouts_recipient_account!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1413,22 +1307,15 @@ macro_rules! default_imp_for_new_connector_integration_webhook_source_verificati
default_imp_for_new_connector_integration_webhook_source_verification!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1547,22 +1434,15 @@ macro_rules! default_imp_for_new_connector_integration_frm_sale {
default_imp_for_new_connector_integration_frm_sale!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1589,22 +1469,15 @@ macro_rules! default_imp_for_new_connector_integration_frm_checkout {
default_imp_for_new_connector_integration_frm_checkout!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1631,22 +1504,15 @@ macro_rules! default_imp_for_new_connector_integration_frm_transaction {
default_imp_for_new_connector_integration_frm_transaction!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1673,22 +1539,15 @@ macro_rules! default_imp_for_new_connector_integration_frm_fulfillment {
default_imp_for_new_connector_integration_frm_fulfillment!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1715,22 +1574,15 @@ macro_rules! default_imp_for_new_connector_integration_frm_record_return {
default_imp_for_new_connector_integration_frm_record_return!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1754,22 +1606,15 @@ macro_rules! default_imp_for_new_connector_integration_revoking_mandates {
default_imp_for_new_connector_integration_revoking_mandates!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
- connector::Trustpay,
connector::Threedsecureio,
connector::Wise,
connector::Plaid
@@ -1953,16 +1798,10 @@ macro_rules! default_imp_for_new_connector_integration_uas {
default_imp_for_new_connector_integration_uas!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -1970,7 +1809,6 @@ default_imp_for_new_connector_integration_uas!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index af5b5e54cbe..02a4fe2386c 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -217,20 +217,15 @@ impl<const T: u8>
default_imp_for_complete_authorize!(
connector::Adyenplatform,
connector::Adyen,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
connector::Payone,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wise,
connector::Wellsfargopayout
);
@@ -263,23 +258,16 @@ impl<const T: u8>
default_imp_for_webhook_source_verification!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -314,23 +302,16 @@ impl<const T: u8>
default_imp_for_create_customer!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -370,8 +351,6 @@ default_imp_for_connector_redirect_response!(
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
- connector::Opayo,
- connector::Opennode,
connector::Payone,
connector::Plaid,
connector::Riskified,
@@ -517,15 +496,10 @@ impl<const T: u8>
default_imp_for_accept_dispute!(
connector::Adyenplatform,
- connector::Authorizedotnet,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -533,7 +507,6 @@ default_imp_for_accept_dispute!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -589,22 +562,16 @@ impl<const T: u8>
default_imp_for_file_upload!(
connector::Adyenplatform,
- connector::Authorizedotnet,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Threedsecureio,
- connector::Trustpay,
- connector::Opennode,
connector::Wellsfargopayout,
connector::Wise
);
@@ -638,22 +605,16 @@ impl<const T: u8>
default_imp_for_submit_evidence!(
connector::Adyenplatform,
- connector::Authorizedotnet,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Threedsecureio,
- connector::Trustpay,
- connector::Opennode,
connector::Wellsfargopayout,
connector::Wise
);
@@ -687,14 +648,10 @@ impl<const T: u8>
default_imp_for_defend_dispute!(
connector::Adyenplatform,
- connector::Authorizedotnet,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -702,8 +659,6 @@ default_imp_for_defend_dispute!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
- connector::Opennode,
connector::Wellsfargopayout,
connector::Wise
);
@@ -752,14 +707,9 @@ impl<const T: u8>
default_imp_for_pre_processing_steps!(
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
connector::Payone,
connector::Plaid,
connector::Riskified,
@@ -785,18 +735,11 @@ default_imp_for_post_processing_steps!(
connector::Adyenplatform,
connector::Adyen,
connector::Nmi,
- connector::Payme,
connector::Paypal,
connector::Stripe,
- connector::Trustpay,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
connector::Payone,
connector::Riskified,
connector::Signifyd,
@@ -817,20 +760,13 @@ macro_rules! default_imp_for_payouts {
impl<const T: u8> Payouts for connector::DummyConnector<T> {}
default_imp_for_payouts!(
- connector::Authorizedotnet,
- connector::Checkout,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout
);
@@ -864,21 +800,14 @@ impl<const T: u8>
#[cfg(feature = "payouts")]
default_imp_for_payouts_create!(
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout
);
@@ -913,23 +842,16 @@ impl<const T: u8>
default_imp_for_payouts_retrieve!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -967,15 +889,9 @@ impl<const T: u8>
#[cfg(feature = "payouts")]
default_imp_for_payouts_eligibility!(
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -983,7 +899,6 @@ default_imp_for_payouts_eligibility!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout
);
@@ -1016,20 +931,13 @@ impl<const T: u8>
#[cfg(feature = "payouts")]
default_imp_for_payouts_fulfill!(
- connector::Authorizedotnet,
- connector::Checkout,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout
);
@@ -1063,22 +971,15 @@ impl<const T: u8>
#[cfg(feature = "payouts")]
default_imp_for_payouts_cancel!(
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout
);
@@ -1113,15 +1014,9 @@ impl<const T: u8>
default_imp_for_payouts_quote!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -1129,7 +1024,6 @@ default_imp_for_payouts_quote!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout
);
@@ -1164,22 +1058,15 @@ impl<const T: u8>
default_imp_for_payouts_recipient!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout
);
@@ -1217,23 +1104,16 @@ impl<const T: u8>
default_imp_for_payouts_recipient_account!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1268,16 +1148,10 @@ impl<const T: u8>
default_imp_for_approve!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -1285,7 +1159,6 @@ default_imp_for_approve!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1320,16 +1193,10 @@ impl<const T: u8>
default_imp_for_reject!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -1337,7 +1204,6 @@ default_imp_for_reject!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1478,22 +1344,15 @@ impl<const T: u8>
default_imp_for_frm_sale!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1530,22 +1389,15 @@ impl<const T: u8>
default_imp_for_frm_checkout!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1582,22 +1434,15 @@ impl<const T: u8>
default_imp_for_frm_transaction!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1634,22 +1479,15 @@ impl<const T: u8>
default_imp_for_frm_fulfillment!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1686,22 +1524,15 @@ impl<const T: u8>
default_imp_for_frm_record_return!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1736,16 +1567,10 @@ impl<const T: u8>
default_imp_for_incremental_authorization!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -1753,7 +1578,6 @@ default_imp_for_incremental_authorization!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -1786,15 +1610,10 @@ impl<const T: u8>
default_imp_for_revoking_mandates!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -1802,7 +1621,6 @@ default_imp_for_revoking_mandates!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wise
);
@@ -2011,16 +1829,10 @@ impl<const T: u8>
default_imp_for_authorize_session_token!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -2028,7 +1840,6 @@ default_imp_for_authorize_session_token!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -2061,16 +1872,10 @@ impl<const T: u8>
default_imp_for_calculate_tax!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -2078,7 +1883,6 @@ default_imp_for_calculate_tax!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -2111,23 +1915,16 @@ impl<const T: u8>
default_imp_for_session_update!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -2160,23 +1957,16 @@ impl<const T: u8>
default_imp_for_post_session_tokens!(
connector::Adyen,
connector::Adyenplatform,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Plaid,
connector::Riskified,
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -2212,16 +2002,10 @@ impl<const T: u8>
default_imp_for_uas_pre_authentication!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -2229,7 +2013,6 @@ default_imp_for_uas_pre_authentication!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -2262,16 +2045,10 @@ impl<const T: u8>
default_imp_for_uas_post_authentication!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -2279,7 +2056,6 @@ default_imp_for_uas_post_authentication!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -2301,16 +2077,10 @@ macro_rules! default_imp_for_uas_authentication_confirmation {
default_imp_for_uas_authentication_confirmation!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -2318,7 +2088,6 @@ default_imp_for_uas_authentication_confirmation!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
@@ -2364,16 +2133,10 @@ impl<const T: u8>
default_imp_for_uas_authentication!(
connector::Adyenplatform,
connector::Adyen,
- connector::Authorizedotnet,
- connector::Checkout,
connector::Ebanx,
connector::Gpayments,
connector::Netcetera,
connector::Nmi,
- connector::Noon,
- connector::Opayo,
- connector::Opennode,
- connector::Payme,
connector::Payone,
connector::Paypal,
connector::Plaid,
@@ -2381,7 +2144,6 @@ default_imp_for_uas_authentication!(
connector::Signifyd,
connector::Stripe,
connector::Threedsecureio,
- connector::Trustpay,
connector::Wellsfargopayout,
connector::Wise
);
|
refactor
|
[AUTHORIZEDOTNET,CHECKOUT,NOON,OPAYO,OPENNODE,PAYME,TRUSTPAY] Move to crate hyperswitch_connectors (#7235)
|
ff1e094b4822c7de2eccce5415b9177790ca5538
|
2023-01-09 14:02:40
|
Narayan Bhat
|
fix(payment_update): allow update when in requires_customer_action (#309)
| false
|
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 427e9fbc3d6..5641f13670e 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -307,10 +307,13 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
let customer_id = customer.map(|c| c.customer_id);
let get_status = || {
+ let current_intent_status = payment_data.payment_intent.status;
if is_payment_method_unavailable {
return enums::IntentStatus::RequiresPaymentMethod;
}
- if !payment_data.confirm.unwrap_or(true) {
+ if !payment_data.confirm.unwrap_or(true)
+ || current_intent_status == enums::IntentStatus::RequiresCustomerAction
+ {
enums::IntentStatus::RequiresConfirmation
} else {
payment_data.payment_intent.status
|
fix
|
allow update when in requires_customer_action (#309)
|
ad7886a6ff636f99e62601483c907f5c90954eb4
|
2024-06-13 19:10:40
|
Sarthak Soni
|
feat(payment_methods): Use Ephemeral auth for pm list and pm delete (#4996)
| false
|
diff --git a/crates/router/src/compatibility/stripe/customers.rs b/crates/router/src/compatibility/stripe/customers.rs
index 65abb012b9a..264f205c907 100644
--- a/crates/router/src/compatibility/stripe/customers.rs
+++ b/crates/router/src/compatibility/stripe/customers.rs
@@ -195,6 +195,7 @@ pub async fn list_customer_payment_method_api(
auth.key_store,
Some(req),
Some(&customer_id),
+ None,
)
},
&auth::ApiKeyAuth,
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index 04983ed8b19..66940fa9508 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -64,6 +64,7 @@ use crate::{
pii::prelude::*,
routes::{
self,
+ app::SessionStateInfo,
metrics::{self, request},
payment_methods::ParentPaymentMethodToken,
},
@@ -3107,10 +3108,25 @@ pub async fn do_list_customer_pm_fetch_customer_if_not_passed(
key_store: domain::MerchantKeyStore,
req: Option<api::PaymentMethodListRequest>,
customer_id: Option<&id_type::CustomerId>,
+ ephemeral_api_key: Option<&str>,
) -> errors::RouterResponse<api::CustomerPaymentMethodsListResponse> {
let db = state.store.as_ref();
let limit = req.clone().and_then(|pml_req| pml_req.limit);
+ let auth_cust = if let Some(key) = ephemeral_api_key {
+ let key = state
+ .store()
+ .get_ephemeral_key(key)
+ .await
+ .change_context(errors::ApiErrorResponse::Unauthorized)?;
+
+ Some(key.customer_id.clone())
+ } else {
+ None
+ };
+
+ let customer_id = customer_id.or(auth_cust.as_ref());
+
if let Some(customer_id) = customer_id {
Box::pin(list_customer_payment_method(
&state,
diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs
index 87366cf5c6d..4684edbd18d 100644
--- a/crates/router/src/routes/customers.rs
+++ b/crates/router/src/routes/customers.rs
@@ -47,7 +47,7 @@ pub async fn customers_retrieve(
let auth = if auth::is_jwt_auth(req.headers()) {
Box::new(auth::JWTAuth(Permission::CustomerRead))
} else {
- match auth::is_ephemeral_auth(req.headers(), &payload.customer_id) {
+ match auth::is_ephemeral_auth(req.headers()) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
}
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index e36a8fc3ea5..09b5c625711 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -139,7 +139,7 @@ pub async fn list_customer_payment_method_api(
let payload = query_payload.into_inner();
let customer_id = customer_id.into_inner().0;
- let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), &customer_id) {
+ let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
@@ -155,6 +155,7 @@ pub async fn list_customer_payment_method_api(
auth.key_store,
Some(req),
Some(&customer_id),
+ None,
)
},
&*ephemeral_auth,
@@ -194,10 +195,12 @@ pub async fn list_customer_payment_method_api_client(
) -> HttpResponse {
let flow = Flow::CustomerPaymentMethodsList;
let payload = query_payload.into_inner();
- let (auth, _) = match auth::check_client_secret_and_get_auth(req.headers(), &payload) {
- Ok((auth, _auth_flow)) => (auth, _auth_flow),
- Err(e) => return api::log_and_return_error_response(e),
- };
+ let api_key = auth::get_api_key(req.headers()).ok();
+ let (auth, _, is_ephemeral_auth) =
+ match auth::get_ephemeral_or_other_auth(req.headers(), false, Some(&payload)).await {
+ Ok((auth, _auth_flow, is_ephemeral_auth)) => (auth, _auth_flow, is_ephemeral_auth),
+ Err(e) => return api::log_and_return_error_response(e),
+ };
Box::pin(api::server_wrap(
flow,
@@ -211,6 +214,7 @@ pub async fn list_customer_payment_method_api_client(
auth.key_store,
Some(req),
None,
+ is_ephemeral_auth.then_some(api_key).flatten(),
)
},
&*auth,
@@ -291,6 +295,11 @@ pub async fn payment_method_delete_api(
let pm = PaymentMethodId {
payment_method_id: payment_method_id.into_inner().0,
};
+ let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) {
+ Ok(auth) => auth,
+ Err(err) => return api::log_and_return_error_response(err),
+ };
+
Box::pin(api::server_wrap(
flow,
state,
@@ -299,7 +308,7 @@ pub async fn payment_method_delete_api(
|state, auth, req, _| {
cards::delete_payment_method(state, auth.merchant_account, req, auth.key_store)
},
- &auth::ApiKeyAuth,
+ &*ephemeral_auth,
api_locking::LockAction::NotApplicable,
))
.await
@@ -345,7 +354,7 @@ pub async fn default_payment_method_set_api(
let pc = payload.clone();
let customer_id = &pc.customer_id;
- let ephemeral_auth = match auth::is_ephemeral_auth(req.headers(), customer_id) {
+ let ephemeral_auth = match auth::is_ephemeral_auth(req.headers()) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(err),
};
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 72d0860eed9..e2224da29ea 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -5,7 +5,7 @@ use api_models::{
};
use async_trait::async_trait;
use common_enums::TokenPurpose;
-use common_utils::{date_time, id_type};
+use common_utils::date_time;
use error_stack::{report, ResultExt};
use jsonwebtoken::{decode, Algorithm, DecodingKey, Validation};
use masking::PeekInterface;
@@ -440,7 +440,7 @@ where
}
#[derive(Debug)]
-pub struct EphemeralKeyAuth(pub id_type::CustomerId);
+pub struct EphemeralKeyAuth;
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for EphemeralKeyAuth
@@ -460,9 +460,6 @@ where
.await
.change_context(errors::ApiErrorResponse::Unauthorized)?;
- if ephemeral_key.customer_id.ne(&self.0) {
- return Err(report!(errors::ApiErrorResponse::InvalidEphemeralKey));
- }
MerchantIdAuth(ephemeral_key.merchant_id)
.authenticate_and_fetch(request_headers, state)
.await
@@ -1046,16 +1043,43 @@ where
Ok((Box::new(ApiKeyAuth), api::AuthFlow::Merchant))
}
+pub async fn get_ephemeral_or_other_auth<T>(
+ headers: &HeaderMap,
+ is_merchant_flow: bool,
+ payload: Option<&impl ClientSecretFetch>,
+) -> RouterResult<(
+ Box<dyn AuthenticateAndFetch<AuthenticationData, T>>,
+ api::AuthFlow,
+ bool,
+)>
+where
+ T: SessionStateInfo,
+ ApiKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
+ PublishableKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
+ EphemeralKeyAuth: AuthenticateAndFetch<AuthenticationData, T>,
+{
+ let api_key = get_api_key(headers)?;
+
+ if api_key.starts_with("epk") {
+ Ok((Box::new(EphemeralKeyAuth), api::AuthFlow::Client, true))
+ } else if is_merchant_flow {
+ Ok((Box::new(ApiKeyAuth), api::AuthFlow::Merchant, false))
+ } else {
+ let payload = payload.get_required_value("ClientSecretFetch")?;
+ let (auth, auth_flow) = check_client_secret_and_get_auth(headers, payload)?;
+ Ok((auth, auth_flow, false))
+ }
+}
+
pub fn is_ephemeral_auth<A: SessionStateInfo + Sync>(
headers: &HeaderMap,
- customer_id: &id_type::CustomerId,
) -> RouterResult<Box<dyn AuthenticateAndFetch<AuthenticationData, A>>> {
let api_key = get_api_key(headers)?;
if !api_key.starts_with("epk") {
Ok(Box::new(ApiKeyAuth))
} else {
- Ok(Box::new(EphemeralKeyAuth(customer_id.to_owned())))
+ Ok(Box::new(EphemeralKeyAuth))
}
}
|
feat
|
Use Ephemeral auth for pm list and pm delete (#4996)
|
88bca86e486c0dce568487b6a9750a52fda501d3
|
2025-03-12 05:58:14
|
github-actions
|
chore(version): 2025.03.12.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9e086199c51..859c044c5ed 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,38 @@
All notable changes to HyperSwitch will be documented here.
+- - -
+
+## 2025.03.12.0
+
+### Features
+
+- **connector:**
+ - Rapyd, Bamboraapac, Gocardless, Powertranz, Shift4 and Worldline added in feature matrix ([#7136](https://github.com/juspay/hyperswitch/pull/7136)) ([`9fe9e9e`](https://github.com/juspay/hyperswitch/commit/9fe9e9e0bc59980014254d925add8adb5ee028ad))
+ - [BILLWERK, FISERVEMEA, TSYS] add in feature matrix api ([#7165](https://github.com/juspay/hyperswitch/pull/7165)) ([`e15c814`](https://github.com/juspay/hyperswitch/commit/e15c8146aa29430423e884677ac0e7c6834b72fa))
+ - Implement wallet mandates for authorizedotnet ([#7412](https://github.com/juspay/hyperswitch/pull/7412)) ([`07733a5`](https://github.com/juspay/hyperswitch/commit/07733a5c5eb94c318626421f2b4420dce0ddd39b))
+- **process_tracker:** Add a version column in process tracker table ([#7389](https://github.com/juspay/hyperswitch/pull/7389)) ([`dbecdcf`](https://github.com/juspay/hyperswitch/commit/dbecdcf1cfae9e6f81a0b48a4a7fb273ad314071))
+
+### Bug Fixes
+
+- **connector:** [BRAINTREE] Changed Attempt Status Mapping for Braintree ([#7471](https://github.com/juspay/hyperswitch/pull/7471)) ([`69d8f35`](https://github.com/juspay/hyperswitch/commit/69d8f351b6fb7cb7ba800e6b4d9a541f7f374787))
+- **postman:** Update expected status from `processing` to `requires_capture` in payment confirmation tests ([#7458](https://github.com/juspay/hyperswitch/pull/7458)) ([`ce84bb9`](https://github.com/juspay/hyperswitch/commit/ce84bb9245d6bdb4fb9627abec639754c868d54a))
+- **router:** Pass card network for external 3DS from additional_payment_method_data ([#7473](https://github.com/juspay/hyperswitch/pull/7473)) ([`5cdfe83`](https://github.com/juspay/hyperswitch/commit/5cdfe8325481909a8a1596f967303eff44ffbcec))
+
+### Refactors
+
+- **core:** Filter default routing config response based on connector type ([#7199](https://github.com/juspay/hyperswitch/pull/7199)) ([`18db67c`](https://github.com/juspay/hyperswitch/commit/18db67c755ebb793223b476e556a4a05617c9a87))
+- **pm:** Create new crate for payment methods ([#7355](https://github.com/juspay/hyperswitch/pull/7355)) ([`a31d140`](https://github.com/juspay/hyperswitch/commit/a31d1403eedbe7abd88139e2a9e9c96047324edb))
+
+### Miscellaneous Tasks
+
+- **postman:** Update Postman collection files ([`fd51beb`](https://github.com/juspay/hyperswitch/commit/fd51bebc52835875919ccae1f31f32bc0eb4d657))
+- **wasm:** Show allowed auth methods option in google pay ([#7425](https://github.com/juspay/hyperswitch/pull/7425)) ([`2f0005a`](https://github.com/juspay/hyperswitch/commit/2f0005ae382fcbcb941d179f0a0d2dd5f93f724a))
+- Update wise connector cypress creds ([#7477](https://github.com/juspay/hyperswitch/pull/7477)) ([`cb256dc`](https://github.com/juspay/hyperswitch/commit/cb256dcdac0533af51a6c77eef0039121a8ee110))
+
+**Full Changelog:** [`2025.03.11.0...2025.03.12.0`](https://github.com/juspay/hyperswitch/compare/2025.03.11.0...2025.03.12.0)
+
+
- - -
## 2025.03.11.0
|
chore
|
2025.03.12.0
|
9cbe38459681784d37ec2a6588a2618ae941a667
|
2025-03-07 18:48:40
|
Hrithikesh
|
chore: add migrate_v2_compatible recipe in justfile (#7415)
| false
|
diff --git a/justfile b/justfile
index f98da88e40d..ace2d3349d3 100644
--- a/justfile
+++ b/justfile
@@ -162,23 +162,24 @@ default_db_url := 'postgresql://' + db_user + ':' + db_password + '@' + db_host
database_url := env_var_or_default('DATABASE_URL', default_db_url)
default_migration_params := ''
v2_migration_dir := source_directory() / 'v2_migrations'
+v2_compatible_migrations := source_directory() / 'v2_compatible_migrations'
v1_migration_dir := source_directory() / 'migrations'
resultant_dir := source_directory() / 'final-migrations'
-# Copy v1 and v2 migrations to a single directory
+# Copy migrations in {{dir_1}} and {{dir_2}} to a single directory {{resultant_dir}} after prefixing the subdirectories of {{dir_2}} with {{prefix}}
[private]
-copy_migrations:
+prefix_and_copy_migrations dir_1 dir_2 prefix resultant_dir:
#! /usr/bin/env bash
mkdir -p {{resultant_dir}}
- cp -r {{v1_migration_dir}}/* {{resultant_dir}}/
+ cp -r {{dir_1}}/* {{resultant_dir}}/ > /dev/null 2>&1
- # Prefix v2 migrations with 9
+ # Prefix v2 migrations with {{prefix}}
sh -c '
- for dir in "{{v2_migration_dir}}"/*; do
- if [ -d "$dir" ]; then
- base_name=$(basename "$dir")
- new_name="9$base_name"
- cp -r "$dir" "{{resultant_dir}}/$new_name"
+ for dir in "{{dir_2}}"/*; do
+ if [ -d "${dir}" ]; then
+ base_name=$(basename "${dir}")
+ new_name="{{prefix}}${base_name}"
+ cp -r "${dir}" "{{resultant_dir}}/${new_name}"
fi
done
'
@@ -212,13 +213,28 @@ migrate_v2 operation=default_operation *args='':
set -euo pipefail
EXIT_CODE=0
- just copy_migrations
+ just prefix_and_copy_migrations {{ v1_migration_dir }} {{ v2_compatible_migrations }} 8 {{ resultant_dir }}
+ just prefix_and_copy_migrations {{ resultant_dir }} {{ v2_migration_dir }} 9 {{ resultant_dir }}
just run_migration {{ operation }} {{ resultant_dir }} {{ v2_config_file_dir }} {{ database_url }} {{ args }} || EXIT_CODE=$?
just delete_dir_if_exists
exit $EXIT_CODE
+# Run database migrations compatible with both v1 and v2
+migrate_v2_compatible:
+ #! /usr/bin/env bash
+ set -euo pipefail
+
+ EXIT_CODE=0
+ just prefix_and_copy_migrations {{ v1_migration_dir }} {{ v2_compatible_migrations }} 8 {{ resultant_dir }}
+
+ # Run the compatible migrations
+ just run_migration run {{ resultant_dir }} {{ database_url }} || EXIT_CODE=$?
+
+ just delete_dir_if_exists
+ exit $EXIT_CODE
+
# Drop database if exists and then create a new 'hyperswitch_db' Database
-resurrect database_name='hyperswitch_db':
+resurrect database_name=db_name:
psql -U postgres -c 'DROP DATABASE IF EXISTS {{ database_name }}';
psql -U postgres -c 'CREATE DATABASE {{ database_name }}';
diff --git a/v2_migrations/2024-07-29-155137_add_v2_soft_delete_db_enum/down.sql b/v2_compatible_migrations/2024-07-29-155137_add_v2_soft_delete_db_enum/down.sql
similarity index 100%
rename from v2_migrations/2024-07-29-155137_add_v2_soft_delete_db_enum/down.sql
rename to v2_compatible_migrations/2024-07-29-155137_add_v2_soft_delete_db_enum/down.sql
diff --git a/v2_migrations/2024-07-29-155137_add_v2_soft_delete_db_enum/up.sql b/v2_compatible_migrations/2024-07-29-155137_add_v2_soft_delete_db_enum/up.sql
similarity index 100%
rename from v2_migrations/2024-07-29-155137_add_v2_soft_delete_db_enum/up.sql
rename to v2_compatible_migrations/2024-07-29-155137_add_v2_soft_delete_db_enum/up.sql
diff --git a/v2_migrations/2024-08-28-081721_add_v2_columns/down.sql b/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/down.sql
similarity index 100%
rename from v2_migrations/2024-08-28-081721_add_v2_columns/down.sql
rename to v2_compatible_migrations/2024-08-28-081721_add_v2_columns/down.sql
diff --git a/v2_migrations/2024-08-28-081721_add_v2_columns/up.sql b/v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql
similarity index 100%
rename from v2_migrations/2024-08-28-081721_add_v2_columns/up.sql
rename to v2_compatible_migrations/2024-08-28-081721_add_v2_columns/up.sql
diff --git a/v2_migrations/2024-08-28-081747_recreate_ids_for_v2/down.sql b/v2_compatible_migrations/2024-08-28-081747_recreate_ids_for_v2/down.sql
similarity index 100%
rename from v2_migrations/2024-08-28-081747_recreate_ids_for_v2/down.sql
rename to v2_compatible_migrations/2024-08-28-081747_recreate_ids_for_v2/down.sql
diff --git a/v2_migrations/2024-08-28-081747_recreate_ids_for_v2/up.sql b/v2_compatible_migrations/2024-08-28-081747_recreate_ids_for_v2/up.sql
similarity index 100%
rename from v2_migrations/2024-08-28-081747_recreate_ids_for_v2/up.sql
rename to v2_compatible_migrations/2024-08-28-081747_recreate_ids_for_v2/up.sql
diff --git a/v2_migrations/2024-08-28-081722_drop_not_null_constraints_on_v1_columns/down.sql b/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/down.sql
similarity index 100%
rename from v2_migrations/2024-08-28-081722_drop_not_null_constraints_on_v1_columns/down.sql
rename to v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/down.sql
diff --git a/v2_migrations/2024-08-28-081722_drop_not_null_constraints_on_v1_columns/up.sql b/v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql
similarity index 100%
rename from v2_migrations/2024-08-28-081722_drop_not_null_constraints_on_v1_columns/up.sql
rename to v2_compatible_migrations/2024-08-28-081757_drop_not_null_constraints_on_v1_columns/up.sql
|
chore
|
add migrate_v2_compatible recipe in justfile (#7415)
|
b8e2b1c5f42dcd41a3d02e0d2422e1407b6a41de
|
2023-05-04 19:28:20
|
Nachiket Kanore
|
refactor: use newtype pattern for email addresses (#819)
| false
|
diff --git a/Cargo.lock b/Cargo.lock
index 0935e38b2e4..46c98b30cc9 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -1305,6 +1305,7 @@ version = "0.1.0"
dependencies = [
"async-trait",
"bytes",
+ "diesel",
"error-stack",
"fake",
"futures",
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index f943d536e12..8e1302f5185 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -228,7 +228,7 @@ pub struct MerchantDetails {
/// The merchant's primary email address
#[schema(value_type = Option<String>, max_length = 255, example = "[email protected]")]
- pub primary_email: Option<Secret<String, pii::Email>>,
+ pub primary_email: Option<pii::Email>,
/// The merchant's secondary contact name
#[schema(value_type = Option<String>, max_length= 255, example = "John Doe2")]
@@ -240,7 +240,7 @@ pub struct MerchantDetails {
/// The merchant's secondary email address
#[schema(value_type = Option<String>, max_length = 255, example = "[email protected]")]
- pub secondary_email: Option<Secret<String, pii::Email>>,
+ pub secondary_email: Option<pii::Email>,
/// The business website of the merchant
#[schema(max_length = 255, example = "www.example.com")]
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs
index a48be2e9dad..b95d1758a4d 100644
--- a/crates/api_models/src/customers.rs
+++ b/crates/api_models/src/customers.rs
@@ -19,7 +19,7 @@ pub struct CustomerRequest {
pub name: Option<String>,
/// The customer's email address
#[schema(value_type = Option<String>,max_length = 255, example = "[email protected]")]
- pub email: Option<Secret<String, pii::Email>>,
+ pub email: Option<pii::Email>,
/// The customer's phone number
#[schema(value_type = Option<String>,max_length = 255, example = "9999999999")]
pub phone: Option<Secret<String>>,
@@ -59,7 +59,7 @@ pub struct CustomerResponse {
pub name: Option<String>,
/// The customer's email address
#[schema(value_type = Option<String>,max_length = 255, example = "[email protected]")]
- pub email: Option<Secret<String, pii::Email>>,
+ pub email: Option<pii::Email>,
/// The customer's phone number
#[schema(value_type = Option<String>,max_length = 255, example = "9999999999")]
pub phone: Option<Secret<String>>,
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index de0cd91e527..3740c996ed3 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -1,6 +1,6 @@
use std::num::NonZeroI64;
-use common_utils::pii;
+use common_utils::{pii, pii::Email};
use masking::{PeekInterface, Secret};
use router_derive::Setter;
use time::PrimitiveDateTime;
@@ -102,7 +102,7 @@ pub struct PaymentsRequest {
/// description: The customer's email address
#[schema(max_length = 255, value_type = Option<String>, example = "[email protected]")]
- pub email: Option<Secret<String, pii::Email>>,
+ pub email: Option<Email>,
/// description: The customer's name
#[schema(value_type = Option<String>, max_length = 255, example = "John Test")]
@@ -258,7 +258,7 @@ pub struct VerifyRequest {
// and is later passed in the struct
pub merchant_id: Option<String>,
pub customer_id: Option<String>,
- pub email: Option<Secret<String, pii::Email>>,
+ pub email: Option<Email>,
pub name: Option<Secret<String>>,
pub phone: Option<Secret<String>>,
pub phone_country_code: Option<String>,
@@ -443,7 +443,7 @@ pub enum PayLaterData {
KlarnaRedirect {
/// The billing email
#[schema(value_type = String)]
- billing_email: Secret<String, pii::Email>,
+ billing_email: Email,
// The billing country code
#[schema(value_type = CountryAlpha2, example = "US")]
billing_country: api_enums::CountryAlpha2,
@@ -459,7 +459,7 @@ pub enum PayLaterData {
AfterpayClearpayRedirect {
/// The billing email
#[schema(value_type = String)]
- billing_email: Secret<String, pii::Email>,
+ billing_email: Email,
/// The billing name
#[schema(value_type = String)]
billing_name: Secret<String>,
@@ -617,7 +617,7 @@ pub enum BankRedirectData {
},
OnlineBankingFinland {
// Shopper Email
- email: Option<Secret<String, pii::Email>>,
+ email: Option<Email>,
},
OnlineBankingPoland {
// Issuer banks
@@ -669,7 +669,7 @@ pub struct BankDebitBilling {
pub name: Secret<String>,
/// The billing email for bank debits
#[schema(value_type = String, example = "[email protected]")]
- pub email: Secret<String, pii::Email>,
+ pub email: Email,
/// The billing address for bank debits
pub address: Option<AddressDetails>,
}
@@ -1072,7 +1072,7 @@ pub struct PaymentsResponse {
/// description: The customer's email address
#[schema(max_length = 255, value_type = Option<String>, example = "[email protected]")]
- pub email: Option<Secret<String, pii::Email>>,
+ pub email: Option<Email>,
/// description: The customer's name
#[schema(value_type = Option<String>, max_length = 255, example = "John Test")]
@@ -1212,7 +1212,7 @@ pub struct VerifyResponse {
// pub status: enums::VerifyStatus,
pub client_secret: Option<Secret<String>>,
pub customer_id: Option<String>,
- pub email: Option<Secret<String, pii::Email>>,
+ pub email: Option<Email>,
pub name: Option<Secret<String>>,
pub phone: Option<Secret<String>>,
pub mandate_id: Option<String>,
diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml
index a8f24cb6603..ae31147d5b7 100644
--- a/crates/common_utils/Cargo.toml
+++ b/crates/common_utils/Cargo.toml
@@ -8,20 +8,9 @@ readme = "README.md"
license = "Apache-2.0"
[features]
-signals = [
- "dep:signal-hook-tokio",
- "dep:signal-hook",
- "dep:tokio",
- "dep:router_env",
- "dep:futures"
-]
-async_ext = [
- "dep:futures",
- "dep:async-trait"
-]
-logs = [
- "dep:router_env"
-]
+signals = ["dep:signal-hook-tokio", "dep:signal-hook", "dep:tokio", "dep:router_env", "dep:futures"]
+async_ext = ["dep:futures", "dep:async-trait"]
+logs = ["dep:router_env"]
[dependencies]
async-trait = { version = "0.1.68", optional = true }
@@ -46,6 +35,7 @@ md5 = "0.7.0"
# First party crates
masking = { version = "0.1.0", path = "../masking" }
router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"], optional = true }
+diesel = "2.0.3"
[target.'cfg(not(target_os = "windows"))'.dependencies]
signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"], optional = true }
diff --git a/crates/common_utils/src/pii.rs b/crates/common_utils/src/pii.rs
index 14f8a260b48..f56df89b25e 100644
--- a/crates/common_utils/src/pii.rs
+++ b/crates/common_utils/src/pii.rs
@@ -1,13 +1,25 @@
//! Personal Identifiable Information protection.
-use std::{convert::AsRef, fmt};
+use std::{convert::AsRef, fmt, str::FromStr};
-use masking::{Strategy, WithType};
+use diesel::{
+ backend,
+ backend::Backend,
+ deserialize,
+ deserialize::FromSql,
+ prelude::*,
+ serialize::{Output, ToSql},
+ sql_types, AsExpression,
+};
+use masking::{Secret, Strategy, WithType};
-use crate::validation::validate_email;
+use crate::{errors::ValidationError, validation::validate_email};
+
+/// A string constant representing a redacted or masked value.
+pub const REDACTED: &str = "Redacted";
/// Type alias for serde_json value which has Secret Information
-pub type SecretSerdeValue = masking::Secret<serde_json::Value>;
+pub type SecretSerdeValue = Secret<serde_json::Value>;
/// Card number
#[derive(Debug)]
@@ -87,26 +99,73 @@ where
}
}
-/// Email address
+/// Strategy for masking Email
#[derive(Debug)]
-pub struct Email;
+pub struct EmailStrategy;
-impl<T> Strategy<T> for Email
+impl<T> Strategy<T> for EmailStrategy
where
- T: AsRef<str>,
+ T: AsRef<str> + std::fmt::Debug,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
- let is_valid = validate_email(val_str);
-
- if is_valid.is_err() {
- return WithType::fmt(val, f);
+ match val_str.split_once('@') {
+ Some((a, b)) => write!(f, "{}@{}", "*".repeat(a.len()), b),
+ None => WithType::fmt(val, f),
}
+ }
+}
+/// Email address
+#[derive(
+ serde::Serialize,
+ serde::Deserialize,
+ Debug,
+ Clone,
+ PartialEq,
+ Eq,
+ Default,
+ Queryable,
+ AsExpression,
+)]
+#[diesel(sql_type = diesel::sql_types::Text)]
+pub struct Email(Secret<String, EmailStrategy>);
+
+impl<DB> FromSql<sql_types::Text, DB> for Email
+where
+ DB: Backend,
+ String: FromSql<sql_types::Text, DB>,
+{
+ fn from_sql(bytes: backend::RawValue<'_, DB>) -> deserialize::Result<Self> {
+ let val = String::from_sql(bytes)?;
+ Ok(Self::from_str(val.as_str())?)
+ }
+}
+
+impl<DB> ToSql<sql_types::Text, DB> for Email
+where
+ DB: Backend,
+ String: ToSql<sql_types::Text, DB>,
+{
+ fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
+ self.0.to_sql(out)
+ }
+}
- if let Some((a, b)) = val_str.split_once('@') {
- write!(f, "{}@{}", "*".repeat(a.len()), b)
- } else {
- WithType::fmt(val, f)
+impl FromStr for Email {
+ type Err = ValidationError;
+
+ fn from_str(email: &str) -> Result<Self, Self::Err> {
+ if email.eq(REDACTED) {
+ return Ok(Self(Secret::new(email.to_string())));
+ }
+ match validate_email(email) {
+ Ok(_) => {
+ let secret = Secret::<String, EmailStrategy>::new(email.to_string());
+ Ok(Self(secret))
+ }
+ Err(_) => Err(ValidationError::InvalidValue {
+ message: "Invalid email address format".into(),
+ }),
}
}
}
@@ -139,9 +198,12 @@ where
#[cfg(test)]
mod pii_masking_strategy_tests {
- use masking::Secret;
+ use std::str::FromStr;
+
+ use masking::{ExposeInterface, Secret};
use super::{CardNumber, ClientSecret, Email, IpAddress};
+ use crate::pii::{EmailStrategy, REDACTED};
#[test]
fn test_valid_card_number_masking() {
@@ -152,7 +214,7 @@ mod pii_masking_strategy_tests {
#[test]
fn test_invalid_card_number_masking() {
let secret: Secret<String, CardNumber> = Secret::new("1234567890".to_string());
- assert_eq!("*** alloc::string::String ***", format!("{secret:?}",));
+ assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
/*
@@ -174,19 +236,46 @@ mod pii_masking_strategy_tests {
#[test]
fn test_valid_email_masking() {
- let secret: Secret<String, Email> = Secret::new("[email protected]".to_string());
- assert_eq!("*******@gmail.com", format!("{secret:?}"));
+ let secret: Secret<String, EmailStrategy> = Secret::new("[email protected]".to_string());
+ assert_eq!("*******@test.com", format!("{secret:?}"));
+
+ let secret: Secret<String, EmailStrategy> = Secret::new("[email protected]".to_string());
+ assert_eq!("********@gmail.com", format!("{secret:?}"));
}
#[test]
fn test_invalid_email_masking() {
- let secret: Secret<String, Email> = Secret::new("myemailgmail.com".to_string());
+ let secret: Secret<String, EmailStrategy> = Secret::new("myemailgmail.com".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
- let secret: Secret<String, Email> = Secret::new("myemail@gmail@com".to_string());
+ let secret: Secret<String, EmailStrategy> = Secret::new("myemail$gmail.com".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
+ #[test]
+ fn test_valid_newtype_email() {
+ let email_check: Result<Email, crate::errors::ValidationError> =
+ Email::from_str("[email protected]");
+ assert!(email_check.is_ok());
+ }
+
+ #[test]
+ fn test_invalid_newtype_email() {
+ let email_check: Result<Email, crate::errors::ValidationError> =
+ Email::from_str("example@abc@com");
+ assert!(email_check.is_err());
+ }
+
+ #[test]
+ fn test_redacted_email() {
+ let email_result = Email::from_str(REDACTED);
+ assert!(email_result.is_ok());
+ if let Ok(email) = email_result {
+ let secret_value = email.0.expose();
+ assert_eq!(secret_value.as_str(), REDACTED);
+ }
+ }
+
#[test]
fn test_valid_ip_addr_masking() {
let secret: Secret<String, IpAddress> = Secret::new("123.23.1.78".to_string());
diff --git a/crates/router/src/compatibility/stripe/customers/types.rs b/crates/router/src/compatibility/stripe/customers/types.rs
index b2ffb923c00..5d969d88cc7 100644
--- a/crates/router/src/compatibility/stripe/customers/types.rs
+++ b/crates/router/src/compatibility/stripe/customers/types.rs
@@ -1,14 +1,14 @@
use std::{convert::From, default::Default};
use api_models::payment_methods as api_types;
-use common_utils::{date_time, pii};
+use common_utils::{date_time, pii, pii::Email};
use serde::{Deserialize, Serialize};
use crate::{logger, types::api};
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct CreateCustomerRequest {
- pub email: Option<masking::Secret<String, pii::Email>>,
+ pub email: Option<Email>,
pub invoice_prefix: Option<String>,
pub name: Option<String>,
pub phone: Option<masking::Secret<String>>,
@@ -20,7 +20,7 @@ pub struct CreateCustomerRequest {
#[derive(Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
pub struct CustomerUpdateRequest {
pub description: Option<String>,
- pub email: Option<masking::Secret<String, pii::Email>>,
+ pub email: Option<Email>,
pub phone: Option<masking::Secret<String, masking::WithType>>,
pub name: Option<String>,
pub address: Option<masking::Secret<serde_json::Value>>,
@@ -33,7 +33,7 @@ pub struct CreateCustomerResponse {
pub object: String,
pub created: u64,
pub description: Option<String>,
- pub email: Option<masking::Secret<String, pii::Email>>,
+ pub email: Option<Email>,
pub metadata: Option<pii::SecretSerdeValue>,
pub name: Option<String>,
pub phone: Option<masking::Secret<String, masking::WithType>>,
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index 648170e5cf9..0046ae3eb17 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -7,7 +7,7 @@ use crate::{
compatibility::stripe::refunds::types as stripe_refunds,
consts,
core::errors,
- pii::{self, PeekInterface},
+ pii::{self, Email, PeekInterface},
types::{
api::{admin, enums as api_enums},
transformers::{ForeignFrom, ForeignInto},
@@ -17,7 +17,7 @@ use crate::{
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub struct StripeBillingDetails {
pub address: Option<payments::AddressDetails>,
- pub email: Option<pii::Secret<String, pii::Email>>,
+ pub email: Option<Email>,
pub name: Option<String>,
pub phone: Option<pii::Secret<String>>,
}
@@ -133,7 +133,7 @@ pub struct StripePaymentIntentRequest {
pub customer: Option<String>,
pub description: Option<String>,
pub payment_method_data: Option<StripePaymentMethodData>,
- pub receipt_email: Option<pii::Secret<String, pii::Email>>,
+ pub receipt_email: Option<Email>,
pub return_url: Option<url::Url>,
pub setup_future_usage: Option<api_enums::FutureUsage>,
pub shipping: Option<Shipping>,
@@ -299,7 +299,7 @@ pub struct StripePaymentIntentResponse {
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub capture_on: Option<time::PrimitiveDateTime>,
pub payment_token: Option<String>,
- pub email: Option<masking::Secret<String, common_utils::pii::Email>>,
+ pub email: Option<Email>,
pub phone: Option<masking::Secret<String>>,
pub statement_descriptor_suffix: Option<String>,
pub statement_descriptor_name: Option<String>,
diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs
index 87f77220426..0279e36ac89 100644
--- a/crates/router/src/compatibility/stripe/setup_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs
@@ -12,7 +12,7 @@ use crate::{
#[derive(Default, Serialize, PartialEq, Eq, Deserialize, Clone)]
pub struct StripeBillingDetails {
pub address: Option<payments::AddressDetails>,
- pub email: Option<pii::Secret<String, pii::Email>>,
+ pub email: Option<pii::Email>,
pub name: Option<String>,
pub phone: Option<pii::Secret<String>>,
}
@@ -114,7 +114,7 @@ pub struct StripeSetupIntentRequest {
pub customer: Option<String>,
pub description: Option<String>,
pub payment_method_data: Option<StripePaymentMethodData>,
- pub receipt_email: Option<pii::Secret<String, pii::Email>>,
+ pub receipt_email: Option<pii::Email>,
pub return_url: Option<url::Url>,
pub setup_future_usage: Option<api_enums::FutureUsage>,
pub shipping: Option<Shipping>,
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index ed8f5fadf8d..93993c95877 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -105,7 +105,7 @@ pub struct AdyenPaymentRequest<'a> {
store_payment_method: Option<bool>,
shopper_name: Option<ShopperName>,
shopper_locale: Option<String>,
- shopper_email: Option<Secret<String, Email>>,
+ shopper_email: Option<Email>,
telephone_number: Option<Secret<String>>,
billing_address: Option<Address>,
delivery_address: Option<Address>,
diff --git a/crates/router/src/connector/cybersource/transformers.rs b/crates/router/src/connector/cybersource/transformers.rs
index 85377cc3fbf..a72d00ab41d 100644
--- a/crates/router/src/connector/cybersource/transformers.rs
+++ b/crates/router/src/connector/cybersource/transformers.rs
@@ -81,14 +81,14 @@ pub struct BillTo {
administrative_area: Secret<String>,
postal_code: Secret<String>,
country: api_enums::CountryAlpha2,
- email: Secret<String, pii::Email>,
+ email: pii::Email,
phone_number: Secret<String>,
}
// for cybersource each item in Billing is mandatory
fn build_bill_to(
address_details: &payments::Address,
- email: Secret<String, pii::Email>,
+ email: pii::Email,
phone_number: Secret<String>,
) -> Result<BillTo, error_stack::Report<errors::ConnectorError>> {
let address = address_details
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs
index c54fa3b31cf..f33b0b43c29 100644
--- a/crates/router/src/connector/dlocal/transformers.rs
+++ b/crates/router/src/connector/dlocal/transformers.rs
@@ -15,7 +15,7 @@ use crate::{
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct Payer {
pub name: Option<Secret<String>>,
- pub email: Option<Secret<String, Email>>,
+ pub email: Option<Email>,
pub document: Secret<String>,
}
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index afc05858c63..46fee5118b1 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -105,7 +105,7 @@ pub struct Customer {
pub state: Option<String>,
pub country: Option<String>,
pub phone: Option<String>,
- pub email: Option<Secret<String, Email>>,
+ pub email: Option<Email>,
pub user_agent: Option<String>,
pub referrer: Option<String>,
pub reference: Option<String>,
@@ -121,7 +121,7 @@ pub struct GatewayInfo {
pub flexible_3d: Option<bool>,
pub moto: Option<bool>,
pub term_url: Option<String>,
- pub email: Option<Secret<String, Email>>,
+ pub email: Option<Email>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index 15e15d5035e..4a981b272d5 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -66,7 +66,7 @@ pub struct NuveiPaymentsRequest {
pub amount: String,
pub currency: storage_models::enums::Currency,
/// This ID uniquely identifies your consumer/user in your system.
- pub user_token_id: Option<Secret<String, Email>>,
+ pub user_token_id: Option<Email>,
pub client_unique_id: String,
pub transaction_type: TransactionType,
pub is_rebilling: Option<String>,
@@ -183,7 +183,7 @@ pub enum AlternativePaymentMethodType {
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BillingAddress {
- pub email: Option<Secret<String, Email>>,
+ pub email: Email,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub country: api_models::enums::CountryAlpha2,
@@ -497,7 +497,7 @@ impl<F>
let (billing_address, bank_id) = match (&payment_method, redirect) {
(AlternativePaymentMethodType::Expresscheckout, _) => (
Some(BillingAddress {
- email: Some(item.request.get_email()?),
+ email: item.request.get_email()?,
country: item.get_billing_country()?,
..Default::default()
}),
@@ -505,7 +505,7 @@ impl<F>
),
(AlternativePaymentMethodType::Giropay, _) => (
Some(BillingAddress {
- email: Some(item.request.get_email()?),
+ email: item.request.get_email()?,
country: item.get_billing_country()?,
..Default::default()
}),
@@ -517,7 +517,7 @@ impl<F>
Some(BillingAddress {
first_name: Some(address.get_first_name()?.clone()),
last_name: Some(address.get_last_name()?.clone()),
- email: Some(item.request.get_email()?),
+ email: item.request.get_email()?,
country: item.get_billing_country()?,
}),
None,
@@ -532,7 +532,7 @@ impl<F>
Some(BillingAddress {
first_name: Some(address.get_first_name()?.clone()),
last_name: Some(address.get_last_name()?.clone()),
- email: Some(item.request.get_email()?),
+ email: item.request.get_email()?,
country: item.get_billing_country()?,
}),
Some(NuveiBIC::try_from(bank_name)?),
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index 4baf9882d1d..6931a91d1ea 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -76,7 +76,7 @@ pub struct PaymentMethod {
#[derive(Debug, Serialize)]
pub struct Billing {
name: Option<Secret<String>>,
- email: Option<Secret<String, pii::Email>>,
+ email: Option<pii::Email>,
address: Option<Address>,
}
diff --git a/crates/router/src/connector/stripe/transformers.rs b/crates/router/src/connector/stripe/transformers.rs
index d0bfd1d4a45..3ba9ae11ef1 100644
--- a/crates/router/src/connector/stripe/transformers.rs
+++ b/crates/router/src/connector/stripe/transformers.rs
@@ -1,6 +1,6 @@
use api_models::{self, enums as api_enums, payments};
use base64::Engine;
-use common_utils::{errors::CustomResult, pii};
+use common_utils::{errors::CustomResult, pii, pii::Email};
use error_stack::{IntoReport, ResultExt};
use masking::{ExposeInterface, ExposeOptionInterface, Secret};
use serde::{Deserialize, Serialize};
@@ -168,7 +168,7 @@ pub struct StripeTokenResponse {
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct CustomerRequest {
pub description: Option<String>,
- pub email: Option<Secret<String, pii::Email>>,
+ pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub name: Option<String>,
}
@@ -177,7 +177,7 @@ pub struct CustomerRequest {
pub struct StripeCustomerResponse {
pub id: String,
pub description: Option<String>,
- pub email: Option<Secret<String, pii::Email>>,
+ pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub name: Option<String>,
}
@@ -1512,7 +1512,7 @@ pub struct StripeShippingAddress {
#[derive(Debug, Default, Eq, PartialEq, Serialize)]
pub struct StripeBillingAddress {
#[serde(rename = "payment_method_data[billing_details][email]")]
- pub email: Option<Secret<String, pii::Email>>,
+ pub email: Option<Email>,
#[serde(rename = "payment_method_data[billing_details][address][country]")]
pub country: Option<api_enums::CountryAlpha2>,
#[serde(rename = "payment_method_data[billing_details][name]")]
diff --git a/crates/router/src/connector/trustpay/transformers.rs b/crates/router/src/connector/trustpay/transformers.rs
index c3cbbc1090d..1a11e39d79e 100644
--- a/crates/router/src/connector/trustpay/transformers.rs
+++ b/crates/router/src/connector/trustpay/transformers.rs
@@ -130,7 +130,7 @@ pub struct PaymentRequestCards {
#[serde(rename = "billing[postcode]")]
pub billing_postcode: Secret<String>,
#[serde(rename = "customer[email]")]
- pub customer_email: Option<Secret<String, Email>>,
+ pub customer_email: Option<Email>,
#[serde(rename = "customer[ipAddress]")]
pub customer_ip_address: Option<std::net::IpAddr>,
#[serde(rename = "browser[acceptHeader]")]
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index d9ced8e1e07..ec1d76ffd67 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -155,7 +155,7 @@ impl<Flow, Request, Response> RouterData for types::RouterData<Flow, Request, Re
pub trait PaymentsAuthorizeRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
- fn get_email(&self) -> Result<Secret<String, Email>, Error>;
+ fn get_email(&self) -> Result<Email, Error>;
fn get_browser_info(&self) -> Result<types::BrowserInformation, Error>;
fn get_order_details(&self) -> Result<OrderDetails, Error>;
fn get_card(&self) -> Result<api::Card, Error>;
@@ -174,7 +174,7 @@ impl PaymentsAuthorizeRequestData for types::PaymentsAuthorizeData {
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
- fn get_email(&self) -> Result<Secret<String, Email>, Error> {
+ fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_browser_info(&self) -> Result<types::BrowserInformation, Error> {
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index c0676e4d55b..f6aab824a7e 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -60,7 +60,7 @@ pub struct BillingAddress {
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ContactDetails {
- pub email_address: Option<Secret<String, Email>>,
+ pub email_address: Option<Email>,
pub mobile_phone_number: Option<Secret<String>>,
}
@@ -202,7 +202,7 @@ fn get_address(
fn build_customer_info(
payment_address: &types::PaymentAddress,
- email: &Option<Secret<String, Email>>,
+ email: &Option<Email>,
) -> Result<Customer, error_stack::Report<errors::ConnectorError>> {
let (billing, address) =
get_address(payment_address).ok_or(errors::ConnectorError::MissingRequiredField {
diff --git a/crates/router/src/connector/zen/transformers.rs b/crates/router/src/connector/zen/transformers.rs
index c273743b24d..c8de11c556a 100644
--- a/crates/router/src/connector/zen/transformers.rs
+++ b/crates/router/src/connector/zen/transformers.rs
@@ -1,5 +1,6 @@
use std::net::IpAddr;
+use common_utils::pii::Email;
use masking::Secret;
use serde::{Deserialize, Serialize};
@@ -56,7 +57,7 @@ pub enum ZenPaymentChannels {
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ZenCustomerDetails {
- email: Secret<String, pii::Email>,
+ email: Email,
ip: IpAddr,
}
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 345245ab84f..09fd6af83fa 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -1,4 +1,6 @@
-use common_utils::ext_traits::ValueExt;
+use std::str::FromStr;
+
+use common_utils::{ext_traits::ValueExt, pii::Email};
use error_stack::ResultExt;
use router_env::{instrument, tracing};
use storage_models::errors as storage_errors;
@@ -13,7 +15,7 @@ use crate::{
routes::{metrics, AppState},
services,
types::{
- api::customers::{self, CustomerRequestExt},
+ api::customers,
storage::{self, enums},
},
};
@@ -24,9 +26,8 @@ pub const REDACTED: &str = "Redacted";
pub async fn create_customer(
db: &dyn StorageInterface,
merchant_account: storage::MerchantAccount,
- customer_data: customers::CustomerRequest,
+ mut customer_data: customers::CustomerRequest,
) -> RouterResponse<customers::CustomerResponse> {
- let mut customer_data = customer_data.validate()?;
let customer_id = &customer_data.customer_id;
let merchant_id = &merchant_account.merchant_id;
customer_data.merchant_id = merchant_id.to_owned();
@@ -201,7 +202,7 @@ pub async fn delete_customer(
let updated_customer = storage::CustomerUpdate::Update {
name: Some(REDACTED.to_string()),
- email: Some(REDACTED.to_string().into()),
+ email: Email::from_str(REDACTED).ok(),
phone: Some(REDACTED.to_string().into()),
description: Some(REDACTED.to_string()),
phone_country_code: Some(REDACTED.to_string()),
@@ -232,7 +233,6 @@ pub async fn update_customer(
merchant_account: storage::MerchantAccount,
update_customer: customers::CustomerRequest,
) -> RouterResponse<customers::CustomerResponse> {
- let update_customer = update_customer.validate()?;
//Add this in update call if customer can be updated anywhere else
db.find_customer_by_customer_id_merchant_id(
&update_customer.customer_id,
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 426fae223d8..a12070f7fab 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -1,4 +1,6 @@
-use common_utils::ext_traits::StringExt;
+use std::str::FromStr;
+
+use common_utils::{ext_traits::StringExt, pii::Email};
use error_stack::ResultExt;
#[cfg(feature = "kms")]
use external_services::kms;
@@ -83,7 +85,7 @@ pub struct AddCardRequest<'a> {
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub merchant_id: &'a str,
- pub email_address: Option<Secret<String, pii::Email>>,
+ pub email_address: Option<Email>,
pub name_on_card: Option<Secret<String>>,
pub nickname: Option<String>,
}
@@ -396,9 +398,12 @@ pub fn mk_add_card_request(
card_exp_month: card.card_exp_month.clone(),
card_exp_year: card.card_exp_year.clone(),
merchant_id: locker_id,
- email_address: Some("[email protected]".to_string().into()), //
- name_on_card: Some("John Doe".to_string().into()), // [#256]
- nickname: Some("router".to_string()), //
+ email_address: match Email::from_str("[email protected]") {
+ Ok(email) => Some(email),
+ Err(_) => None,
+ }, //
+ name_on_card: Some("John Doe".to_string().into()), // [#256]
+ nickname: Some("router".to_string()), //
};
let body = utils::Encode::<AddCardRequest<'_>>::url_encode(&add_card_req)
.change_context(errors::VaultError::RequestEncodingFailed)?;
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index a22f91ba215..db71a3cca16 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -7,8 +7,10 @@ pub mod transformers;
use std::{fmt::Debug, marker::PhantomData, time::Instant};
use api_models::payments::Metadata;
+use common_utils::pii::Email;
use error_stack::{IntoReport, ResultExt};
use futures::future::join_all;
+use masking::Secret;
use router_env::{instrument, tracing};
use time;
@@ -28,7 +30,7 @@ use crate::{
payment_methods::vault,
},
db::StorageInterface,
- logger, pii,
+ logger,
routes::AppState,
scheduler::utils as pt_utils,
services::{self, api::Authenticate},
@@ -821,8 +823,8 @@ where
pub payment_method_data: Option<api::PaymentMethodData>,
pub refunds: Vec<storage::Refund>,
pub sessions_token: Vec<api::SessionToken>,
- pub card_cvc: Option<pii::Secret<String>>,
- pub email: Option<masking::Secret<String, pii::Email>>,
+ pub card_cvc: Option<Secret<String>>,
+ pub email: Option<Email>,
pub creds_identifier: Option<String>,
pub pm_token: Option<String>,
pub connector_customer_id: Option<String>,
@@ -831,9 +833,9 @@ where
#[derive(Debug, Default)]
pub struct CustomerDetails {
pub customer_id: Option<String>,
- pub name: Option<masking::Secret<String, masking::WithType>>,
- pub email: Option<masking::Secret<String, pii::Email>>,
- pub phone: Option<masking::Secret<String, masking::WithType>>,
+ pub name: Option<Secret<String, masking::WithType>>,
+ pub email: Option<Email>,
+ pub phone: Option<Secret<String, masking::WithType>>,
pub phone_country_code: Option<String>,
}
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 0c4c243a351..37efb5d0570 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -14,8 +14,7 @@ use crate::{
payments::{self, helpers, operations, PaymentData},
},
db::StorageInterface,
- logger, pii,
- pii::Secret,
+ logger,
routes::AppState,
types::{
api::{self, PaymentIdTypeExt},
@@ -153,7 +152,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
payment_attempt,
currency,
amount,
- email: None::<Secret<String, pii::Email>>,
+ email: None,
mandate_id: None,
token: None,
setup_mandate: None,
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index c5892806876..5a4fd81bb2b 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -12,8 +12,6 @@ use crate::{
payments::{helpers, operations, CustomerDetails, PaymentAddress, PaymentData},
},
db::StorageInterface,
- pii,
- pii::Secret,
routes::AppState,
types::{
api::{self, PaymentIdTypeExt},
@@ -124,7 +122,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f
payment_intent,
currency,
amount,
- email: None::<Secret<String, pii::Email>>,
+ email: None,
mandate_id: None,
connector_response,
setup_mandate: None,
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 8bcbf2d580b..aecbbfe6bd6 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -190,7 +190,7 @@ pub struct RouterData<Flow, Request, Response> {
pub struct PaymentsAuthorizeData {
pub payment_method_data: payments::PaymentMethodData,
pub amount: i64,
- pub email: Option<masking::Secret<String, Email>>,
+ pub email: Option<Email>,
pub currency: storage_enums::Currency,
pub confirm: bool,
pub statement_descriptor_suffix: Option<String>,
@@ -233,7 +233,7 @@ pub struct AuthorizeSessionTokenData {
#[derive(Debug, Clone)]
pub struct ConnectorCustomerData {
pub description: Option<String>,
- pub email: Option<masking::Secret<String, Email>>,
+ pub email: Option<Email>,
pub phone: Option<masking::Secret<String>>,
pub name: Option<String>,
}
@@ -247,7 +247,7 @@ pub struct PaymentMethodTokenizationData {
pub struct CompleteAuthorizeData {
pub payment_method_data: Option<payments::PaymentMethodData>,
pub amount: i64,
- pub email: Option<masking::Secret<String, Email>>,
+ pub email: Option<Email>,
pub currency: storage_enums::Currency,
pub confirm: bool,
pub statement_descriptor_suffix: Option<String>,
diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rs
index 6cd0edd7e14..904e223c126 100644
--- a/crates/router/src/types/api/customers.rs
+++ b/crates/router/src/types/api/customers.rs
@@ -1,39 +1,14 @@
use api_models::customers;
pub use api_models::customers::{CustomerDeleteResponse, CustomerId, CustomerRequest};
-use error_stack::ResultExt;
use serde::Serialize;
-use crate::{
- core::errors::{self, RouterResult},
- newtype,
- pii::PeekInterface,
- types::storage,
- utils::{self, ValidateCall},
-};
+use crate::{newtype, types::storage};
newtype!(
pub CustomerResponse = customers::CustomerResponse,
derives = (Debug, Clone, Serialize)
);
-pub(crate) trait CustomerRequestExt: Sized {
- fn validate(self) -> RouterResult<Self>;
-}
-
-impl CustomerRequestExt for CustomerRequest {
- fn validate(self) -> RouterResult<Self> {
- self.email
- .as_ref()
- .validate_opt(|email| utils::validate_email(email.peek()))
- .change_context(errors::ApiErrorResponse::InvalidDataFormat {
- field_name: "email".to_string(),
- expected_format: "valid email address".to_string(),
- })?;
-
- Ok(self)
- }
-}
-
impl From<storage::Customer> for CustomerResponse {
fn from(cust: storage::Customer) -> Self {
customers::CustomerResponse {
diff --git a/crates/router/tests/connectors/cybersource.rs b/crates/router/tests/connectors/cybersource.rs
index 3395f6a7ead..297a27ff662 100644
--- a/crates/router/tests/connectors/cybersource.rs
+++ b/crates/router/tests/connectors/cybersource.rs
@@ -1,3 +1,6 @@
+use std::str::FromStr;
+
+use common_utils::pii::Email;
use masking::Secret;
use router::types::{
self, api,
@@ -58,7 +61,7 @@ fn get_default_payment_info() -> Option<utils::PaymentInfo> {
fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
currency: storage::enums::Currency::USD,
- email: Some(Secret::new("[email protected]".to_string())),
+ email: Some(Email::from_str("[email protected]").unwrap()),
..PaymentAuthorizeType::default().0
})
}
diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs
index 11af6514d9e..4130a73990c 100644
--- a/crates/router/tests/connectors/zen.rs
+++ b/crates/router/tests/connectors/zen.rs
@@ -1,4 +1,7 @@
+use std::str::FromStr;
+
use api_models::payments::OrderDetails;
+use common_utils::pii::Email;
use masking::Secret;
use router::types::{self, api, storage::enums};
@@ -304,7 +307,7 @@ async fn should_fail_payment_for_incorrect_card_number() {
product_name: "test".to_string(),
quantity: 1,
}),
- email: Some(Secret::new("[email protected]".to_string())),
+ email: Some(Email::from_str("[email protected]").unwrap()),
webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()),
..utils::PaymentAuthorizeType::default().0
}),
@@ -338,7 +341,7 @@ async fn should_fail_payment_for_empty_card_number() {
product_name: "test".to_string(),
quantity: 1,
}),
- email: Some(Secret::new("[email protected]".to_string())),
+ email: Some(Email::from_str("[email protected]").unwrap()),
webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()),
..utils::PaymentAuthorizeType::default().0
}),
@@ -367,7 +370,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
product_name: "test".to_string(),
quantity: 1,
}),
- email: Some(Secret::new("[email protected]".to_string())),
+ email: Some(Email::from_str("[email protected]").unwrap()),
webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()),
..utils::PaymentAuthorizeType::default().0
}),
@@ -401,7 +404,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
product_name: "test".to_string(),
quantity: 1,
}),
- email: Some(Secret::new("[email protected]".to_string())),
+ email: Some(Email::from_str("[email protected]").unwrap()),
webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()),
..utils::PaymentAuthorizeType::default().0
}),
@@ -435,7 +438,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
product_name: "test".to_string(),
quantity: 1,
}),
- email: Some(Secret::new("[email protected]".to_string())),
+ email: Some(Email::from_str("[email protected]").unwrap()),
webhook_url: Some("https://1635-116-74-253-164.ngrok-free.app".to_string()),
..utils::PaymentAuthorizeType::default().0
}),
diff --git a/crates/storage_models/src/customers.rs b/crates/storage_models/src/customers.rs
index 6f9bb379ba8..ea4154bdd60 100644
--- a/crates/storage_models/src/customers.rs
+++ b/crates/storage_models/src/customers.rs
@@ -1,4 +1,4 @@
-use common_utils::pii;
+use common_utils::{pii, pii::Email};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable};
use masking::Secret;
use time::PrimitiveDateTime;
@@ -11,7 +11,7 @@ pub struct CustomerNew {
pub customer_id: String,
pub merchant_id: String,
pub name: Option<String>,
- pub email: Option<Secret<String, pii::Email>>,
+ pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub description: Option<String>,
pub phone_country_code: Option<String>,
@@ -26,7 +26,7 @@ pub struct Customer {
pub customer_id: String,
pub merchant_id: String,
pub name: Option<String>,
- pub email: Option<Secret<String, pii::Email>>,
+ pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub phone_country_code: Option<String>,
pub description: Option<String>,
@@ -40,7 +40,7 @@ pub struct Customer {
pub enum CustomerUpdate {
Update {
name: Option<String>,
- email: Option<Secret<String, pii::Email>>,
+ email: Option<Email>,
phone: Option<Secret<String>>,
description: Option<String>,
phone_country_code: Option<String>,
@@ -56,7 +56,7 @@ pub enum CustomerUpdate {
#[diesel(table_name = customers)]
pub struct CustomerUpdateInternal {
name: Option<String>,
- email: Option<Secret<String, pii::Email>>,
+ email: Option<Email>,
phone: Option<Secret<String>>,
description: Option<String>,
phone_country_code: Option<String>,
|
refactor
|
use newtype pattern for email addresses (#819)
|
04787313941ec39b179490d0196258f09e2e51dd
|
2024-12-23 18:23:55
|
Shankar Singh C
|
feat(router): add /retrieve api for relay (#6918)
| false
|
diff --git a/crates/api_models/src/relay.rs b/crates/api_models/src/relay.rs
index e4bc607fc0d..f54e1471632 100644
--- a/crates/api_models/src/relay.rs
+++ b/crates/api_models/src/relay.rs
@@ -84,9 +84,20 @@ pub struct RelayRetrieveRequest {
#[serde(default)]
pub force_sync: bool,
/// The unique identifier for the Relay
- pub id: String,
+ pub id: common_utils::id_type::RelayId,
+}
+
+#[derive(Debug, ToSchema, Clone, Deserialize, Serialize)]
+pub struct RelayRetrieveBody {
+ /// The unique identifier for the Relay
+ #[serde(default)]
+ pub force_sync: bool,
}
impl common_utils::events::ApiEventMetric for RelayRequest {}
impl common_utils::events::ApiEventMetric for RelayResponse {}
+
+impl common_utils::events::ApiEventMetric for RelayRetrieveRequest {}
+
+impl common_utils::events::ApiEventMetric for RelayRetrieveBody {}
diff --git a/crates/diesel_models/src/query/relay.rs b/crates/diesel_models/src/query/relay.rs
index 28ede3cd61a..034446fe6b5 100644
--- a/crates/diesel_models/src/query/relay.rs
+++ b/crates/diesel_models/src/query/relay.rs
@@ -35,4 +35,15 @@ impl Relay {
result => result,
}
}
+
+ pub async fn find_by_id(
+ conn: &PgPooledConn,
+ id: &common_utils::id_type::RelayId,
+ ) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::id.eq(id.to_owned()),
+ )
+ .await
+ }
}
diff --git a/crates/diesel_models/src/relay.rs b/crates/diesel_models/src/relay.rs
index 24a6ab8b034..153e06ab17f 100644
--- a/crates/diesel_models/src/relay.rs
+++ b/crates/diesel_models/src/relay.rs
@@ -67,7 +67,7 @@ pub struct RelayNew {
}
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
-#[table_name = "relay"]
+#[diesel(table_name = relay)]
pub struct RelayUpdateInternal {
pub connector_reference_id: Option<String>,
pub status: Option<storage_enums::RelayStatus>,
diff --git a/crates/router/src/core/relay.rs b/crates/router/src/core/relay.rs
index 812709269d8..d25296635ad 100644
--- a/crates/router/src/core/relay.rs
+++ b/crates/router/src/core/relay.rs
@@ -1,5 +1,6 @@
use api_models::relay as relay_models;
-use common_utils::{self, ext_traits::OptionExt, id_type};
+use common_enums::RelayStatus;
+use common_utils::{self, id_type};
use error_stack::ResultExt;
use super::errors::{self, ConnectorErrorExt, RouterResponse, RouterResult, StorageErrorExt};
@@ -11,6 +12,7 @@ use crate::{
api::{self},
domain,
},
+ utils::OptionExt,
};
pub mod utils;
@@ -27,11 +29,7 @@ pub async fn relay(
let merchant_id = merchant_account.get_id();
let connector_id = &req.connector_id;
- let profile_id_from_auth_layer = profile_id_optional
- .get_required_value("ProfileId")
- .change_context(errors::ApiErrorResponse::MissingRequiredField {
- field_name: "profile id",
- })?;
+ let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?;
let profile = db
.find_business_profile_by_merchant_id_profile_id(
@@ -175,3 +173,158 @@ pub fn validate_relay_refund_data(
}
Ok(())
}
+
+pub async fn relay_retrieve(
+ state: SessionState,
+ merchant_account: domain::MerchantAccount,
+ profile_id_optional: Option<id_type::ProfileId>,
+ key_store: domain::MerchantKeyStore,
+ req: relay_models::RelayRetrieveRequest,
+) -> RouterResponse<relay_models::RelayResponse> {
+ let db = state.store.as_ref();
+ let key_manager_state = &(&state).into();
+ let merchant_id = merchant_account.get_id();
+ let relay_id = &req.id;
+
+ let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?;
+
+ db.find_business_profile_by_merchant_id_profile_id(
+ key_manager_state,
+ &key_store,
+ merchant_id,
+ &profile_id_from_auth_layer,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::ProfileNotFound {
+ id: profile_id_from_auth_layer.get_string_repr().to_owned(),
+ })?;
+
+ let relay_record_result = db
+ .find_relay_by_id(key_manager_state, &key_store, relay_id)
+ .await;
+
+ let relay_record = match relay_record_result {
+ Err(error) => {
+ if error.current_context().is_db_not_found() {
+ Err(error).change_context(errors::ApiErrorResponse::GenericNotFoundError {
+ message: "relay not found".to_string(),
+ })?
+ } else {
+ Err(error)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("error while fetch relay record")?
+ }
+ }
+ Ok(relay) => relay,
+ };
+
+ #[cfg(feature = "v1")]
+ let connector_account = db
+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(
+ key_manager_state,
+ merchant_id,
+ &relay_record.connector_id,
+ &key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: relay_record.connector_id.get_string_repr().to_string(),
+ })?;
+
+ #[cfg(feature = "v2")]
+ let connector_account = db
+ .find_merchant_connector_account_by_id(
+ key_manager_state,
+ &relay_record.connector_id,
+ &key_store,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
+ id: relay_record.connector_id.get_string_repr().to_string(),
+ })?;
+
+ let relay_response = match relay_record.relay_type {
+ common_enums::RelayType::Refund => {
+ if should_call_connector_for_relay_refund_status(&relay_record, req.force_sync) {
+ let relay_response = sync_relay_refund_with_gateway(
+ &state,
+ &merchant_account,
+ &relay_record,
+ connector_account,
+ )
+ .await?;
+
+ db.update_relay(key_manager_state, &key_store, relay_record, relay_response)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to update the relay record")?
+ } else {
+ relay_record
+ }
+ }
+ };
+
+ let response = relay_models::RelayResponse::from(relay_response);
+
+ Ok(hyperswitch_domain_models::api::ApplicationResponse::Json(
+ response,
+ ))
+}
+
+fn should_call_connector_for_relay_refund_status(
+ relay: &hyperswitch_domain_models::relay::Relay,
+ force_sync: bool,
+) -> bool {
+ // This allows refund sync at connector level if force_sync is enabled, or
+ // check if the refund is in terminal state
+ !matches!(relay.status, RelayStatus::Failure | RelayStatus::Success) && force_sync
+}
+
+pub async fn sync_relay_refund_with_gateway(
+ state: &SessionState,
+ merchant_account: &domain::MerchantAccount,
+ relay_record: &hyperswitch_domain_models::relay::Relay,
+ connector_account: domain::MerchantConnectorAccount,
+) -> RouterResult<hyperswitch_domain_models::relay::RelayUpdate> {
+ let connector_id = &relay_record.connector_id;
+ let merchant_id = merchant_account.get_id();
+
+ let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ &connector_account.connector_name,
+ api::GetToken::Connector,
+ Some(connector_id.clone()),
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get the connector")?;
+
+ let router_data = utils::construct_relay_refund_router_data(
+ state,
+ &connector_account.connector_name,
+ merchant_id,
+ &connector_account,
+ relay_record,
+ )
+ .await?;
+
+ let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
+ api::RSync,
+ hyperswitch_domain_models::router_request_types::RefundsData,
+ hyperswitch_domain_models::router_response_types::RefundsResponseData,
+ > = connector_data.connector.get_connector_integration();
+
+ let router_data_res = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ &router_data,
+ payments::CallConnectorAction::Trigger,
+ None,
+ )
+ .await
+ .to_refund_failed_response()?;
+
+ let relay_response =
+ hyperswitch_domain_models::relay::RelayUpdate::from(router_data_res.response);
+
+ Ok(relay_response)
+}
diff --git a/crates/router/src/db/relay.rs b/crates/router/src/db/relay.rs
index e869165aa33..46259679c55 100644
--- a/crates/router/src/db/relay.rs
+++ b/crates/router/src/db/relay.rs
@@ -28,6 +28,13 @@ pub trait RelayInterface {
current_state: hyperswitch_domain_models::relay::Relay,
relay_update: hyperswitch_domain_models::relay::RelayUpdate,
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>;
+
+ async fn find_relay_by_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ relay_id: &common_utils::id_type::RelayId,
+ ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -79,6 +86,25 @@ impl RelayInterface for Store {
.await
.change_context(errors::StorageError::DecryptionError)
}
+
+ async fn find_relay_by_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ relay_id: &common_utils::id_type::RelayId,
+ ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ diesel_models::relay::Relay::find_by_id(&conn, relay_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?
+ .convert(
+ key_manager_state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
}
#[async_trait::async_trait]
@@ -101,6 +127,15 @@ impl RelayInterface for MockDb {
) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
+
+ async fn find_relay_by_id(
+ &self,
+ _key_manager_state: &KeyManagerState,
+ _merchant_key_store: &domain::MerchantKeyStore,
+ _relay_id: &common_utils::id_type::RelayId,
+ ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
+ Err(errors::StorageError::MockDbError)?
+ }
}
#[async_trait::async_trait]
@@ -132,4 +167,15 @@ impl RelayInterface for KafkaStore {
)
.await
}
+
+ async fn find_relay_by_id(
+ &self,
+ key_manager_state: &KeyManagerState,
+ merchant_key_store: &domain::MerchantKeyStore,
+ relay_id: &common_utils::id_type::RelayId,
+ ) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {
+ self.diesel_store
+ .find_relay_by_id(key_manager_state, merchant_key_store, relay_id)
+ .await
+ }
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 00a94561bec..28a994fdf3f 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -598,6 +598,7 @@ impl Relay {
web::scope("/relay")
.app_data(web::Data::new(state))
.service(web::resource("").route(web::post().to(relay::relay)))
+ .service(web::resource("/{relay_id}").route(web::get().to(relay::relay_retrieve)))
}
}
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 198692ac2d6..1bc31451fad 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -166,7 +166,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::RefundsFilters
| Flow::RefundsAggregate
| Flow::RefundsManualUpdate => Self::Refunds,
- Flow::Relay => Self::Relay,
+ Flow::Relay | Flow::RelayRetrieve => Self::Relay,
Flow::FrmFulfillment
| Flow::IncomingWebhookReceive
diff --git a/crates/router/src/routes/relay.rs b/crates/router/src/routes/relay.rs
index 13c92eb19a6..cfc66253d50 100644
--- a/crates/router/src/routes/relay.rs
+++ b/crates/router/src/routes/relay.rs
@@ -38,3 +38,39 @@ pub async fn relay(
))
.await
}
+
+#[instrument(skip_all, fields(flow = ?Flow::RelayRetrieve))]
+#[cfg(feature = "oltp")]
+pub async fn relay_retrieve(
+ state: web::Data<app::AppState>,
+ path: web::Path<common_utils::id_type::RelayId>,
+ req: actix_web::HttpRequest,
+ query_params: web::Query<api_models::relay::RelayRetrieveBody>,
+) -> impl Responder {
+ let flow = Flow::RelayRetrieve;
+ let relay_retrieve_request = api_models::relay::RelayRetrieveRequest {
+ force_sync: query_params.force_sync,
+ id: path.into_inner(),
+ };
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ relay_retrieve_request,
+ |state, auth: auth::AuthenticationData, req, _| {
+ relay::relay_retrieve(
+ state,
+ auth.merchant_account,
+ #[cfg(feature = "v1")]
+ auth.profile_id,
+ #[cfg(feature = "v2")]
+ Some(auth.profile.get_id().clone()),
+ auth.key_store,
+ req,
+ )
+ },
+ &auth::HeaderAuth(auth::ApiKeyAuth),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index ccbf9598a56..8bcd9e44199 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -533,6 +533,8 @@ pub enum Flow {
VolumeSplitOnRoutingType,
/// Relay flow
Relay,
+ /// Relay retrieve flow
+ RelayRetrieve,
}
/// Trait for providing generic behaviour to flow metric
|
feat
|
add /retrieve api for relay (#6918)
|
728177666bbfa0c0d75267b3e3c9684ce5b8e294
|
2023-07-17 23:25:25
|
github-actions
|
chore(version): v1.6.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ad988698a82..e9a19286163 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,50 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.6.0 (2023-07-17)
+
+### Features
+
+- **compatibility:**
+ - [upi] add upi pm in compatibility layer, convert amount to base unit in iatapay ([#1711](https://github.com/juspay/hyperswitch/pull/1711)) ([`5213656`](https://github.com/juspay/hyperswitch/commit/5213656fac1cd1372374bfdcd90d41487e7aa387))
+ - Add support for stripe compatible webhooks ([#1728](https://github.com/juspay/hyperswitch/pull/1728)) ([`87ae99f`](https://github.com/juspay/hyperswitch/commit/87ae99f7f2247f92078064169f998519cdfcf27b))
+- **connector:**
+ - [Adyen] Implement Bizum in Bank Redirects ([#1589](https://github.com/juspay/hyperswitch/pull/1589)) ([`c654d76`](https://github.com/juspay/hyperswitch/commit/c654d76660fcca18f54e270920b1d6976a01972b))
+ - [Globepay] Add Refund and Refund Sync flow ([#1706](https://github.com/juspay/hyperswitch/pull/1706)) ([`c72a592`](https://github.com/juspay/hyperswitch/commit/c72a592e5e1d5c8ed16ae8fea89a7e3cfd365532))
+ - [Mollie] Implement card 3ds ([#1421](https://github.com/juspay/hyperswitch/pull/1421)) ([`91f969a`](https://github.com/juspay/hyperswitch/commit/91f969a2908f4e7b0101a212567305888f51e236))
+ - [PowerTranz] Add cards 3ds support for PowerTranz connector ([#1722](https://github.com/juspay/hyperswitch/pull/1722)) ([`95a45e4`](https://github.com/juspay/hyperswitch/commit/95a45e49786db4980fac8e347534048100e24039))
+ - [Tsys] Add cards for Payments and Refunds flow ([#1716](https://github.com/juspay/hyperswitch/pull/1716)) ([`714cd27`](https://github.com/juspay/hyperswitch/commit/714cd275b32d16e24a8c1e5f181f97537947a3b9))
+ - [Adyen] Implement Clearpay in BNPL ([#1546](https://github.com/juspay/hyperswitch/pull/1546)) ([`abed197`](https://github.com/juspay/hyperswitch/commit/abed197366035a03810b36eead590f189d83e6ac))
+ - [Adyen] implement Gopay for Adyen ([#1557](https://github.com/juspay/hyperswitch/pull/1557)) ([`de2d9bd`](https://github.com/juspay/hyperswitch/commit/de2d9bd059ed82b34a6f0656492348693b985ec4))
+- **mandates:** Recurring payment support for bank redirect and bank debit payment method for stripe ([#1119](https://github.com/juspay/hyperswitch/pull/1119)) ([`14c2d72`](https://github.com/juspay/hyperswitch/commit/14c2d72509c7fae648bbef620c2e3ef82aa9d8d6))
+- **router:**
+ - Add attempt_count field in attempt update record of payment_intent ([#1725](https://github.com/juspay/hyperswitch/pull/1725)) ([`95de3a5`](https://github.com/juspay/hyperswitch/commit/95de3a579d073060dd0e4eca382650042bfd6737))
+ - Restricted customer update in payments-confirm and payments-update call via clientAuth ([#1659](https://github.com/juspay/hyperswitch/pull/1659)) ([`94a5eb3`](https://github.com/juspay/hyperswitch/commit/94a5eb35335afb4c38f4af62aef1a195f30ec448))
+
+### Bug Fixes
+
+- **ci:** Run UI tests only for 15mins max in case of build failure ([#1718](https://github.com/juspay/hyperswitch/pull/1718)) ([`16a2c46`](https://github.com/juspay/hyperswitch/commit/16a2c46affbd4319ee1106e08922e7f3094adfbe))
+- **connector:**
+ - [Adyen] Fix Klarna mandates for Adyen ([#1717](https://github.com/juspay/hyperswitch/pull/1717)) ([`c34a049`](https://github.com/juspay/hyperswitch/commit/c34a049506e18fa5f0c458676e54e54f95a1609e))
+ - [Adyen] Add bizum in common enums ([#1719](https://github.com/juspay/hyperswitch/pull/1719)) ([`cbde4a6`](https://github.com/juspay/hyperswitch/commit/cbde4a6d7b65cfe11de51f7fd348e238f7ff9500))
+ - [Multisafepay] Fix bug in Paypal payment decline and cancel ([#1647](https://github.com/juspay/hyperswitch/pull/1647)) ([`a77ab42`](https://github.com/juspay/hyperswitch/commit/a77ab42f4fde59a48d1e044295b0955152b99b58))
+- **payments:** Populate mandate_data in the response body of the PaymentsCreate endpoint ([#1715](https://github.com/juspay/hyperswitch/pull/1715)) ([`fb149cb`](https://github.com/juspay/hyperswitch/commit/fb149cb0ff750fbaadf22d263be0f7bfe1574e37))
+- **refunds:** Modify refund fields to process updating of refund_reason ([#1544](https://github.com/juspay/hyperswitch/pull/1544)) ([`9890570`](https://github.com/juspay/hyperswitch/commit/9890570274e344c474b2b0033033ae70e0314cc8))
+- **router:** Convert ephemeral to client secret auth list payment_method_customer ([#1602](https://github.com/juspay/hyperswitch/pull/1602)) ([`5fbd1cc`](https://github.com/juspay/hyperswitch/commit/5fbd1cc3c787a64634aac640ced9e2dce59b036d))
+
+### Refactors
+
+- **pm_list:** Update required fields for a payment method ([#1720](https://github.com/juspay/hyperswitch/pull/1720)) ([`8dd9fcc`](https://github.com/juspay/hyperswitch/commit/8dd9fcc2c594f4aebd2f0418986836fce6e5c242))
+
+### Revert
+
+- Refactor(pm_list): Update required fields for a payment method ([#1724](https://github.com/juspay/hyperswitch/pull/1724)) ([`c6f7455`](https://github.com/juspay/hyperswitch/commit/c6f745540fa3096f8024ca29546a006395aa4bf2))
+
+**Full Changelog:** [`v1.5.0...v1.6.0`](https://github.com/juspay/hyperswitch/compare/v1.5.0...v1.6.0)
+
+- - -
+
+
## 1.5.0 (2023-07-14)
### Features
|
chore
|
v1.6.0
|
b2eb56e8d8589d1ae1a841a2c9e914c9d93e7993
|
2024-10-04 16:59:11
|
Mani Chandra
|
refactor(users): Deprecate unused user APIs and stabilize v1 APIs (#6114)
| false
|
diff --git a/crates/api_models/src/events/user.rs b/crates/api_models/src/events/user.rs
index 9b100a7321e..bb61a025180 100644
--- a/crates/api_models/src/events/user.rs
+++ b/crates/api_models/src/events/user.rs
@@ -12,25 +12,16 @@ use crate::user::{
},
AcceptInviteFromEmailRequest, AuthSelectRequest, AuthorizeResponse, BeginTotpResponse,
ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest,
- CreateUserAuthenticationMethodRequest, DashboardEntryResponse, ForgotPasswordRequest,
- GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse,
- GetUserRoleDetailsRequest, GetUserRoleDetailsResponse, GetUserRoleDetailsResponseV2,
- InviteUserRequest, ListUsersResponse, ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest,
- RotatePasswordRequest, SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest,
- SsoSignInRequest, SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest,
- TokenResponse, TwoFactorAuthStatusResponse, UpdateUserAccountDetailsRequest,
- UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantCreate,
- VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
+ CreateUserAuthenticationMethodRequest, ForgotPasswordRequest, GetSsoAuthUrlRequest,
+ GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest,
+ GetUserRoleDetailsResponseV2, InviteUserRequest, ReInviteUserRequest, RecoveryCodes,
+ ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignUpRequest,
+ SignUpWithMerchantIdRequest, SsoSignInRequest, SwitchMerchantRequest,
+ SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, TwoFactorAuthStatusResponse,
+ UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest,
+ UserMerchantCreate, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest,
};
-impl ApiEventMetric for DashboardEntryResponse {
- fn get_api_event_type(&self) -> Option<ApiEventsType> {
- Some(ApiEventsType::User {
- user_id: self.user_id.clone(),
- })
- }
-}
-
#[cfg(feature = "recon")]
impl ApiEventMetric for VerifyTokenResponse {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
@@ -55,7 +46,6 @@ common_utils::impl_api_event_type!(
SwitchProfileRequest,
CreateInternalUserRequest,
UserMerchantCreate,
- ListUsersResponse,
AuthorizeResponse,
ConnectAccountRequest,
ForgotPasswordRequest,
@@ -69,7 +59,6 @@ common_utils::impl_api_event_type!(
UpdateUserAccountDetailsRequest,
GetUserDetailsResponse,
GetUserRoleDetailsRequest,
- GetUserRoleDetailsResponse,
GetUserRoleDetailsResponseV2,
TokenResponse,
TwoFactorAuthStatusResponse,
diff --git a/crates/api_models/src/events/user_role.rs b/crates/api_models/src/events/user_role.rs
index eb09abd471c..a2c76ecc394 100644
--- a/crates/api_models/src/events/user_role.rs
+++ b/crates/api_models/src/events/user_role.rs
@@ -3,26 +3,21 @@ use common_utils::events::{ApiEventMetric, ApiEventsType};
use crate::user_role::{
role::{
CreateRoleRequest, GetRoleRequest, ListRolesAtEntityLevelRequest, ListRolesRequest,
- ListRolesResponse, RoleInfoResponseNew, RoleInfoWithGroupsResponse,
- RoleInfoWithPermissionsResponse, UpdateRoleRequest,
+ RoleInfoResponseNew, RoleInfoWithGroupsResponse, UpdateRoleRequest,
},
- AcceptInvitationRequest, AuthorizationInfoResponse, DeleteUserRoleRequest,
- ListUsersInEntityRequest, MerchantSelectRequest, UpdateUserRoleRequest,
+ AuthorizationInfoResponse, DeleteUserRoleRequest, ListUsersInEntityRequest,
+ UpdateUserRoleRequest,
};
common_utils::impl_api_event_type!(
Miscellaneous,
(
- RoleInfoWithPermissionsResponse,
GetRoleRequest,
AuthorizationInfoResponse,
UpdateUserRoleRequest,
- MerchantSelectRequest,
- AcceptInvitationRequest,
DeleteUserRoleRequest,
CreateRoleRequest,
UpdateRoleRequest,
- ListRolesResponse,
ListRolesAtEntityLevelRequest,
RoleInfoResponseNew,
RoleInfoWithGroupsResponse,
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 7b22387b3c3..d66f9f3bc03 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -1,6 +1,6 @@
use std::fmt::Debug;
-use common_enums::{EntityType, PermissionGroup, RoleScope, TokenPurpose};
+use common_enums::{EntityType, TokenPurpose};
use common_utils::{crypto::OptionalEncryptableName, id_type, pii};
use masking::Secret;
@@ -25,19 +25,6 @@ pub struct SignUpRequest {
pub password: Secret<String>,
}
-#[derive(serde::Serialize, Debug, Clone)]
-pub struct DashboardEntryResponse {
- pub token: Secret<String>,
- pub merchant_id: id_type::MerchantId,
- pub name: Secret<String>,
- pub email: pii::Email,
- pub verification_days_left: Option<i64>,
- pub user_role: String,
- //this field is added for audit/debug reasons
- #[serde(skip_serializing)]
- pub user_id: String,
-}
-
pub type SignInRequest = SignUpRequest;
#[derive(serde::Deserialize, Debug, Clone, serde::Serialize)]
@@ -131,20 +118,6 @@ pub struct UserMerchantCreate {
pub company_name: String,
}
-#[derive(Debug, serde::Serialize)]
-pub struct ListUsersResponse(pub Vec<UserDetails>);
-
-#[derive(Debug, serde::Serialize)]
-pub struct UserDetails {
- pub email: pii::Email,
- pub name: Secret<String>,
- pub role_id: String,
- pub role_name: String,
- pub status: UserStatus,
- #[serde(with = "common_utils::custom_serde::iso8601")]
- pub last_modified_at: time::PrimitiveDateTime,
-}
-
#[derive(serde::Serialize, Debug, Clone)]
pub struct GetUserDetailsResponse {
pub merchant_id: id_type::MerchantId,
@@ -167,19 +140,6 @@ pub struct GetUserRoleDetailsRequest {
pub email: pii::Email,
}
-#[derive(Debug, serde::Serialize)]
-pub struct GetUserRoleDetailsResponse {
- pub email: pii::Email,
- pub name: Secret<String>,
- pub role_id: String,
- pub role_name: String,
- pub status: UserStatus,
- #[serde(with = "common_utils::custom_serde::iso8601")]
- pub last_modified_at: time::PrimitiveDateTime,
- pub groups: Vec<PermissionGroup>,
- pub role_scope: RoleScope,
-}
-
#[derive(Debug, serde::Serialize)]
pub struct GetUserRoleDetailsResponseV2 {
pub role_id: String,
@@ -207,16 +167,6 @@ pub struct SendVerifyEmailRequest {
pub email: pii::Email,
}
-#[derive(Debug, serde::Serialize)]
-pub struct UserMerchantAccount {
- pub merchant_id: id_type::MerchantId,
- pub merchant_name: OptionalEncryptableName,
- pub is_active: bool,
- pub role_id: String,
- pub role_name: String,
- pub org_id: id_type::OrganizationId,
-}
-
#[cfg(feature = "recon")]
#[derive(serde::Serialize, Debug)]
pub struct VerifyTokenResponse {
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index f2743d6a311..ab32651e729 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -54,42 +54,17 @@ pub enum ParentGroup {
Recon,
}
-#[derive(Debug, serde::Serialize)]
-pub enum PermissionModule {
- Payments,
- Refunds,
- MerchantAccount,
- Connectors,
- Routing,
- Analytics,
- Mandates,
- Customer,
- Disputes,
- ThreeDsDecisionManager,
- SurchargeDecisionManager,
- AccountCreate,
- Payouts,
- Recon,
-}
-
#[derive(Debug, serde::Serialize)]
pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>);
#[derive(Debug, serde::Serialize)]
#[serde(untagged)]
pub enum AuthorizationInfo {
- Module(ModuleInfo),
Group(GroupInfo),
GroupWithTag(ParentInfo),
}
-#[derive(Debug, serde::Serialize)]
-pub struct ModuleInfo {
- pub module: PermissionModule,
- pub description: &'static str,
- pub permissions: Vec<PermissionInfo>,
-}
-
+// TODO: To be deprecated
#[derive(Debug, serde::Serialize)]
pub struct GroupInfo {
pub group: PermissionGroup,
@@ -122,16 +97,6 @@ pub enum UserStatus {
InvitationSent,
}
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct MerchantSelectRequest {
- pub merchant_ids: Vec<common_utils::id_type::MerchantId>,
-}
-
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct AcceptInvitationRequest {
- pub merchant_ids: Vec<common_utils::id_type::MerchantId>,
-}
-
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct DeleteUserRoleRequest {
pub email: pii::Email,
diff --git a/crates/api_models/src/user_role/role.rs b/crates/api_models/src/user_role/role.rs
index be467421e65..885ec455e4c 100644
--- a/crates/api_models/src/user_role/role.rs
+++ b/crates/api_models/src/user_role/role.rs
@@ -1,8 +1,6 @@
pub use common_enums::PermissionGroup;
use common_enums::{EntityType, RoleScope};
-use super::Permission;
-
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct CreateRoleRequest {
pub role_name: String,
@@ -16,17 +14,6 @@ pub struct UpdateRoleRequest {
pub role_name: Option<String>,
}
-#[derive(Debug, serde::Serialize)]
-pub struct ListRolesResponse(pub Vec<RoleInfoWithGroupsResponse>);
-
-#[derive(Debug, serde::Serialize)]
-pub struct RoleInfoWithPermissionsResponse {
- pub role_id: String,
- pub permissions: Vec<Permission>,
- pub role_name: String,
- pub role_scope: RoleScope,
-}
-
#[derive(Debug, serde::Serialize)]
pub struct RoleInfoWithGroupsResponse {
pub role_id: String,
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index f36ecc18116..9f865c1071e 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -1135,121 +1135,6 @@ pub async fn create_internal_user(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn switch_merchant_id(
- state: SessionState,
- request: user_api::SwitchMerchantRequest,
- user_from_token: auth::UserFromToken,
-) -> UserResponse<user_api::DashboardEntryResponse> {
- if user_from_token.merchant_id == request.merchant_id {
- return Err(UserErrors::InvalidRoleOperationWithMessage(
- "User switching to same merchant_id".to_string(),
- )
- .into());
- }
-
- let user = user_from_token.get_user_from_db(&state).await?;
- let key_manager_state = &(&state).into();
- let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
- &state,
- &user_from_token.role_id,
- &user_from_token.merchant_id,
- &user_from_token.org_id,
- )
- .await
- .to_not_found_response(UserErrors::InternalServerError)?;
-
- let (token, role_id) = if role_info.is_internal() {
- let key_store = state
- .store
- .get_merchant_key_store_by_merchant_id(
- key_manager_state,
- &request.merchant_id,
- &state.store.get_master_key().to_vec().into(),
- )
- .await
- .map_err(|e| {
- if e.current_context().is_db_not_found() {
- e.change_context(UserErrors::MerchantIdNotFound)
- } else {
- e.change_context(UserErrors::InternalServerError)
- }
- })?;
-
- let org_id = state
- .store
- .find_merchant_account_by_merchant_id(
- key_manager_state,
- &request.merchant_id,
- &key_store,
- )
- .await
- .map_err(|e| {
- if e.current_context().is_db_not_found() {
- e.change_context(UserErrors::MerchantIdNotFound)
- } else {
- e.change_context(UserErrors::InternalServerError)
- }
- })?
- .organization_id;
-
- let token = utils::user::generate_jwt_auth_token_with_attributes_without_profile(
- &state,
- user_from_token.user_id,
- request.merchant_id.clone(),
- org_id.clone(),
- user_from_token.role_id.clone(),
- )
- .await?;
-
- (token, user_from_token.role_id)
- } else {
- let user_roles = state
- .store
- .list_user_roles_by_user_id_and_version(&user_from_token.user_id, UserRoleVersion::V1)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let active_user_roles = user_roles
- .into_iter()
- .filter(|role| role.status == UserStatus::Active)
- .collect::<Vec<_>>();
-
- let user_role = active_user_roles
- .iter()
- .find_map(|role| {
- let Some(ref merchant_id) = role.merchant_id else {
- return Some(Err(report!(UserErrors::InternalServerError)));
- };
- if merchant_id == &request.merchant_id {
- Some(Ok(role))
- } else {
- None
- }
- })
- .transpose()?
- .ok_or(report!(UserErrors::InvalidRoleOperation))
- .attach_printable("User doesn't have access to switch")?;
-
- let token =
- utils::user::generate_jwt_auth_token_without_profile(&state, &user, user_role).await?;
- utils::user_role::set_role_permissions_in_cache_by_user_role(&state, user_role).await;
-
- (token, user_role.role_id.clone())
- };
-
- let response = user_api::DashboardEntryResponse {
- token: token.clone(),
- name: user.get_name(),
- email: user.get_email(),
- user_id: user.get_user_id().to_string(),
- verification_days_left: None,
- user_role: role_id,
- merchant_id: request.merchant_id,
- };
-
- auth::cookies::set_cookie_response(response, token)
-}
-
pub async fn create_merchant_account(
state: SessionState,
user_from_token: auth::UserFromToken,
@@ -1282,142 +1167,6 @@ pub async fn create_merchant_account(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn list_merchants_for_user(
- state: SessionState,
- user_from_token: auth::UserIdFromAuth,
-) -> UserResponse<Vec<user_api::UserMerchantAccount>> {
- let user_roles = state
- .store
- .list_user_roles_by_user_id_and_version(
- user_from_token.user_id.as_str(),
- UserRoleVersion::V1,
- )
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let merchant_accounts_map = state
- .store
- .list_multiple_merchant_accounts(
- &(&state).into(),
- user_roles
- .iter()
- .map(|role| {
- role.merchant_id
- .clone()
- .ok_or(UserErrors::InternalServerError)
- })
- .collect::<Result<Vec<_>, _>>()?,
- )
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .map(|merchant_account| (merchant_account.get_id().clone(), merchant_account))
- .collect::<HashMap<_, _>>();
-
- let roles_map = futures::future::try_join_all(user_roles.iter().map(|user_role| async {
- let Some(merchant_id) = &user_role.merchant_id else {
- return Err(report!(UserErrors::InternalServerError))
- .attach_printable("merchant_id not found for user_role");
- };
- let Some(org_id) = &user_role.org_id else {
- return Err(report!(UserErrors::InternalServerError)
- .attach_printable("org_id not found in user_role"));
- };
- roles::RoleInfo::from_role_id_in_merchant_scope(
- &state,
- &user_role.role_id,
- merchant_id,
- org_id,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("Unable to find role info for user role")
- }))
- .await?
- .into_iter()
- .map(|role_info| (role_info.get_role_id().to_owned(), role_info))
- .collect::<HashMap<_, _>>();
-
- Ok(ApplicationResponse::Json(
- user_roles
- .into_iter()
- .map(|user_role| {
- let Some(merchant_id) = &user_role.merchant_id else {
- return Err(report!(UserErrors::InternalServerError))
- .attach_printable("merchant_id not found for user_role");
- };
- let Some(org_id) = &user_role.org_id else {
- return Err(report!(UserErrors::InternalServerError)
- .attach_printable("org_id not found in user_role"));
- };
- let merchant_account = merchant_accounts_map
- .get(merchant_id)
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("Merchant account for user role doesn't exist")?;
-
- let role_info = roles_map
- .get(&user_role.role_id)
- .ok_or(UserErrors::InternalServerError)
- .attach_printable("Role info for user role doesn't exist")?;
-
- Ok(user_api::UserMerchantAccount {
- merchant_id: merchant_id.to_owned(),
- merchant_name: merchant_account.merchant_name.clone(),
- is_active: user_role.status == UserStatus::Active,
- role_id: user_role.role_id,
- role_name: role_info.get_role_name().to_string(),
- org_id: org_id.to_owned(),
- })
- })
- .collect::<Result<Vec<_>, _>>()?,
- ))
-}
-
-pub async fn get_user_details_in_merchant_account(
- state: SessionState,
- user_from_token: auth::UserFromToken,
- request: user_api::GetUserRoleDetailsRequest,
- _req_state: ReqState,
-) -> UserResponse<user_api::GetUserRoleDetailsResponse> {
- let required_user = utils::user::get_user_from_db_by_email(&state, request.email.try_into()?)
- .await
- .to_not_found_response(UserErrors::InvalidRoleOperation)?;
-
- let required_user_role = state
- .store
- .find_user_role_by_user_id_merchant_id(
- required_user.get_user_id(),
- &user_from_token.merchant_id,
- UserRoleVersion::V1,
- )
- .await
- .to_not_found_response(UserErrors::InvalidRoleOperation)
- .attach_printable("User not found in the merchant account")?;
-
- let role_info = roles::RoleInfo::from_role_id_in_merchant_scope(
- &state,
- &required_user_role.role_id,
- &user_from_token.merchant_id,
- &user_from_token.org_id,
- )
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("User role exists but the corresponding role doesn't")?;
-
- Ok(ApplicationResponse::Json(
- user_api::GetUserRoleDetailsResponse {
- email: required_user.get_email(),
- name: required_user.get_name(),
- role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
- status: required_user_role.status.foreign_into(),
- last_modified_at: required_user_role.last_modified,
- groups: role_info.get_permission_groups().to_vec(),
- role_scope: role_info.get_scope(),
- },
- ))
-}
-
pub async fn list_user_roles_details(
state: SessionState,
user_from_token: auth::UserFromToken,
@@ -1670,80 +1419,6 @@ pub async fn list_user_roles_details(
Ok(ApplicationResponse::Json(role_details_list))
}
-pub async fn list_users_for_merchant_account(
- state: SessionState,
- user_from_token: auth::UserFromToken,
-) -> UserResponse<user_api::ListUsersResponse> {
- let user_roles: HashMap<String, _> = state
- .store
- .list_user_roles_by_merchant_id(&user_from_token.merchant_id, UserRoleVersion::V1)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("No user roles for given merchant_id")?
- .into_iter()
- .map(|role| (role.user_id.clone(), role))
- .collect();
-
- let user_ids = user_roles.keys().cloned().collect::<Vec<_>>();
-
- let users = state
- .global_store
- .find_users_by_user_ids(user_ids)
- .await
- .change_context(UserErrors::InternalServerError)
- .attach_printable("No users for given merchant_id")?;
-
- let users_and_user_roles: Vec<_> = users
- .into_iter()
- .filter_map(|user| {
- user_roles
- .get(&user.user_id)
- .map(|role| (user.clone(), role.clone()))
- })
- .collect();
-
- let users_user_roles_and_roles =
- futures::future::try_join_all(users_and_user_roles.into_iter().map(
- |(user, user_role)| async {
- roles::RoleInfo::from_role_id_in_merchant_scope(
- &state,
- &user_role.role_id.clone(),
- user_role
- .merchant_id
- .as_ref()
- .ok_or(UserErrors::InternalServerError)?,
- user_role
- .org_id
- .as_ref()
- .ok_or(UserErrors::InternalServerError)?,
- )
- .await
- .map(|role_info| (user, user_role, role_info))
- .to_not_found_response(UserErrors::InternalServerError)
- },
- ))
- .await?;
-
- let user_details_vec = users_user_roles_and_roles
- .into_iter()
- .map(|(user, user_role, role_info)| {
- let user = domain::UserFromStorage::from(user);
- user_api::UserDetails {
- email: user.get_email(),
- name: user.get_name(),
- role_id: user_role.role_id.clone(),
- role_name: role_info.get_role_name().to_string(),
- status: user_role.status.foreign_into(),
- last_modified_at: user_role.last_modified,
- }
- })
- .collect();
-
- Ok(ApplicationResponse::Json(user_api::ListUsersResponse(
- user_details_vec,
- )))
-}
-
#[cfg(feature = "email")]
pub async fn verify_email_token_only_flow(
state: SessionState,
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index e10fa0eb81c..5973a20dd33 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -26,6 +26,7 @@ pub mod role;
use common_enums::{EntityType, PermissionGroup};
use strum::IntoEnumIterator;
+// TODO: To be deprecated
pub async fn get_authorization_info_with_groups(
_state: SessionState,
) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
@@ -38,6 +39,7 @@ pub async fn get_authorization_info_with_groups(
),
))
}
+
pub async fn get_authorization_info_with_group_tag(
) -> UserResponse<user_role_api::AuthorizationInfoResponse> {
static GROUPS_WITH_PARENT_TAGS: Lazy<Vec<user_role_api::ParentInfo>> = Lazy::new(|| {
@@ -253,49 +255,6 @@ pub async fn update_user_role(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn accept_invitation(
- state: SessionState,
- user_token: auth::UserFromToken,
- req: user_role_api::AcceptInvitationRequest,
-) -> UserResponse<()> {
- let merchant_accounts = state
- .store
- .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids)
- .await
- .change_context(UserErrors::InternalServerError)?;
- let update_result =
- futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async {
- let (update_v1_result, update_v2_result) =
- utils::user_role::update_v1_and_v2_user_roles_in_db(
- &state,
- user_token.user_id.as_str(),
- &merchant_account.organization_id,
- merchant_account.get_id(),
- None,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user_token.user_id.clone(),
- },
- )
- .await;
-
- if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found())
- || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found())
- {
- Err(report!(UserErrors::InternalServerError))
- } else {
- Ok(())
- }
- }))
- .await;
-
- if update_result.is_empty() || update_result.iter().all(Result::is_err) {
- return Err(UserErrors::MerchantIdNotFound.into());
- }
-
- Ok(ApplicationResponse::StatusOk)
-}
-
pub async fn accept_invitations_v2(
state: SessionState,
user_from_token: auth::UserFromToken,
@@ -348,67 +307,6 @@ pub async fn accept_invitations_v2(
Ok(ApplicationResponse::StatusOk)
}
-pub async fn merchant_select_token_only_flow(
- state: SessionState,
- user_token: auth::UserFromSinglePurposeToken,
- req: user_role_api::MerchantSelectRequest,
-) -> UserResponse<user_api::TokenResponse> {
- let merchant_accounts = state
- .store
- .list_multiple_merchant_accounts(&(&state).into(), req.merchant_ids)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let update_result =
- futures::future::join_all(merchant_accounts.iter().map(|merchant_account| async {
- let (update_v1_result, update_v2_result) =
- utils::user_role::update_v1_and_v2_user_roles_in_db(
- &state,
- user_token.user_id.as_str(),
- &merchant_account.organization_id,
- merchant_account.get_id(),
- None,
- UserRoleUpdate::UpdateStatus {
- status: UserStatus::Active,
- modified_by: user_token.user_id.clone(),
- },
- )
- .await;
-
- if update_v1_result.is_err_and(|err| !err.current_context().is_db_not_found())
- || update_v2_result.is_err_and(|err| !err.current_context().is_db_not_found())
- {
- Err(report!(UserErrors::InternalServerError))
- } else {
- Ok(())
- }
- }))
- .await;
-
- if update_result.is_empty() || update_result.iter().all(Result::is_err) {
- return Err(UserErrors::MerchantIdNotFound.into());
- }
-
- let user_from_db: domain::UserFromStorage = state
- .global_store
- .find_user_by_id(user_token.user_id.as_str())
- .await
- .change_context(UserErrors::InternalServerError)?
- .into();
-
- let current_flow =
- domain::CurrentFlow::new(user_token, domain::SPTFlow::MerchantSelect.into())?;
- let next_flow = current_flow.next(user_from_db.clone(), &state).await?;
-
- let token = next_flow.get_token(&state).await?;
-
- let response = user_api::TokenResponse {
- token: token.clone(),
- token_type: next_flow.get_flow().into(),
- };
- auth::cookies::set_cookie_response(response, token)
-}
-
pub async fn accept_invitations_pre_auth(
state: SessionState,
user_token: auth::UserFromSinglePurposeToken,
@@ -644,20 +542,23 @@ pub async fn delete_user_role(
}
// Check if user has any more role associations
- let user_roles_v2 = state
+ let remaining_roles = state
.store
- .list_user_roles_by_user_id_and_version(user_from_db.get_user_id(), UserRoleVersion::V2)
- .await
- .change_context(UserErrors::InternalServerError)?;
-
- let user_roles_v1 = state
- .store
- .list_user_roles_by_user_id_and_version(user_from_db.get_user_id(), UserRoleVersion::V1)
+ .list_user_roles_by_user_id(ListUserRolesByUserIdPayload {
+ user_id: user_from_db.get_user_id(),
+ org_id: None,
+ merchant_id: None,
+ profile_id: None,
+ entity_id: None,
+ version: None,
+ status: None,
+ limit: None,
+ })
.await
.change_context(UserErrors::InternalServerError)?;
// If user has no more role associated with him then deleting user
- if user_roles_v2.is_empty() && user_roles_v1.is_empty() {
+ if remaining_roles.is_empty() {
state
.global_store
.delete_user_by_user_id(user_from_db.get_user_id())
diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rs
index d5d655b4a89..b5b5cab421f 100644
--- a/crates/router/src/core/user_role/role.rs
+++ b/crates/router/src/core/user_role/role.rs
@@ -83,45 +83,6 @@ pub async fn create_role(
))
}
-pub async fn list_invitable_roles_with_groups(
- state: SessionState,
- user_from_token: UserFromToken,
-) -> UserResponse<role_api::ListRolesResponse> {
- let predefined_roles_map = PREDEFINED_ROLES
- .iter()
- .filter(|(_, role_info)| role_info.is_invitable())
- .map(
- |(role_id, role_info)| role_api::RoleInfoWithGroupsResponse {
- groups: role_info.get_permission_groups().to_vec(),
- role_id: role_id.to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- },
- );
-
- let custom_roles_map = state
- .store
- .list_all_roles(&user_from_token.merchant_id, &user_from_token.org_id)
- .await
- .change_context(UserErrors::InternalServerError)?
- .into_iter()
- .filter_map(|role| {
- let role_info = roles::RoleInfo::from(role);
- role_info
- .is_invitable()
- .then_some(role_api::RoleInfoWithGroupsResponse {
- groups: role_info.get_permission_groups().to_vec(),
- role_id: role_info.get_role_id().to_string(),
- role_name: role_info.get_role_name().to_string(),
- role_scope: role_info.get_scope(),
- })
- });
-
- Ok(ApplicationResponse::Json(role_api::ListRolesResponse(
- predefined_roles_map.chain(custom_roles_map).collect(),
- )))
-}
-
pub async fn get_role_with_groups(
state: SessionState,
user_from_token: UserFromToken,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index de10b70f507..f0eb5b76fb5 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -3023,37 +3023,6 @@ impl UserRoleInterface for KafkaStore {
self.diesel_store.insert_user_role(user_role).await
}
- async fn find_user_role_by_user_id(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<user_storage::UserRole, errors::StorageError> {
- self.diesel_store
- .find_user_role_by_user_id(user_id, version)
- .await
- }
-
- async fn find_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<user_storage::UserRole, errors::StorageError> {
- self.diesel_store
- .find_user_role_by_user_id_merchant_id(user_id, merchant_id, version)
- .await
- }
-
- async fn list_user_roles_by_user_id_and_version(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
- self.diesel_store
- .list_user_roles_by_user_id_and_version(user_id, version)
- .await
- }
-
async fn find_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
@@ -3113,16 +3082,6 @@ impl UserRoleInterface for KafkaStore {
.await
}
- async fn list_user_roles_by_merchant_id(
- &self,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
- self.diesel_store
- .list_user_roles_by_merchant_id(merchant_id, version)
- .await
- }
-
async fn list_user_roles_by_user_id<'a>(
&self,
payload: ListUserRolesByUserIdPayload<'a>,
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index d511010e6b5..9a5c7149b68 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -54,31 +54,6 @@ pub trait UserRoleInterface {
user_role: InsertUserRolePayload,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
- async fn find_user_role_by_user_id(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError>;
-
- async fn find_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError>;
-
- async fn list_user_roles_by_user_id_and_version(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
-
- async fn list_user_roles_by_merchant_id(
- &self,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
-
async fn find_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
@@ -132,59 +107,6 @@ impl UserRoleInterface for Store {
.map_err(|error| report!(errors::StorageError::from(error)))
}
- #[instrument(skip_all)]
- async fn find_user_role_by_user_id(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::UserRole::find_by_user_id(&conn, user_id.to_owned(), version)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
- #[instrument(skip_all)]
- async fn find_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::UserRole::find_by_user_id_merchant_id(
- &conn,
- user_id.to_owned(),
- merchant_id.to_owned(),
- version,
- )
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
- async fn list_user_roles_by_user_id_and_version(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::UserRole::list_by_user_id(&conn, user_id.to_owned(), version)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
- #[instrument(skip_all)]
- async fn list_user_roles_by_merchant_id(
- &self,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
- let conn = connection::pg_connection_write(self).await?;
- storage::UserRole::list_by_merchant_id(&conn, merchant_id.to_owned(), version)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))
- }
-
#[instrument(skip_all)]
async fn find_user_role_by_user_id_and_lineage(
&self,
@@ -335,96 +257,6 @@ impl UserRoleInterface for MockDb {
.collect::<Result<Vec<_>, _>>()
}
- async fn find_user_role_by_user_id(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- let user_roles = self.user_roles.lock().await;
- user_roles
- .iter()
- .find(|user_role| user_role.user_id == user_id && user_role.version == version)
- .cloned()
- .ok_or(
- errors::StorageError::ValueNotFound(format!(
- "No user role available for user_id = {user_id}"
- ))
- .into(),
- )
- }
-
- async fn find_user_role_by_user_id_merchant_id(
- &self,
- user_id: &str,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<storage::UserRole, errors::StorageError> {
- let user_roles = self.user_roles.lock().await;
-
- for user_role in user_roles.iter() {
- let Some(user_role_merchant_id) = &user_role.merchant_id else {
- continue;
- };
- if user_role.user_id == user_id
- && user_role_merchant_id == merchant_id
- && user_role.version == version
- {
- return Ok(user_role.clone());
- }
- }
-
- Err(errors::StorageError::ValueNotFound(format!(
- "No user role available for user_id = {} and merchant_id = {}",
- user_id,
- merchant_id.get_string_repr()
- ))
- .into())
- }
-
- async fn list_user_roles_by_user_id_and_version(
- &self,
- user_id: &str,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
- let user_roles = self.user_roles.lock().await;
-
- Ok(user_roles
- .iter()
- .cloned()
- .filter_map(|ele| {
- if ele.user_id == user_id && ele.version == version {
- return Some(ele);
- }
- None
- })
- .collect())
- }
-
- async fn list_user_roles_by_merchant_id(
- &self,
- merchant_id: &id_type::MerchantId,
- version: enums::UserRoleVersion,
- ) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
- let user_roles = self.user_roles.lock().await;
-
- let filtered_roles: Vec<_> = user_roles
- .iter()
- .filter_map(|role| {
- if let Some(role_merchant_id) = &role.merchant_id {
- if role_merchant_id == merchant_id && role.version == version {
- Some(role.clone())
- } else {
- None
- }
- } else {
- None
- }
- })
- .collect();
-
- Ok(filtered_roles)
- }
-
async fn find_user_role_by_user_id_and_lineage(
&self,
user_id: &str,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index dd3471f569b..02937065052 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1785,26 +1785,11 @@ impl User {
.service(
web::resource("/internal_signup").route(web::post().to(user::internal_user_signup)),
)
- .service(
- web::resource("/switch_merchant").route(web::post().to(user::switch_merchant_id)),
- )
.service(
web::resource("/create_merchant")
.route(web::post().to(user::user_merchant_account_create)),
)
- // TODO: Remove this endpoint once migration to /merchants/list is done
- .service(
- web::resource("/switch/list").route(web::get().to(user::list_merchants_for_user)),
- )
- .service(
- web::resource("/merchants/list")
- .route(web::get().to(user::list_merchants_for_user)),
- )
- // The route is utilized to select an invitation from a list of merchants in an intermediate state
- .service(
- web::resource("/merchants_select/list")
- .route(web::get().to(user::list_merchants_for_user)),
- )
+ // TODO: To be deprecated
.service(
web::resource("/permission_info")
.route(web::get().to(user_role::get_authorization_info)),
@@ -1946,12 +1931,13 @@ impl User {
// User management
route = route.service(
web::scope("/user")
- .service(web::resource("").route(web::get().to(user::get_user_role_details)))
+ .service(web::resource("").route(web::post().to(user::list_user_roles_details)))
+ // TODO: To be deprecated
.service(web::resource("/v2").route(web::post().to(user::list_user_roles_details)))
.service(
- web::resource("/list")
- .route(web::get().to(user::list_users_for_merchant_account)),
+ web::resource("/list").route(web::get().to(user_role::list_users_in_lineage)),
)
+ // TODO: To be deprecated
.service(
web::resource("/v2/list")
.route(web::get().to(user_role::list_users_in_lineage)),
@@ -1964,8 +1950,11 @@ impl User {
web::scope("/invite/accept")
.service(
web::resource("")
- .route(web::post().to(user_role::merchant_select))
- .route(web::put().to(user_role::accept_invitation)),
+ .route(web::post().to(user_role::accept_invitations_v2)),
+ )
+ .service(
+ web::resource("/pre_auth")
+ .route(web::post().to(user_role::accept_invitations_pre_auth)),
)
.service(
web::scope("/v2")
@@ -1990,36 +1979,38 @@ impl User {
);
// Role information
- route = route.service(
- web::scope("/role")
- .service(
- web::resource("")
- .route(web::get().to(user_role::get_role_from_token))
- .route(web::post().to(user_role::create_role)),
- )
- .service(
- web::resource("/v2/list").route(web::get().to(user_role::list_roles_with_info)),
- )
- .service(
- web::scope("/list")
- .service(web::resource("").route(web::get().to(user_role::list_all_roles)))
- .service(
- web::resource("/invite").route(
+ route =
+ route.service(
+ web::scope("/role")
+ .service(
+ web::resource("")
+ .route(web::get().to(user_role::get_role_from_token))
+ .route(web::post().to(user_role::create_role)),
+ )
+ // TODO: To be deprecated
+ .service(
+ web::resource("/v2/list")
+ .route(web::get().to(user_role::list_roles_with_info)),
+ )
+ .service(
+ web::scope("/list")
+ .service(
+ web::resource("")
+ .route(web::get().to(user_role::list_roles_with_info)),
+ )
+ .service(web::resource("/invite").route(
web::get().to(user_role::list_invitable_roles_at_entity_level),
- ),
- )
- .service(
- web::resource("/update").route(
+ ))
+ .service(web::resource("/update").route(
web::get().to(user_role::list_updatable_roles_at_entity_level),
- ),
- ),
- )
- .service(
- web::resource("/{role_id}")
- .route(web::get().to(user_role::get_role))
- .route(web::put().to(user_role::update_role)),
- ),
- );
+ )),
+ )
+ .service(
+ web::resource("/{role_id}")
+ .route(web::get().to(user_role::get_role))
+ .route(web::put().to(user_role::update_role)),
+ ),
+ );
#[cfg(feature = "dummy_connector")]
{
diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rs
index 482bc40c49f..18211b7fbb0 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -219,16 +219,13 @@ impl From<Flow> for ApiIdentifier {
| Flow::VerifyPaymentConnector
| Flow::InternalUserSignup
| Flow::SwitchOrg
- | Flow::SwitchMerchant
| Flow::SwitchMerchantV2
| Flow::SwitchProfile
| Flow::UserMerchantAccountCreate
| Flow::GenerateSampleData
| Flow::DeleteSampleData
- | Flow::UserMerchantAccountList
| Flow::GetUserDetails
| Flow::GetUserRoleDetails
- | Flow::ListUsersForMerchantAccount
| Flow::ForgotPassword
| Flow::ResetPassword
| Flow::RotatePassword
@@ -259,8 +256,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::ListInvitationsForUser
| Flow::AuthSelect => Self::User,
- Flow::ListRoles
- | Flow::ListRolesV2
+ Flow::ListRolesV2
| Flow::ListInvitableRolesAtEntityLevel
| Flow::ListUpdatableRolesAtEntityLevel
| Flow::GetRole
@@ -268,9 +264,7 @@ impl From<Flow> for ApiIdentifier {
| Flow::UpdateUserRole
| Flow::GetAuthorizationInfo
| Flow::GetRolesInfo
- | Flow::AcceptInvitation
| Flow::AcceptInvitationsV2
- | Flow::MerchantSelect
| Flow::AcceptInvitationsPreAuth
| Flow::DeleteUserRole
| Flow::CreateRole
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index fdb7d8592c5..16786e71768 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -228,24 +228,6 @@ pub async fn internal_user_signup(
.await
}
-pub async fn switch_merchant_id(
- state: web::Data<AppState>,
- http_req: HttpRequest,
- json_payload: web::Json<user_api::SwitchMerchantRequest>,
-) -> HttpResponse {
- let flow = Flow::SwitchMerchant;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &http_req,
- json_payload.into_inner(),
- |state, user, req, _| user_core::switch_merchant_id(state, req, user),
- &auth::DashboardNoPermissionAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn user_merchant_account_create(
state: web::Data<AppState>,
req: HttpRequest,
@@ -317,41 +299,6 @@ pub async fn delete_sample_data(
.await
}
-pub async fn list_merchants_for_user(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
- let flow = Flow::UserMerchantAccountList;
- Box::pin(api::server_wrap(
- flow,
- state,
- &req,
- (),
- |state, user, _, _| user_core::list_merchants_for_user(state, user),
- &auth::SinglePurposeOrLoginTokenAuth(TokenPurpose::AcceptInvite),
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
-pub async fn get_user_role_details(
- state: web::Data<AppState>,
- req: HttpRequest,
- payload: web::Query<user_api::GetUserRoleDetailsRequest>,
-) -> HttpResponse {
- let flow = Flow::GetUserDetails;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload.into_inner(),
- user_core::get_user_details_in_merchant_account,
- &auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant,
- },
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn list_user_roles_details(
state: web::Data<AppState>,
req: HttpRequest,
@@ -373,26 +320,6 @@ pub async fn list_user_roles_details(
.await
}
-pub async fn list_users_for_merchant_account(
- state: web::Data<AppState>,
- req: HttpRequest,
-) -> HttpResponse {
- let flow = Flow::ListUsersForMerchantAccount;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- (),
- |state, user, _, _| user_core::list_users_for_merchant_account(state, user),
- &auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant,
- },
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn rotate_password(
state: web::Data<AppState>,
req: HttpRequest,
diff --git a/crates/router/src/routes/user_role.rs b/crates/router/src/routes/user_role.rs
index 922e7612b14..777cbe1fd95 100644
--- a/crates/router/src/routes/user_role.rs
+++ b/crates/router/src/routes/user_role.rs
@@ -16,6 +16,7 @@ use crate::{
},
};
+// TODO: To be deprecated
pub async fn get_authorization_info(
state: web::Data<AppState>,
http_req: HttpRequest,
@@ -76,25 +77,6 @@ pub async fn create_role(
.await
}
-pub async fn list_all_roles(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
- let flow = Flow::ListRoles;
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- (),
- |state, user, _, _| async move {
- role_core::list_invitable_roles_with_groups(state, user).await
- },
- &auth::JWTAuth {
- permission: Permission::UsersRead,
- minimum_entity_level: EntityType::Merchant,
- },
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn get_role(
state: web::Data<AppState>,
req: HttpRequest,
@@ -167,25 +149,6 @@ pub async fn update_user_role(
.await
}
-pub async fn accept_invitation(
- state: web::Data<AppState>,
- req: HttpRequest,
- json_payload: web::Json<user_role_api::AcceptInvitationRequest>,
-) -> HttpResponse {
- let flow = Flow::AcceptInvitation;
- let payload = json_payload.into_inner();
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload,
- |state, user, req_body, _| user_role_core::accept_invitation(state, user, req_body),
- &auth::DashboardNoPermissionAuth,
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn accept_invitations_v2(
state: web::Data<AppState>,
req: HttpRequest,
@@ -205,27 +168,6 @@ pub async fn accept_invitations_v2(
.await
}
-pub async fn merchant_select(
- state: web::Data<AppState>,
- req: HttpRequest,
- json_payload: web::Json<user_role_api::MerchantSelectRequest>,
-) -> HttpResponse {
- let flow = Flow::MerchantSelect;
- let payload = json_payload.into_inner();
- Box::pin(api::server_wrap(
- flow,
- state.clone(),
- &req,
- payload,
- |state, user, req_body, _| async move {
- user_role_core::merchant_select_token_only_flow(state, user, req_body).await
- },
- &auth::SinglePurposeJWTAuth(TokenPurpose::AcceptInvite),
- api_locking::LockAction::NotApplicable,
- ))
- .await
-}
-
pub async fn accept_invitations_pre_auth(
state: web::Data<AppState>,
req: HttpRequest,
diff --git a/crates/router/src/services/authorization/info.rs b/crates/router/src/services/authorization/info.rs
index 822035c7925..7cfde3efeea 100644
--- a/crates/router/src/services/authorization/info.rs
+++ b/crates/router/src/services/authorization/info.rs
@@ -1,21 +1,17 @@
use api_models::user_role::{GroupInfo, ParentGroup, PermissionInfo};
use common_enums::PermissionGroup;
-use strum::{EnumIter, IntoEnumIterator};
+use strum::IntoEnumIterator;
use super::{permission_groups::get_permissions_vec, permissions::Permission};
-pub fn get_module_authorization_info() -> Vec<ModuleInfo> {
- PermissionModule::iter()
- .map(|module| ModuleInfo::new(&module))
- .collect()
-}
-
+// TODO: To be deprecated
pub fn get_group_authorization_info() -> Vec<GroupInfo> {
PermissionGroup::iter()
.map(get_group_info_from_permission_group)
.collect()
}
+// TODO: To be deprecated
pub fn get_permission_info_from_permissions(permissions: &[Permission]) -> Vec<PermissionInfo> {
permissions
.iter()
@@ -26,169 +22,7 @@ pub fn get_permission_info_from_permissions(permissions: &[Permission]) -> Vec<P
.collect()
}
-// TODO: Deprecate once groups are stable
-#[derive(PartialEq, EnumIter, Clone)]
-pub enum PermissionModule {
- Payments,
- Refunds,
- MerchantAccount,
- Connectors,
- Routing,
- Analytics,
- Mandates,
- Customer,
- Disputes,
- ThreeDsDecisionManager,
- SurchargeDecisionManager,
- AccountCreate,
- Payouts,
- Recon,
-}
-
-impl PermissionModule {
- pub fn get_module_description(&self) -> &'static str {
- match self {
- Self::Payments => "Everything related to payments - like creating and viewing payment related information are within this module",
- Self::Refunds => "Refunds module encompasses everything related to refunds - like creating and viewing payment related information",
- Self::MerchantAccount => "Accounts module permissions allow the user to view and update account details, configure webhooks and much more",
- Self::Connectors => "All connector related actions - like configuring new connectors, viewing and updating connector configuration lies with this module",
- Self::Routing => "All actions related to new, active, and past routing stacks take place here",
- Self::Analytics => "Permission to view and analyse the data relating to payments, refunds, sdk etc.",
- Self::Mandates => "Everything related to mandates - like creating and viewing mandate related information are within this module",
- Self::Customer => "Everything related to customers - like creating and viewing customer related information are within this module",
- Self::Disputes => "Everything related to disputes - like creating and viewing dispute related information are within this module",
- Self::ThreeDsDecisionManager => "View and configure 3DS decision rules configured for a merchant",
- Self::SurchargeDecisionManager =>"View and configure surcharge decision rules configured for a merchant",
- Self::AccountCreate => "Create new account within your organization",
- Self::Payouts => "Everything related to payouts - like creating and viewing payout related information are within this module",
- Self::Recon => "Everything related to recon - raise requests for activating recon and generate recon auth tokens",
- }
- }
-}
-
-// TODO: Deprecate once groups are stable
-pub struct ModuleInfo {
- pub module: PermissionModule,
- pub description: &'static str,
- pub permissions: Vec<PermissionInfo>,
-}
-
-impl ModuleInfo {
- pub fn new(module: &PermissionModule) -> Self {
- let module_name = module.clone();
- let description = module.get_module_description();
-
- match module {
- PermissionModule::Payments => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::PaymentRead,
- Permission::PaymentWrite,
- ]),
- },
- PermissionModule::Refunds => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::RefundRead,
- Permission::RefundWrite,
- ]),
- },
- PermissionModule::MerchantAccount => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::MerchantAccountRead,
- Permission::MerchantAccountWrite,
- ]),
- },
- PermissionModule::Connectors => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::MerchantConnectorAccountRead,
- Permission::MerchantConnectorAccountWrite,
- ]),
- },
- PermissionModule::Routing => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::RoutingRead,
- Permission::RoutingWrite,
- ]),
- },
- PermissionModule::Analytics => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[Permission::Analytics]),
- },
- PermissionModule::Mandates => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::MandateRead,
- Permission::MandateWrite,
- ]),
- },
- PermissionModule::Customer => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::CustomerRead,
- Permission::CustomerWrite,
- ]),
- },
- PermissionModule::Disputes => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::DisputeRead,
- Permission::DisputeWrite,
- ]),
- },
- PermissionModule::ThreeDsDecisionManager => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::ThreeDsDecisionManagerRead,
- Permission::ThreeDsDecisionManagerWrite,
- ]),
- },
-
- PermissionModule::SurchargeDecisionManager => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::SurchargeDecisionManagerRead,
- Permission::SurchargeDecisionManagerWrite,
- ]),
- },
- PermissionModule::AccountCreate => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::MerchantAccountCreate,
- ]),
- },
- PermissionModule::Payouts => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[
- Permission::PayoutRead,
- Permission::PayoutWrite,
- ]),
- },
- PermissionModule::Recon => Self {
- module: module_name,
- description,
- permissions: get_permission_info_from_permissions(&[Permission::ReconAdmin]),
- },
- }
- }
-}
-
+// TODO: To be deprecated
fn get_group_info_from_permission_group(group: PermissionGroup) -> GroupInfo {
let description = get_group_description(group);
GroupInfo {
@@ -198,6 +32,7 @@ fn get_group_info_from_permission_group(group: PermissionGroup) -> GroupInfo {
}
}
+// TODO: To be deprecated
fn get_group_description(group: PermissionGroup) -> &'static str {
match group {
PermissionGroup::OperationsView => {
@@ -250,10 +85,10 @@ pub fn get_parent_group_description(group: ParentGroup) -> &'static str {
ParentGroup::Operations => "Payments, Refunds, Payouts, Mandates, Disputes and Customers",
ParentGroup::Connectors => "Create, modify and delete connectors like Payment Processors, Payout Processors and Fraud & Risk Manager",
ParentGroup::Workflows => "Create, modify and delete Routing, 3DS Decision Manager, Surcharge Decision Manager",
- ParentGroup::Analytics => "View Analytics",
+ ParentGroup::Analytics => "View Analytics",
ParentGroup::Users => "Manage and invite Users to the Team",
- ParentGroup::Merchant => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
- ParentGroup::Organization =>"Manage organization level tasks like create new Merchant accounts, Organization level roles, etc",
- ParentGroup::Recon => "View and manage reconciliation reports",
+ ParentGroup::Merchant => "Create, modify and delete Merchant Details like api keys, webhooks, etc",
+ ParentGroup::Organization =>"Manage organization level tasks like create new Merchant accounts, Organization level roles, etc",
+ ParentGroup::Recon => "View and manage reconciliation reports",
}
}
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index 19d682aeef1..6361b82afb4 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -32,7 +32,7 @@ use crate::{
},
db::{user_role::InsertUserRolePayload, GlobalStorageInterface},
routes::SessionState,
- services::{self, authentication::UserFromToken, authorization::info},
+ services::{self, authentication::UserFromToken},
types::transformers::ForeignFrom,
utils::user::password,
};
@@ -1019,37 +1019,6 @@ impl UserFromStorage {
}
}
-impl From<info::ModuleInfo> for user_role_api::ModuleInfo {
- fn from(value: info::ModuleInfo) -> Self {
- Self {
- module: value.module.into(),
- description: value.description,
- permissions: value.permissions.into_iter().map(Into::into).collect(),
- }
- }
-}
-
-impl From<info::PermissionModule> for user_role_api::PermissionModule {
- fn from(value: info::PermissionModule) -> Self {
- match value {
- info::PermissionModule::Payments => Self::Payments,
- info::PermissionModule::Refunds => Self::Refunds,
- info::PermissionModule::MerchantAccount => Self::MerchantAccount,
- info::PermissionModule::Connectors => Self::Connectors,
- info::PermissionModule::Routing => Self::Routing,
- info::PermissionModule::Analytics => Self::Analytics,
- info::PermissionModule::Mandates => Self::Mandates,
- info::PermissionModule::Customer => Self::Customer,
- info::PermissionModule::Disputes => Self::Disputes,
- info::PermissionModule::ThreeDsDecisionManager => Self::ThreeDsDecisionManager,
- info::PermissionModule::SurchargeDecisionManager => Self::SurchargeDecisionManager,
- info::PermissionModule::AccountCreate => Self::AccountCreate,
- info::PermissionModule::Payouts => Self::Payouts,
- info::PermissionModule::Recon => Self::Recon,
- }
- }
-}
-
impl ForeignFrom<UserStatus> for user_role_api::UserStatus {
fn foreign_from(value: UserStatus) -> Self {
match value {
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 22edf6768c8..8975519fd97 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -5,8 +5,7 @@ use common_enums::UserAuthType;
use common_utils::{
encryption::Encryption, errors::CustomResult, id_type, type_name, types::keymanager::Identifier,
};
-use diesel_models::user_role::UserRole;
-use error_stack::{report, ResultExt};
+use error_stack::ResultExt;
use masking::{ExposeInterface, Secret};
use redis_interface::RedisConnectionPool;
@@ -86,45 +85,6 @@ impl UserFromToken {
}
}
-pub async fn generate_jwt_auth_token_without_profile(
- state: &SessionState,
- user: &UserFromStorage,
- user_role: &UserRole,
-) -> UserResult<Secret<String>> {
- let token = AuthToken::new_token(
- user.get_user_id().to_string(),
- user_role
- .merchant_id
- .as_ref()
- .ok_or(report!(UserErrors::InternalServerError))
- .attach_printable("merchant_id not found for user_role")?
- .clone(),
- user_role.role_id.clone(),
- &state.conf,
- user_role
- .org_id
- .as_ref()
- .ok_or(report!(UserErrors::InternalServerError))
- .attach_printable("org_id not found for user_role")?
- .clone(),
- None,
- )
- .await?;
- Ok(Secret::new(token))
-}
-
-pub async fn generate_jwt_auth_token_with_attributes_without_profile(
- state: &SessionState,
- user_id: String,
- merchant_id: id_type::MerchantId,
- org_id: id_type::OrganizationId,
- role_id: String,
-) -> UserResult<Secret<String>> {
- let token =
- AuthToken::new_token(user_id, merchant_id, role_id, &state.conf, org_id, None).await?;
- Ok(Secret::new(token))
-}
-
pub async fn generate_jwt_auth_token_with_attributes(
state: &SessionState,
user_id: String,
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 603c5cc91c1..2bae094fd96 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -364,8 +364,6 @@ pub enum Flow {
InternalUserSignup,
/// Switch org
SwitchOrg,
- /// Switch merchant
- SwitchMerchant,
/// Switch merchant v2
SwitchMerchantV2,
/// Switch profile
@@ -374,8 +372,6 @@ pub enum Flow {
GetAuthorizationInfo,
/// Get Roles info
GetRolesInfo,
- /// List roles
- ListRoles,
/// List roles v2
ListRolesV2,
/// List invitable roles at entity level
@@ -394,14 +390,10 @@ pub enum Flow {
GenerateSampleData,
/// Delete Sample Data
DeleteSampleData,
- /// List merchant accounts for user
- UserMerchantAccountList,
/// Get details of a user
GetUserDetails,
/// Get details of a user role in a merchant account
GetUserRoleDetails,
- /// List users for merchant account
- ListUsersForMerchantAccount,
/// PaymentMethodAuth Link token create
PmAuthLinkTokenCreate,
/// PaymentMethodAuth Exchange token create
@@ -434,12 +426,8 @@ pub enum Flow {
VerifyEmailRequest,
/// Update user account details
UpdateUserAccountDetails,
- /// Accept user invitation using merchant_ids
- AcceptInvitation,
/// Accept user invitation using entities
AcceptInvitationsV2,
- /// Select merchant from invitations
- MerchantSelect,
/// Accept user invitation using entities before user login
AcceptInvitationsPreAuth,
/// Initiate external authentication for a payment
|
refactor
|
Deprecate unused user APIs and stabilize v1 APIs (#6114)
|
4859b7da73125c2da72f4754863ff4485bebce29
|
2023-10-17 20:05:29
|
chikke srujan
|
fix(connector): [Authorizedotnet]fix error deserialization incase of authentication failure (#2600)
| false
|
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index 7ff2098344e..d25e62391b5 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -883,30 +883,31 @@ fn get_error_response(
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
match response.transaction_response {
- Some(transaction_response) => Ok({
- transaction_response
- .errors
- .and_then(|errors| {
- errors.into_iter().next().map(|error| types::ErrorResponse {
- code: error.error_code,
- message: error.error_text,
- reason: None,
- status_code,
- })
- })
- .unwrap_or_else(|| types::ErrorResponse {
- code: consts::NO_ERROR_CODE.to_string(),
- message: consts::NO_ERROR_MESSAGE.to_string(),
- reason: None,
+ Some(authorizedotnet::TransactionResponse::AuthorizedotnetTransactionResponse(
+ payment_response,
+ )) => Ok(payment_response
+ .errors
+ .and_then(|errors| {
+ errors.into_iter().next().map(|error| types::ErrorResponse {
+ code: error.error_code,
+ message: error.error_text.to_owned(),
+ reason: Some(error.error_text),
status_code,
})
- }),
- None => {
+ })
+ .unwrap_or_else(|| types::ErrorResponse {
+ code: consts::NO_ERROR_CODE.to_string(), // authorizedotnet sends 200 in case of bad request so this are hard coded to NO_ERROR_CODE and NO_ERROR_MESSAGE
+ message: consts::NO_ERROR_MESSAGE.to_string(),
+ reason: None,
+ status_code,
+ })),
+ Some(authorizedotnet::TransactionResponse::AuthorizedotnetTransactionResponseError(_))
+ | None => {
let message = &response.messages.message[0].text;
Ok(types::ErrorResponse {
code: consts::NO_ERROR_CODE.to_string(),
message: message.to_string(),
- reason: None,
+ reason: Some(message.to_string()),
status_code,
})
}
diff --git a/crates/router/src/connector/authorizedotnet/transformers.rs b/crates/router/src/connector/authorizedotnet/transformers.rs
index cd7e070b16f..20d78729a1b 100644
--- a/crates/router/src/connector/authorizedotnet/transformers.rs
+++ b/crates/router/src/connector/authorizedotnet/transformers.rs
@@ -453,9 +453,22 @@ pub struct ErrorMessage {
pub error_text: String,
}
+#[derive(Debug, Clone, Deserialize)]
+#[serde(untagged)]
+pub enum TransactionResponse {
+ AuthorizedotnetTransactionResponse(Box<AuthorizedotnetTransactionResponse>),
+ AuthorizedotnetTransactionResponseError(Box<AuthorizedotnetTransactionResponseError>),
+}
+
+#[derive(Debug, Clone, Deserialize)]
+#[serde(rename_all = "PascalCase")]
+pub struct AuthorizedotnetTransactionResponseError {
+ _supplemental_data_qualification_indicator: i64,
+}
+
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
-pub struct TransactionResponse {
+pub struct AuthorizedotnetTransactionResponse {
response_code: AuthorizedotnetPaymentStatus,
#[serde(rename = "transId")]
transaction_id: String,
@@ -550,7 +563,7 @@ impl<F, T>
>,
) -> Result<Self, Self::Error> {
match &item.response.transaction_response {
- Some(transaction_response) => {
+ Some(TransactionResponse::AuthorizedotnetTransactionResponse(transaction_response)) => {
let status = enums::AttemptStatus::from(transaction_response.response_code.clone());
let error = transaction_response.errors.as_ref().and_then(|errors| {
errors.iter().next().map(|error| types::ErrorResponse {
@@ -598,11 +611,13 @@ impl<F, T>
..item.data
})
}
- None => Ok(Self {
- status: enums::AttemptStatus::Failure,
- response: Err(get_err_response(item.http_code, item.response.messages)),
- ..item.data
- }),
+ Some(TransactionResponse::AuthorizedotnetTransactionResponseError(_)) | None => {
+ Ok(Self {
+ status: enums::AttemptStatus::Failure,
+ response: Err(get_err_response(item.http_code, item.response.messages)),
+ ..item.data
+ })
+ }
}
}
}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/.meta.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/.meta.json
new file mode 100644
index 00000000000..69b505c6d86
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/.meta.json
@@ -0,0 +1,3 @@
+{
+ "childrenOrder": ["Payments - Create", "Payments - Retrieve"]
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/.event.meta.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/.event.meta.json
new file mode 100644
index 00000000000..220b1a6723d
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/.event.meta.json
@@ -0,0 +1,3 @@
+{
+ "eventOrder": ["event.test.js", "event.prerequest.js"]
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/event.prerequest.js b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/event.prerequest.js
new file mode 100644
index 00000000000..27965bb9c01
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/event.prerequest.js
@@ -0,0 +1 @@
+pm.environment.set("random_number", _.random(1000, 100000));
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/event.test.js b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/event.test.js
new file mode 100644
index 00000000000..414cbe9ae30
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/event.test.js
@@ -0,0 +1,91 @@
+// Validate status 2xx
+pm.test("[POST]::/payments - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/payments - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[POST]::/payments - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+
+// Response body should have value "processing" or "failed" for "error_code"
+if (jsonData?.error_code) {
+ pm.test(
+ "[POST]::/payments - Content check if value for 'error_code' matches '3' or '11' ",
+ function () {
+ pm.expect(jsonData.error_code).to.be.oneOf(["3", "11"]);
+ },
+ );
+}
+
+// Response body should have value "processing" or "failed" for "status"
+if (jsonData?.error_message) {
+ pm.test(
+ "[POST]::/payments - Content check if value for 'error_message' matches 'processing' or 'This transaction has been declined.' ",
+ function () {
+ pm.expect(jsonData.error_message).to.be.oneOf(["A duplicate transaction has been submitted.", "This transaction has been declined."]);
+ },
+ );
+}
+
+// Response body should have value "processing" or "failed" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments - Content check if value for 'status' matches 'processing' or 'failed' ",
+ function () {
+ pm.expect(jsonData.status).to.be.oneOf(["failed"]);
+ },
+ );
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/request.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/request.json
new file mode 100644
index 00000000000..b9bf4f2b66e
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/request.json
@@ -0,0 +1,87 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw_json_formatted": {
+ "amount": 7003,
+ "currency": "USD",
+ "confirm": true,
+ "routing": {
+ "data": "authorizedotnet",
+ "type": "single"
+ },
+ "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://duck.com",
+ "payment_method": "card",
+ "payment_method_data": {
+ "card": {
+ "card_number": "370000000000002",
+ "card_exp_month": "10",
+ "card_exp_year": "25",
+ "card_holder_name": "joseph Doe",
+ "card_cvc": "900"
+ }
+ },
+ "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"
+ }
+ },
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/response.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Create/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Retrieve/.event.meta.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Retrieve/.event.meta.json
new file mode 100644
index 00000000000..0731450e6b2
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Retrieve/.event.meta.json
@@ -0,0 +1,3 @@
+{
+ "eventOrder": ["event.test.js"]
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Retrieve/event.test.js b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Retrieve/event.test.js
new file mode 100644
index 00000000000..611bb438bb8
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Retrieve/event.test.js
@@ -0,0 +1,71 @@
+// Validate status 2xx
+pm.test("[POST]::/payments - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[POST]::/payments - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[POST]::/payments - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+
+// Response body should have value "processing" or "failed" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments - Content check if value for 'status' matches 'processing' or 'failed' ",
+ function () {
+ pm.expect(jsonData.status).to.be.oneOf(["processing", "failed"]);
+ },
+ );
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Retrieve/request.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Retrieve/request.json
new file mode 100644
index 00000000000..6cd4b7d96c5
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Retrieve/request.json
@@ -0,0 +1,28 @@
+{
+ "method": "GET",
+ "header": [
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "url": {
+ "raw": "{{baseUrl}}/payments/:id?force_sync=true",
+ "host": ["{{baseUrl}}"],
+ "path": ["payments", ":id"],
+ "query": [
+ {
+ "key": "force_sync",
+ "value": "true"
+ }
+ ],
+ "variable": [
+ {
+ "key": "id",
+ "value": "{{payment_id}}",
+ "description": "(Required) unique payment id"
+ }
+ ]
+ },
+ "description": "To retrieve the properties of a Payment. This may be used to get the status of a previously initiated payment or next action for an ongoing payment"
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Retrieve/response.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Retrieve/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Happy Cases/Scenario4-Create failed payment with confirm true copy/Payments - Retrieve/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/.meta.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/.meta.json
new file mode 100644
index 00000000000..0cc63949449
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/.meta.json
@@ -0,0 +1,8 @@
+{
+ "childrenOrder": [
+ "Payments Connector - Update",
+ "Payments - Create",
+ "Recurring Payments - Retrieve",
+ "Payments Connector - Update"
+ ]
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/.event.meta.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/.event.meta.json
new file mode 100644
index 00000000000..220b1a6723d
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/.event.meta.json
@@ -0,0 +1,3 @@
+{
+ "eventOrder": ["event.test.js", "event.prerequest.js"]
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/event.prerequest.js b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/event.prerequest.js
new file mode 100644
index 00000000000..e69de29bb2d
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/event.test.js b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/event.test.js
new file mode 100644
index 00000000000..88e92d8d84a
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/event.test.js
@@ -0,0 +1,39 @@
+// Validate status 2xx
+pm.test(
+ "[POST]::/account/:account_id/connectors - Status code is 2xx",
+ function () {
+ pm.response.to.be.success;
+ },
+);
+
+// Validate if response header has matching content-type
+pm.test(
+ "[POST]::/account/:account_id/connectors - Content-Type is application/json",
+ function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+ },
+);
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set merchant_connector_id as variable for jsonData.merchant_connector_id
+if (jsonData?.merchant_connector_id) {
+ pm.collectionVariables.set(
+ "merchant_connector_id",
+ jsonData.merchant_connector_id,
+ );
+ console.log(
+ "- use {{merchant_connector_id}} as collection variable for value",
+ jsonData.merchant_connector_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{merchant_connector_id}}, as jsonData.merchant_connector_id is undefined.",
+ );
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/request.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/request.json
new file mode 100644
index 00000000000..89e78ae13e1
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/request.json
@@ -0,0 +1,68 @@
+{
+ "auth": {
+ "type": "apikey",
+ "apikey": [
+ {
+ "key": "value",
+ "value": "{{admin_api_key}}",
+ "type": "string"
+ },
+ {
+ "key": "key",
+ "value": "api-key",
+ "type": "string"
+ },
+ {
+ "key": "in",
+ "value": "header",
+ "type": "string"
+ }
+ ]
+ },
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ },
+ "raw_json_formatted": {
+ "connector_type": "fiz_operations",
+ "connector_account_details": {
+ "auth_type": "BodyKey",
+ "api_key": "{{connector_api_key}}",
+ "key1": "authorizedot"
+ }
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/account/:account_id/connectors/:connector_id",
+ "host": ["{{baseUrl}}"],
+ "path": ["account", ":account_id", "connectors",":connector_id"],
+ "variable": [
+ {
+ "key": "account_id",
+ "value": "{{merchant_id}}",
+ "description": "(Required) The unique identifier for the merchant account"
+ },
+ {
+ "key": "connector_id",
+ "value": "{{merchant_connector_id}}",
+ "description": "(Required) The unique identifier for the merchant connector account"
+ }
+
+ ]
+ },
+ "description": "Create a new Payment Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialised services like Fraud / Accounting etc."
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/response.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payment Connector - Update/response.json
@@ -0,0 +1 @@
+[]
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/.event.meta.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/.event.meta.json
new file mode 100644
index 00000000000..220b1a6723d
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/.event.meta.json
@@ -0,0 +1,3 @@
+{
+ "eventOrder": ["event.test.js", "event.prerequest.js"]
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/event.prerequest.js b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/event.prerequest.js
new file mode 100644
index 00000000000..27965bb9c01
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/event.prerequest.js
@@ -0,0 +1 @@
+pm.environment.set("random_number", _.random(1000, 100000));
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/event.test.js b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/event.test.js
new file mode 100644
index 00000000000..d2d47ca994b
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/event.test.js
@@ -0,0 +1,92 @@
+// Validate status 2xx
+pm.test("[GET]::/payments/:id - Status code is 2xx", function () {
+ pm.response.to.be.success;
+});
+
+// Validate if response header has matching content-type
+pm.test("[GET]::/payments/:id - Content-Type is application/json", function () {
+ pm.expect(pm.response.headers.get("Content-Type")).to.include(
+ "application/json",
+ );
+});
+
+// Validate if response has JSON Body
+pm.test("[GET]::/payments/:id - Response has JSON Body", function () {
+ pm.response.to.have.jsonBody();
+});
+
+// Set response object as internal variable
+let jsonData = {};
+try {
+ jsonData = pm.response.json();
+} catch (e) {}
+
+// pm.collectionVariables - Set payment_id as variable for jsonData.payment_id
+if (jsonData?.payment_id) {
+ pm.collectionVariables.set("payment_id", jsonData.payment_id);
+ console.log(
+ "- use {{payment_id}} as collection variable for value",
+ jsonData.payment_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{payment_id}}, as jsonData.payment_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set mandate_id as variable for jsonData.mandate_id
+if (jsonData?.mandate_id) {
+ pm.collectionVariables.set("mandate_id", jsonData.mandate_id);
+ console.log(
+ "- use {{mandate_id}} as collection variable for value",
+ jsonData.mandate_id,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{mandate_id}}, as jsonData.mandate_id is undefined.",
+ );
+}
+
+// pm.collectionVariables - Set client_secret as variable for jsonData.client_secret
+if (jsonData?.client_secret) {
+ pm.collectionVariables.set("client_secret", jsonData.client_secret);
+ console.log(
+ "- use {{client_secret}} as collection variable for value",
+ jsonData.client_secret,
+ );
+} else {
+ console.log(
+ "INFO - Unable to assign variable {{client_secret}}, as jsonData.client_secret is undefined.",
+ );
+}
+
+
+// Response body should have value "processing" or "failed" for "error_code"
+if (jsonData?.error_code) {
+ pm.test(
+ "[POST]::/payments - Content check if value for 'error_code' matches 'E00007' or '11' ",
+ function () {
+ pm.expect(jsonData.error_code).to.be.oneOf(["E00007", "11"]);
+ },
+ );
+}
+
+// Response body should have value "processing" or "failed" for "status"
+if (jsonData?.error_message) {
+ pm.test(
+ "[POST]::/payments - Content check if value for 'error_message' matches 'processing' or 'This transaction has been declined.' ",
+ function () {
+ pm.expect(jsonData.error_message).to.be.oneOf(["A duplicate transaction has been submitted.", "User authentication failed due to invalid authentication values."]);
+ },
+ );
+}
+
+// Response body should have value "processing" or "failed" for "status"
+if (jsonData?.status) {
+ pm.test(
+ "[POST]::/payments - Content check if value for 'status' matches 'processing' or 'failed' ",
+ function () {
+ pm.expect(jsonData.status).to.be.oneOf(["failed"]);
+ },
+ );
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/request.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/request.json
new file mode 100644
index 00000000000..b9bf4f2b66e
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/request.json
@@ -0,0 +1,87 @@
+{
+ "method": "POST",
+ "header": [
+ {
+ "key": "Content-Type",
+ "value": "application/json"
+ },
+ {
+ "key": "Accept",
+ "value": "application/json"
+ }
+ ],
+ "body": {
+ "mode": "raw",
+ "raw_json_formatted": {
+ "amount": 7003,
+ "currency": "USD",
+ "confirm": true,
+ "routing": {
+ "data": "authorizedotnet",
+ "type": "single"
+ },
+ "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://duck.com",
+ "payment_method": "card",
+ "payment_method_data": {
+ "card": {
+ "card_number": "370000000000002",
+ "card_exp_month": "10",
+ "card_exp_year": "25",
+ "card_holder_name": "joseph Doe",
+ "card_cvc": "900"
+ }
+ },
+ "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"
+ }
+ },
+ "options": {
+ "raw": {
+ "language": "json"
+ }
+ }
+ },
+ "url": {
+ "raw": "{{baseUrl}}/payments",
+ "host": ["{{baseUrl}}"],
+ "path": ["payments"]
+ },
+ "description": "To process a payment you will have to create a payment, attach a payment method and confirm. Depending on the user journey you wish to achieve, you may opt to all the steps in a single request or in a sequence of API request using following APIs: (i) Payments - Update, (ii) Payments - Confirm, and (iii) Payments - Capture"
+}
diff --git a/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/response.json b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/response.json
new file mode 100644
index 00000000000..fe51488c706
--- /dev/null
+++ b/postman/collection-dir/authorizedotnet/Flow Testcases/Variation Cases/Scenario12-Failed case for wrong api keys/Payments - Create/response.json
@@ -0,0 +1 @@
+[]
|
fix
|
[Authorizedotnet]fix error deserialization incase of authentication failure (#2600)
|
a2ea0ed19c075fb0e23b16ddc24b5230dc70369b
|
2024-06-05 05:44:52
|
github-actions
|
chore(version): 2024.06.05.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3b2946f8baa..ff445d36849 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,34 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.06.05.0
+
+### Features
+
+- **auth:** Create and use `SinglePurposeOrLoginTokenAuth` ([#4830](https://github.com/juspay/hyperswitch/pull/4830)) ([`5414485`](https://github.com/juspay/hyperswitch/commit/5414485866989c205830feec8ff79baecc834950))
+- **connector:** [CRYPTOPAY] Make payment_method_data.crypto.network as enum ([#4853](https://github.com/juspay/hyperswitch/pull/4853)) ([`1eaba9a`](https://github.com/juspay/hyperswitch/commit/1eaba9a10b11a4f1d540e0a848a798c81e3f6fd1))
+- **cypress:** Add service level testing for Payouts ([#4744](https://github.com/juspay/hyperswitch/pull/4744)) ([`1d36798`](https://github.com/juspay/hyperswitch/commit/1d36798399c118f7cb7af93935123634e1afd6a0))
+- **router:** Add `request_external_three_ds_authentication` flag in payment_method_list_response ([#4864](https://github.com/juspay/hyperswitch/pull/4864)) ([`fcf5297`](https://github.com/juspay/hyperswitch/commit/fcf52973f49e091cfbf4390e70cdfe883b15bf3b))
+
+### Bug Fixes
+
+- **cypress:** Fix `redirectionHandler` from failing to compile ([#4846](https://github.com/juspay/hyperswitch/pull/4846)) ([`901b88a`](https://github.com/juspay/hyperswitch/commit/901b88ab8065459cf9f9d8b2ac27f378449afc4a))
+
+### Refactors
+
+- **api_models:** Rename Card struct for payouts to avoid overrides in auto generated open API spec ([#4861](https://github.com/juspay/hyperswitch/pull/4861)) ([`7f75f94`](https://github.com/juspay/hyperswitch/commit/7f75f941c18e5c1ce113a6e59f91a47e8302838d))
+- **connector:**
+ - [Adyen] handle redirection error response ([#4862](https://github.com/juspay/hyperswitch/pull/4862)) ([`8096d5e`](https://github.com/juspay/hyperswitch/commit/8096d5e577d892b3cdb7854dd100c3c8bab955d6))
+ - [Klarna] Add support for Klarna Optional Shipping Address ([#4876](https://github.com/juspay/hyperswitch/pull/4876)) ([`3509b45`](https://github.com/juspay/hyperswitch/commit/3509b45e1b855dce4561beb5cded4ba490be6f8c))
+
+### Miscellaneous Tasks
+
+- **euclid_wasm:** Paypal metadata ([#4868](https://github.com/juspay/hyperswitch/pull/4868)) ([`d413e1a`](https://github.com/juspay/hyperswitch/commit/d413e1a8a5105a51f1909e160cda1c3648713926))
+
+**Full Changelog:** [`2024.06.04.1...2024.06.05.0`](https://github.com/juspay/hyperswitch/compare/2024.06.04.1...2024.06.05.0)
+
+- - -
+
## 2024.06.04.1
### Bug Fixes
|
chore
|
2024.06.05.0
|
418715b816337bcaeee1aceeb911e6d329add2ad
|
2023-10-19 19:39:09
|
Seemebadnekai
|
refactor(connector): [Forte] Remove Default Case Handling (#2625)
| false
|
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs
index bc7c55c4f87..7851608d11b 100644
--- a/crates/router/src/connector/forte/transformers.rs
+++ b/crates/router/src/connector/forte/transformers.rs
@@ -101,9 +101,23 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest {
card,
})
}
- _ => Err(errors::ConnectorError::NotImplemented(
- "Payment Method".to_string(),
- ))?,
+ api_models::payments::PaymentMethodData::CardRedirect(_)
+ | api_models::payments::PaymentMethodData::Wallet(_)
+ | api_models::payments::PaymentMethodData::PayLater(_)
+ | api_models::payments::PaymentMethodData::BankRedirect(_)
+ | api_models::payments::PaymentMethodData::BankDebit(_)
+ | api_models::payments::PaymentMethodData::BankTransfer(_)
+ | api_models::payments::PaymentMethodData::Crypto(_)
+ | api_models::payments::PaymentMethodData::MandatePayment {}
+ | api_models::payments::PaymentMethodData::Reward {}
+ | api_models::payments::PaymentMethodData::Upi(_)
+ | api_models::payments::PaymentMethodData::Voucher(_)
+ | api_models::payments::PaymentMethodData::GiftCard(_) => {
+ Err(errors::ConnectorError::NotSupported {
+ message: utils::SELECTED_PAYMENT_METHOD.to_string(),
+ connector: "Forte",
+ })?
+ }
}
}
}
|
refactor
|
[Forte] Remove Default Case Handling (#2625)
|
e377279d9cc872238fcfd8de324b44b0249b95c2
|
2023-10-31 19:28:58
|
Adarsh Jha
|
feat(connector): [BitPay] Currency Unit Conversion (#2736)
| false
|
diff --git a/crates/router/src/connector/bitpay.rs b/crates/router/src/connector/bitpay.rs
index 2dc634426f3..e8826e93390 100644
--- a/crates/router/src/connector/bitpay.rs
+++ b/crates/router/src/connector/bitpay.rs
@@ -82,6 +82,10 @@ impl ConnectorCommon for Bitpay {
"bitpay"
}
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Minor
+ }
+
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
@@ -169,7 +173,13 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
&self,
req: &types::PaymentsAuthorizeRouterData,
) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
- let req_obj = bitpay::BitpayPaymentsRequest::try_from(req)?;
+ let connector_router_data = bitpay::BitpayRouterData::try_from((
+ &self.get_currency_unit(),
+ req.request.currency,
+ req.request.amount,
+ req,
+ ))?;
+ let req_obj = bitpay::BitpayPaymentsRequest::try_from(&connector_router_data)?;
let bitpay_req = types::RequestBody::log_and_get_request_body(
&req_obj,
diff --git a/crates/router/src/connector/bitpay/transformers.rs b/crates/router/src/connector/bitpay/transformers.rs
index f99729da16d..c5c20608a75 100644
--- a/crates/router/src/connector/bitpay/transformers.rs
+++ b/crates/router/src/connector/bitpay/transformers.rs
@@ -9,6 +9,37 @@ use crate::{
types::{self, api, storage::enums, ConnectorAuthType},
};
+#[derive(Debug, Serialize)]
+pub struct BitpayRouterData<T> {
+ pub amount: i64,
+ pub router_data: T,
+}
+
+impl<T>
+ TryFrom<(
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ )> for BitpayRouterData<T>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+
+ fn try_from(
+ (_currency_unit, _currency, amount, router_data): (
+ &types::api::CurrencyUnit,
+ types::storage::enums::Currency,
+ i64,
+ T,
+ ),
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount,
+ router_data,
+ })
+ }
+}
+
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TransactionSpeed {
@@ -31,9 +62,11 @@ pub struct BitpayPaymentsRequest {
token: Secret<String>,
}
-impl TryFrom<&types::PaymentsAuthorizeRouterData> for BitpayPaymentsRequest {
+impl TryFrom<&BitpayRouterData<&types::PaymentsAuthorizeRouterData>> for BitpayPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &BitpayRouterData<&types::PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
get_crypto_specific_payment_data(item)
}
}
@@ -152,11 +185,13 @@ pub struct BitpayRefundRequest {
pub amount: i64,
}
-impl<F> TryFrom<&types::RefundsRouterData<F>> for BitpayRefundRequest {
+impl<F> TryFrom<&BitpayRouterData<&types::RefundsRouterData<F>>> for BitpayRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
- fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ fn try_from(
+ item: &BitpayRouterData<&types::RefundsRouterData<F>>,
+ ) -> Result<Self, Self::Error> {
Ok(Self {
- amount: item.request.refund_amount,
+ amount: item.router_data.request.refund_amount,
})
}
}
@@ -232,14 +267,14 @@ pub struct BitpayErrorResponse {
}
fn get_crypto_specific_payment_data(
- item: &types::PaymentsAuthorizeRouterData,
+ item: &BitpayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<BitpayPaymentsRequest, error_stack::Report<errors::ConnectorError>> {
- let price = item.request.amount;
- let currency = item.request.currency.to_string();
- let redirect_url = item.request.get_return_url()?;
- let notification_url = item.request.get_webhook_url()?;
+ let price = item.amount;
+ let currency = item.router_data.request.currency.to_string();
+ let redirect_url = item.router_data.request.get_return_url()?;
+ let notification_url = item.router_data.request.get_webhook_url()?;
let transaction_speed = TransactionSpeed::Medium;
- let auth_type = item.connector_auth_type.clone();
+ let auth_type = item.router_data.connector_auth_type.clone();
let token = match auth_type {
ConnectorAuthType::HeaderKey { api_key } => api_key,
_ => String::default().into(),
|
feat
|
[BitPay] Currency Unit Conversion (#2736)
|
e5ad9c5c35f386486afedded90c46793196a17d0
|
2023-10-03 19:14:23
|
Shankar Singh C
|
refactor(router): add `#[cfg(not(feature = "kms"))]` feature flag to test the simplified apple pay flow locally (#2200)
| false
|
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index adde413730c..228d02e1dda 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -41,7 +41,6 @@ pub(crate) const APPLEPAY_VALIDATION_URL: &str =
pub(crate) const QR_IMAGE_DATA_SOURCE_STRING: &str = "data:image/png;base64";
// OID (Object Identifier) for the merchant ID field extension.
-#[cfg(feature = "kms")]
pub(crate) const MERCHANT_ID_FIELD_EXTENSION_ID: &str = "1.2.840.113635.100.6.32";
pub(crate) const METRICS_HOST_TAG_NAME: &str = "host";
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index cb2b24c4158..708e20d2050 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -15,7 +15,6 @@ use data_models::mandates::MandateData;
use diesel_models::{ephemeral_key, fraud_check::FraudCheck};
use error_stack::{IntoReport, ResultExt};
use futures::future::join_all;
-#[cfg(feature = "kms")]
use helpers::ApplePayData;
use masking::Secret;
use router_env::{instrument, tracing};
@@ -643,7 +642,6 @@ where
// Tokenization Action will be DecryptApplePayToken, only when payment method type is Apple Pay
// and the connector supports Apple Pay predecrypt
- #[cfg(feature = "kms")]
if matches!(
tokenization_action,
TokenizationAction::DecryptApplePayToken
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index d964b4b2e2b..60ebfd2bdf0 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -16,26 +16,23 @@ use error_stack::{report, IntoReport, ResultExt};
use external_services::kms;
use josekit::jwe;
use masking::{ExposeInterface, PeekInterface};
-#[cfg(feature = "kms")]
-use openssl::derive::Deriver;
-#[cfg(feature = "kms")]
-use openssl::pkey::PKey;
-#[cfg(feature = "kms")]
-use openssl::symm::{decrypt_aead, Cipher};
+use openssl::{
+ derive::Deriver,
+ pkey::PKey,
+ symm::{decrypt_aead, Cipher},
+};
use router_env::{instrument, logger, tracing};
use time::Duration;
use uuid::Uuid;
-#[cfg(feature = "kms")]
use x509_parser::parse_x509_certificate;
use super::{
operations::{BoxedOperation, Operation, PaymentResponse},
CustomerDetails, PaymentData,
};
-#[cfg(feature = "kms")]
-use crate::connector;
use crate::{
configs::settings::{ConnectorRequestReferenceIdConfig, Server, TempLockerDisableConfig},
+ connector,
consts::{self, BASE64_ENGINE},
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
@@ -3213,7 +3210,6 @@ pub struct ApplePayHeader {
transaction_id: masking::Secret<String>,
}
-#[cfg(feature = "kms")]
impl ApplePayData {
pub fn token_json(
wallet_data: api_models::payments::WalletData,
@@ -3241,12 +3237,16 @@ impl ApplePayData {
&self,
state: &AppState,
) -> CustomResult<String, errors::ApplePayDecryptionError> {
+ #[cfg(feature = "kms")]
let cert_data = kms::get_kms_client(&state.conf.kms)
.await
.decrypt(&state.conf.applepay_decrypt_keys.apple_pay_ppc)
.await
.change_context(errors::ApplePayDecryptionError::DecryptionFailed)?;
+ #[cfg(not(feature = "kms"))]
+ let cert_data = &state.conf.applepay_decrypt_keys.apple_pay_ppc;
+
let base64_decode_cert_data = BASE64_ENGINE
.decode(cert_data)
.into_report()
@@ -3297,12 +3297,15 @@ impl ApplePayData {
.change_context(errors::ApplePayDecryptionError::KeyDeserializationFailed)
.attach_printable("Failed to deserialize the public key")?;
+ #[cfg(feature = "kms")]
let decrypted_apple_pay_ppc_key = kms::get_kms_client(&state.conf.kms)
.await
.decrypt(&state.conf.applepay_decrypt_keys.apple_pay_ppc_key)
.await
.change_context(errors::ApplePayDecryptionError::DecryptionFailed)?;
+ #[cfg(not(feature = "kms"))]
+ let decrypted_apple_pay_ppc_key = &state.conf.applepay_decrypt_keys.apple_pay_ppc_key;
// Create PKey objects from EcKey
let private_key = PKey::private_key_from_pem(decrypted_apple_pay_ppc_key.as_bytes())
.into_report()
|
refactor
|
add `#[cfg(not(feature = "kms"))]` feature flag to test the simplified apple pay flow locally (#2200)
|
afeb83194f0772e7550c5d4a6ed4ba16216d2a28
|
2023-04-20 17:40:49
|
Arjun Karthik
|
fix(connector): fix adyen unit test (#931)
| false
|
diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs
index 84e860dd442..f9d60e23e28 100644
--- a/crates/router/tests/connectors/adyen.rs
+++ b/crates/router/tests/connectors/adyen.rs
@@ -417,10 +417,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
)
.await
.unwrap();
- assert_eq!(
- response.response.unwrap_err().message,
- "The provided Expiry Date is not valid.: Expiry month should be between 1 and 12 inclusive: 20",
- );
+ assert_eq!(response.response.unwrap_err().message, "Refused",);
}
// Creates a payment with incorrect expiry year.
|
fix
|
fix adyen unit test (#931)
|
c3b7197304283c14bb7474787c99e78fac8a1d78
|
2025-02-27 17:34:25
|
GORAKHNATH YADAV
|
docs(api-reference): fix the content of the tip (#7387)
| false
|
diff --git a/api-reference/api-reference/payments/Introduction--to--payments.mdx b/api-reference/api-reference/payments/Introduction--to--payments.mdx
index 4cccc9cde2c..2893aec261b 100644
--- a/api-reference/api-reference/payments/Introduction--to--payments.mdx
+++ b/api-reference/api-reference/payments/Introduction--to--payments.mdx
@@ -15,7 +15,7 @@ You have two options to use the Payments API:
2. **Self-Deploy** – Create merchants and API keys through Rest API.
Each option has specific nuances, we have mentioned the differences in the below step by step guide
-<Tip>We recommend using our [Dashboard](https://app.hyperswitch.io/dashboard/login) to generate API Key and setting up Connectors (Step 4)</Tip> for faster trial and simple setup
+<Tip>We recommend using our [Dashboard](https://app.hyperswitch.io/dashboard/login) to generate API Key and setting up Connectors (Step 4) for faster trial and simple setup.</Tip>
<Steps>
<Step title="Create a Merchant Account">
This account is representative of you or your organization that would like to accept payments from different <Tooltip tip="Can be a payment method or payment service provider">payment connectors</Tooltip>
|
docs
|
fix the content of the tip (#7387)
|
50706bde774d2c0864d77c7f74e26427a4f7479a
|
2022-12-19 13:38:03
|
Narayan Bhat
|
feat(core): support for gpay session token creation (#152)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index a01dded02a3..5b2ff66c609 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -691,11 +691,65 @@ pub struct PaymentsSessionRequest {
pub client_secret: String,
}
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GpayAllowedMethodsParameters {
+ pub allowed_auth_methods: Vec<String>,
+ pub allowed_card_networks: Vec<String>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GpayTokenParameters {
+ pub gateway: String,
+ pub gateway_merchant_id: String,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GpayTokenizationSpecification {
+ #[serde(rename = "type")]
+ pub token_specification_type: String,
+ pub parameters: GpayTokenParameters,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GpayAllowedPaymentMethods {
+ #[serde(rename = "type")]
+ pub payment_method_type: String,
+ pub parameters: GpayAllowedMethodsParameters,
+ pub tokenization_specification: GpayTokenizationSpecification,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GpayTransactionInfo {
+ pub country_code: String,
+ pub currency_code: String,
+ pub total_price_status: String,
+ pub total_price: i64,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GpayMerchantInfo {
+ pub merchant_name: String,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GpayMetadata {
+ pub merchant_info: GpayMerchantInfo,
+ pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>,
+}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct GpaySessionTokenData {
+ pub gpay: GpayMetadata,
+}
+
#[derive(Debug, Clone, serde::Serialize)]
#[serde(tag = "connector_name")]
#[serde(rename_all = "lowercase")]
pub enum SessionToken {
- Gpay {},
+ Gpay {
+ allowed_payment_methods: Vec<GpayAllowedPaymentMethods>,
+ transaction_info: GpayTransactionInfo,
+ },
Klarna {
session_token: String,
session_id: String,
diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs
index dc4eaccc310..8c8202521a8 100644
--- a/crates/router/src/connector/braintree.rs
+++ b/crates/router/src/connector/braintree.rs
@@ -111,7 +111,7 @@ impl
.build(),
);
- logger::debug!(session_request=?request);
+ logger::debug!(braintree_session_request=?request);
Ok(request)
}
@@ -132,9 +132,14 @@ impl
fn get_request_body(
&self,
- _req: &types::PaymentsSessionRouterData,
+ req: &types::PaymentsSessionRouterData,
) -> CustomResult<Option<String>, errors::ConnectorError> {
- Ok(None)
+ let braintree_session_request =
+ utils::Encode::<braintree::BraintreeSessionRequest>::convert_and_encode(req)
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+
+ logger::debug!(?braintree_session_request);
+ Ok(Some(braintree_session_request))
}
fn handle_response(
diff --git a/crates/router/src/connector/braintree/transformers.rs b/crates/router/src/connector/braintree/transformers.rs
index c28f713575d..c4a5b0bb6e2 100644
--- a/crates/router/src/connector/braintree/transformers.rs
+++ b/crates/router/src/connector/braintree/transformers.rs
@@ -19,6 +19,27 @@ pub struct BraintreePaymentsRequest {
transaction: TransactionBody,
}
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct BraintreeApiVersion {
+ version: String,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct BraintreeSessionRequest {
+ client_token: BraintreeApiVersion,
+}
+
+impl TryFrom<&types::PaymentsSessionRouterData> for BraintreeSessionRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(_item: &types::PaymentsSessionRouterData) -> Result<Self, Self::Error> {
+ Ok(Self {
+ client_token: BraintreeApiVersion {
+ version: "2".to_string(),
+ },
+ })
+ }
+}
+
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct TransactionBody {
@@ -178,7 +199,7 @@ impl<F, T>
Ok(types::RouterData {
response: Ok(types::PaymentsResponseData::SessionResponse {
session_token: types::api::SessionToken::Paypal {
- session_token: item.response.client_token.value.authorization_fingerprint,
+ session_token: item.response.client_token.value,
},
}),
..item.data
@@ -192,16 +213,10 @@ pub struct BraintreePaymentsResponse {
transaction: TransactionResponse,
}
-#[derive(Default, Debug, Clone, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct AuthorizationFingerprint {
- authorization_fingerprint: String,
-}
#[derive(Default, Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClientToken {
- #[serde(with = "common_utils::custom_serde::json_string")]
- pub value: AuthorizationFingerprint,
+ pub value: String,
}
#[derive(Default, Debug, Clone, Deserialize)]
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 2cb971531db..3b7a9e75ee4 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -169,7 +169,6 @@ where
}
#[allow(clippy::too_many_arguments)]
-#[instrument(skip_all)]
pub async fn payments_core<F, Res, Req, Op, FData>(
state: &AppState,
merchant_account: storage::MerchantAccount,
@@ -236,8 +235,11 @@ where
},
)?;
- let connector_data =
- api::ConnectorData::get_connector_by_name(&state.conf.connectors, &connector)?;
+ let connector_data = api::ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ &connector,
+ api::GetToken::Connector,
+ )?;
let flow_type = connector_data
.connector
@@ -402,17 +404,16 @@ where
for (connector_res, connector) in result.into_iter().zip(connectors) {
let connector_name = connector.connector_name.to_string();
- match connector_res?.response {
+ match connector_res {
Ok(connector_response) => {
- if let types::PaymentsResponseData::SessionResponse { session_token } =
- connector_response
+ if let Ok(types::PaymentsResponseData::SessionResponse { session_token }) =
+ connector_response.response
{
payment_data.sessions_token.push(session_token);
}
}
-
Err(connector_error) => {
- logger::debug!(
+ logger::error!(
"sessions_connector_error {} {:?}",
connector_name,
connector_error
diff --git a/crates/router/src/core/payments/flows/session_flow.rs b/crates/router/src/core/payments/flows/session_flow.rs
index 50f77ff3cef..69aa47238f9 100644
--- a/crates/router/src/core/payments/flows/session_flow.rs
+++ b/crates/router/src/core/payments/flows/session_flow.rs
@@ -1,9 +1,11 @@
+use api_models::payments as payment_types;
use async_trait::async_trait;
+use error_stack::ResultExt;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
- errors::{ConnectorErrorExt, RouterResult},
+ errors::{self, ConnectorErrorExt, RouterResult},
payments::{self, transformers, PaymentData},
},
routes, services,
@@ -11,6 +13,7 @@ use crate::{
self, api,
storage::{self, enums},
},
+ utils::OptionExt,
};
#[async_trait]
@@ -55,6 +58,45 @@ impl Feature<api::Session, types::PaymentsSessionData> for types::PaymentsSessio
}
}
+fn create_gpay_session_token(
+ router_data: &types::PaymentsSessionRouterData,
+) -> RouterResult<types::PaymentsSessionRouterData> {
+ let connector_metadata = router_data.connector_meta_data.clone();
+
+ let gpay_data = connector_metadata
+ .clone()
+ .parse_value::<payment_types::GpaySessionTokenData>("GpaySessionTokenData")
+ .change_context(errors::ConnectorError::NoConnectorMetaData)
+ .attach_printable(format!(
+ "cannnot parse gpay metadata from the given value {:?}",
+ connector_metadata
+ ))
+ .change_context(errors::ApiErrorResponse::InvalidDataFormat {
+ field_name: "connector_metadata".to_string(),
+ expected_format: "gpay_metadata_format".to_string(),
+ })?;
+
+ let session_data = router_data.request.clone();
+ let transaction_info = payment_types::GpayTransactionInfo {
+ country_code: session_data.country.unwrap_or_else(|| "US".to_string()),
+ currency_code: router_data.request.currency.to_string(),
+ total_price_status: "Final".to_string(),
+ total_price: router_data.request.amount,
+ };
+
+ let response_router_data = types::PaymentsSessionRouterData {
+ response: Ok(types::PaymentsResponseData::SessionResponse {
+ session_token: payment_types::SessionToken::Gpay {
+ allowed_payment_methods: gpay_data.gpay.allowed_payment_methods,
+ transaction_info,
+ },
+ }),
+ ..router_data.clone()
+ };
+
+ Ok(response_router_data)
+}
+
impl types::PaymentsSessionRouterData {
pub async fn decide_flow<'a, 'b>(
&'b self,
@@ -64,20 +106,25 @@ impl types::PaymentsSessionRouterData {
_confirm: Option<bool>,
call_connector_action: payments::CallConnectorAction,
) -> RouterResult<types::PaymentsSessionRouterData> {
- let connector_integration: services::BoxedConnectorIntegration<
- api::Session,
- types::PaymentsSessionData,
- types::PaymentsResponseData,
- > = connector.connector.get_connector_integration();
- let resp = services::execute_connector_processing_step(
- state,
- connector_integration,
- self,
- call_connector_action,
- )
- .await
- .map_err(|error| error.to_payment_failed_response())?;
+ match connector.get_token {
+ api::GetToken::Metadata => create_gpay_session_token(self),
+ api::GetToken::Connector => {
+ let connector_integration: services::BoxedConnectorIntegration<
+ api::Session,
+ types::PaymentsSessionData,
+ types::PaymentsResponseData,
+ > = connector.connector.get_connector_integration();
+ let resp = services::execute_connector_processing_step(
+ state,
+ connector_integration,
+ self,
+ call_connector_action,
+ )
+ .await
+ .map_err(|error| error.to_payment_failed_response())?;
- Ok(resp)
+ Ok(resp)
+ }
+ }
}
}
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index c32acc0a61c..c363dbd8a29 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -650,7 +650,11 @@ pub async fn get_connector_default(
.change_context(errors::ApiErrorResponse::InternalServerError)?
.as_str();
- let connector_data = api::ConnectorData::get_connector_by_name(connectors, connector_name)?;
+ let connector_data = api::ConnectorData::get_connector_by_name(
+ connectors,
+ connector_name,
+ api::GetToken::Connector,
+ )?;
Ok(api::ConnectorCallType::Single(connector_data))
}
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 1cf6cdc645a..b94929e47ec 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -1,6 +1,7 @@
use std::marker::PhantomData;
use async_trait::async_trait;
+use common_utils::ext_traits::ValueExt;
use error_stack::ResultExt;
use router_derive::PaymentOperation;
use router_env::{instrument, tracing};
@@ -197,6 +198,11 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsSessionRequest> for Paymen
}
}
+#[derive(serde::Deserialize, Default)]
+pub struct PaymentMethodEnabled {
+ payment_method: String,
+}
+
#[async_trait]
impl<F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsSessionRequest>>
Domain<F, api::PaymentsSessionRequest> for Op
@@ -257,12 +263,13 @@ where
let supported_connectors: &Vec<String> = state.conf.connectors.supported.wallets.as_ref();
- //FIXME: Check if merchant has enabled wallet through the connector
- let connector_names = db
+ let connector_accounts = db
.find_merchant_connector_account_by_merchant_id_list(&merchant_account.merchant_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Database error when querying for merchant accounts")?
+ .attach_printable("Database error when querying for merchant connector accounts")?;
+
+ let normal_connector_names = connector_accounts
.iter()
.filter(|connector_account| {
supported_connectors.contains(&connector_account.connector_name)
@@ -270,11 +277,48 @@ where
.map(|filtered_connector| filtered_connector.connector_name.clone())
.collect::<Vec<String>>();
- let mut connectors_data = Vec::with_capacity(connector_names.len());
+ // Parse the payment methods enabled to check if the merchant has enabled gpay ( wallet )
+ // through that connector this parsing from Value to payment method is costly and has to be done for every connector
+ // for sure looks like an area of optimization
+ 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: PaymentMethodEnabled = payment_method
+ .clone()
+ .parse_value("payment_method")
+ .unwrap_or_default();
+
+ parsed_payment_method.payment_method == "wallet"
+ })
+ })
+ .map(|filtered_connector| filtered_connector.connector_name.clone())
+ .collect::<Vec<String>>();
+
+ 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);
+ }
- for connector_name in connector_names {
- let connector_data =
- api::ConnectorData::get_connector_by_name(connectors, &connector_name)?;
+ for connector_name in session_token_from_metadata_connectors {
+ let connector_data = api::ConnectorData::get_connector_by_name(
+ connectors,
+ &connector_name,
+ api::GetToken::Metadata,
+ )?;
connectors_data.push(connector_data);
}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 56abaf783f1..801b0b0c4c7 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -468,6 +468,11 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsSessionData {
Ok(Self {
amount: payment_data.amount.into(),
currency: payment_data.currency,
+ country: payment_data
+ .address
+ .billing
+ .and_then(|billing_address| billing_address.address.map(|address| address.country))
+ .flatten(),
})
}
}
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 13e8a37079c..bef2c60964b 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -97,10 +97,13 @@ pub async fn trigger_refund_to_gateway(
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)?;
let connector_id = connector.to_string();
- let connector: api::ConnectorData =
- api::ConnectorData::get_connector_by_name(&state.conf.connectors, &connector_id)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to get the connector")?;
+ let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ &connector_id,
+ api::GetToken::Connector,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get the connector")?;
let currency = payment_attempt.currency.ok_or_else(|| {
report!(errors::ApiErrorResponse::MissingRequiredField {
@@ -241,10 +244,13 @@ pub async fn sync_refund_with_gateway(
refund: &storage::Refund,
) -> RouterResult<storage::Refund> {
let connector_id = refund.connector.to_string();
- let connector: api::ConnectorData =
- api::ConnectorData::get_connector_by_name(&state.conf.connectors, &connector_id)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to get the connector")?;
+ let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ &connector_id,
+ api::GetToken::Connector,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to get the connector")?;
let currency = payment_attempt.currency.get_required_value("currency")?;
diff --git a/crates/router/src/core/webhooks.rs b/crates/router/src/core/webhooks.rs
index d581b848a19..386e62dc621 100644
--- a/crates/router/src/core/webhooks.rs
+++ b/crates/router/src/core/webhooks.rs
@@ -197,10 +197,13 @@ pub async fn webhooks_core(
connector_name: &str,
body: actix_web::web::Bytes,
) -> RouterResponse<serde_json::Value> {
- let connector =
- api::ConnectorData::get_connector_by_name(&state.conf.connectors, connector_name)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed construction of ConnectorData")?;
+ let connector = api::ConnectorData::get_connector_by_name(
+ &state.conf.connectors,
+ connector_name,
+ api::GetToken::Connector,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed construction of ConnectorData")?;
let connector = connector.connector;
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index 308df41550a..391c4333e5b 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -124,9 +124,9 @@ pub struct PaymentsCancelData {
#[derive(Debug, Clone)]
pub struct PaymentsSessionData {
- //TODO: Add the fields here as required
pub amount: i64,
pub currency: storage_enums::Currency,
+ pub country: Option<String>,
}
#[derive(Debug, Clone)]
@@ -147,12 +147,6 @@ pub struct PaymentsTransactionResponse {
pub redirect: bool,
}
-#[derive(Debug, Clone)]
-pub struct PaymentsSessionResponse {
- pub session_id: Option<String>,
- pub session_token: String,
-}
-
#[derive(Debug, Clone)]
pub enum PaymentsResponseData {
TransactionResponse {
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 90602740f39..d97c252f360 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -64,9 +64,17 @@ impl<T: Refund + Payment + Debug + ConnectorRedirectResponse + Send + IncomingWe
type BoxedConnector = Box<&'static (dyn Connector + marker::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 )
+pub enum GetToken {
+ Metadata,
+ Connector,
+}
+
pub struct ConnectorData {
pub connector: BoxedConnector,
pub connector_name: types::Connector,
+ pub get_token: GetToken,
}
pub enum ConnectorCallType {
@@ -78,6 +86,7 @@ impl ConnectorData {
pub fn get_connector_by_name(
connectors: &Connectors,
name: &str,
+ connector_type: GetToken,
) -> CustomResult<ConnectorData, errors::ApiErrorResponse> {
let connector = Self::convert_connector(connectors, name)?;
let connector_name = types::Connector::from_str(name)
@@ -88,6 +97,7 @@ impl ConnectorData {
Ok(ConnectorData {
connector,
connector_name,
+ get_token: connector_type,
})
}
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index 1bf4374d27f..aed7c9c70df 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -104,6 +104,7 @@ async fn payments_create_success() {
let connector = types::api::ConnectorData {
connector: Box::new(&CV),
connector_name: types::Connector::Aci,
+ get_token: types::api::GetToken::Connector,
};
let connector_integration: services::BoxedConnectorIntegration<
types::api::Authorize,
@@ -135,6 +136,7 @@ async fn payments_create_failure() {
let connector = types::api::ConnectorData {
connector: Box::new(&CV),
connector_name: types::Connector::Aci,
+ get_token: types::api::GetToken::Connector,
};
let connector_integration: services::BoxedConnectorIntegration<
types::api::Authorize,
@@ -171,6 +173,7 @@ async fn refund_for_successful_payments() {
let connector = types::api::ConnectorData {
connector: Box::new(&CV),
connector_name: types::Connector::Aci,
+ get_token: types::api::GetToken::Connector,
};
let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await;
let connector_integration: services::BoxedConnectorIntegration<
@@ -226,6 +229,7 @@ async fn refunds_create_failure() {
let connector = types::api::ConnectorData {
connector: Box::new(&CV),
connector_name: types::Connector::Aci,
+ get_token: types::api::GetToken::Connector,
};
let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await;
let connector_integration: services::BoxedConnectorIntegration<
diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs
index 0ad2f938cbf..5c4c33f3d2e 100644
--- a/crates/router/tests/connectors/authorizedotnet.rs
+++ b/crates/router/tests/connectors/authorizedotnet.rs
@@ -102,6 +102,7 @@ async fn payments_create_success() {
let connector = types::api::ConnectorData {
connector: Box::new(&CV),
connector_name: types::Connector::Authorizedotnet,
+ get_token: types::api::GetToken::Connector,
};
let connector_integration: services::BoxedConnectorIntegration<
types::api::Authorize,
@@ -136,6 +137,7 @@ async fn payments_create_failure() {
let connector = types::api::ConnectorData {
connector: Box::new(&CV),
connector_name: types::Connector::Authorizedotnet,
+ get_token: types::api::GetToken::Connector,
};
let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await;
let connector_integration: services::BoxedConnectorIntegration<
@@ -179,6 +181,7 @@ async fn refunds_create_success() {
let connector = types::api::ConnectorData {
connector: Box::new(&CV),
connector_name: types::Connector::Authorizedotnet,
+ get_token: types::api::GetToken::Connector,
};
let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await;
let connector_integration: services::BoxedConnectorIntegration<
@@ -214,6 +217,7 @@ async fn refunds_create_failure() {
let connector = types::api::ConnectorData {
connector: Box::new(&CV),
connector_name: types::Connector::Authorizedotnet,
+ get_token: types::api::GetToken::Connector,
};
let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await;
let connector_integration: services::BoxedConnectorIntegration<
diff --git a/crates/router/tests/connectors/checkout.rs b/crates/router/tests/connectors/checkout.rs
index 867375f9e4a..06f0af68c47 100644
--- a/crates/router/tests/connectors/checkout.rs
+++ b/crates/router/tests/connectors/checkout.rs
@@ -100,6 +100,7 @@ async fn test_checkout_payment_success() {
let connector = types::api::ConnectorData {
connector: Box::new(&CV),
connector_name: types::Connector::Checkout,
+ get_token: types::api::GetToken::Connector,
};
let state = routes::AppState::with_storage(conf, StorageImpl::PostgresqlTest).await;
let connector_integration: services::BoxedConnectorIntegration<
@@ -138,6 +139,7 @@ async fn test_checkout_refund_success() {
let connector = types::api::ConnectorData {
connector: Box::new(&CV),
connector_name: types::Connector::Checkout,
+ get_token: types::api::GetToken::Connector,
};
let connector_integration: services::BoxedConnectorIntegration<
types::api::Authorize,
@@ -203,6 +205,7 @@ async fn test_checkout_payment_failure() {
let connector = types::api::ConnectorData {
connector: Box::new(&CV),
connector_name: types::Connector::Checkout,
+ get_token: types::api::GetToken::Connector,
};
let connector_integration: services::BoxedConnectorIntegration<
types::api::Authorize,
@@ -234,6 +237,7 @@ async fn test_checkout_refund_failure() {
let connector = types::api::ConnectorData {
connector: Box::new(&CV),
connector_name: types::Connector::Checkout,
+ get_token: types::api::GetToken::Connector,
};
let connector_integration: services::BoxedConnectorIntegration<
types::api::Authorize,
|
feat
|
support for gpay session token creation (#152)
|
5a5ac61d011d16153c317bde574055dc058190e6
|
2022-12-01 14:35:04
|
Kartikeya Hegde
|
fix: Update browser info on payment confirmation (#52)
| false
|
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index 70174cb2dba..340eaad9ba2 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -18,11 +18,11 @@ use crate::{
},
routes::AppState,
types::{
- api,
+ self, api,
storage::{self, enums},
Connector,
},
- utils::OptionExt,
+ utils::{self, OptionExt},
};
#[derive(Debug, Clone, Copy, PaymentOperation)]
@@ -71,6 +71,15 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
}
}
+ let browser_info = request
+ .browser_info
+ .clone()
+ .map(|x| utils::Encode::<types::BrowserInformation>::encode_to_value(&x))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "browser_info",
+ })?;
+
payment_attempt = db
.find_payment_attempt_by_payment_id_merchant_id(&payment_id, merchant_id)
.await
@@ -80,6 +89,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
payment_attempt.payment_method = payment_method_type.or(payment_attempt.payment_method);
payment_attempt.payment_method = payment_method_type.or(payment_attempt.payment_method);
+ payment_attempt.browser_info = browser_info;
currency = payment_attempt.currency.get_required_value("currency")?;
amount = payment_attempt.amount;
@@ -163,6 +173,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
F: 'b + Send,
{
let payment_method = payment_data.payment_attempt.payment_method;
+ let browser_info = payment_data.payment_attempt.browser_info.clone();
let (intent_status, attempt_status) = match payment_data.payment_attempt.authentication_type
{
@@ -182,6 +193,7 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
storage::PaymentAttemptUpdate::ConfirmUpdate {
status: attempt_status,
payment_method,
+ browser_info,
},
)
.await
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index e7528b3a99c..ef97834dbba 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -87,6 +87,7 @@ pub enum PaymentAttemptUpdate {
ConfirmUpdate {
status: enums::AttemptStatus,
payment_method: Option<enums::PaymentMethodType>,
+ browser_info: Option<serde_json::Value>,
},
VoidUpdate {
status: enums::AttemptStatus,
@@ -124,6 +125,7 @@ pub(super) struct PaymentAttemptUpdateInternal {
modified_at: Option<PrimitiveDateTime>,
redirect: Option<bool>,
mandate_id: Option<String>,
+ browser_info: Option<serde_json::Value>,
}
impl PaymentAttemptUpdate {
@@ -142,6 +144,7 @@ impl PaymentAttemptUpdate {
payment_method_id: pa_update
.payment_method_id
.unwrap_or(source.payment_method_id),
+ browser_info: pa_update.browser_info,
modified_at: common_utils::date_time::now(),
..source
}
@@ -178,10 +181,12 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
PaymentAttemptUpdate::ConfirmUpdate {
status,
payment_method,
+ browser_info,
} => Self {
status: Some(status),
payment_method,
modified_at: Some(common_utils::date_time::now()),
+ browser_info,
..Default::default()
},
PaymentAttemptUpdate::VoidUpdate {
|
fix
|
Update browser info on payment confirmation (#52)
|
b39369ced97de75d26ac99230d63d3c500123005
|
2023-09-18 09:53:24
|
Sanchith Hegde
|
chore(version): v1.40.1
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 90e71e3c320..3039a34693a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,18 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.40.1 (2023-09-18)
+
+### Refactors
+
+- **connector:** [Bluesnap] Enahnce 3ds Flow ([#2115](https://github.com/juspay/hyperswitch/pull/2115)) ([`272f5e4`](https://github.com/juspay/hyperswitch/commit/272f5e4c1f34710fe13b1ede1b938d2f0b76e251))
+- Set merchant_id as `MERCHANT_ID_NOT_FOUND` for traces and metrics if not found ([#2156](https://github.com/juspay/hyperswitch/pull/2156)) ([`d40fae8`](https://github.com/juspay/hyperswitch/commit/d40fae87feb509718059ab2d72539f37f26a8251))
+
+**Full Changelog:** [`v1.40.0...v1.40.1`](https://github.com/juspay/hyperswitch/compare/v1.40.0...v1.40.1)
+
+- - -
+
+
## 1.40.0 (2023-09-15)
### Features
|
chore
|
v1.40.1
|
840609af61ad1441ca95ebb7294196b35e7b875b
|
2024-09-12 22:48:12
|
Swangi Kumari
|
refactor(core): Update shipping_cost and order_tax_amount to net_amount of payment_attempt (#5844)
| false
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index b80319add88..bda5fab29c0 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -13030,7 +13030,7 @@
"net_amount": {
"type": "integer",
"format": "int64",
- "description": "The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount,\nIf no surcharge_details, net_amount = amount",
+ "description": "The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount,\nIf no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount",
"example": 6540
},
"amount_capturable": {
@@ -13502,6 +13502,66 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "order_tax_amount": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MinorUnit"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
+ "PaymentsDynamicTaxCalculationRequest": {
+ "type": "object",
+ "required": [
+ "shipping",
+ "client_secret",
+ "payment_method_type"
+ ],
+ "properties": {
+ "shipping": {
+ "$ref": "#/components/schemas/Address"
+ },
+ "client_secret": {
+ "type": "string",
+ "description": "Client Secret"
+ },
+ "payment_method_type": {
+ "$ref": "#/components/schemas/PaymentMethodType"
+ }
+ }
+ },
+ "PaymentsDynamicTaxCalculationResponse": {
+ "type": "object",
+ "required": [
+ "payment_id",
+ "net_amount"
+ ],
+ "properties": {
+ "payment_id": {
+ "type": "string",
+ "description": "The identifier for the payment"
+ },
+ "net_amount": {
+ "$ref": "#/components/schemas/MinorUnit"
+ },
+ "order_tax_amount": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MinorUnit"
+ }
+ ],
+ "nullable": true
+ },
+ "shipping_cost": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MinorUnit"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -14095,7 +14155,7 @@
"net_amount": {
"type": "integer",
"format": "int64",
- "description": "The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount,\nIf no surcharge_details, net_amount = amount",
+ "description": "The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount,\nIf no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount",
"example": 6540
},
"amount_capturable": {
@@ -14592,6 +14652,14 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "order_tax_amount": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MinorUnit"
+ }
+ ],
+ "nullable": true
}
}
},
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index 58d11fc49a9..9d6074fe16b 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -17028,7 +17028,7 @@
"net_amount": {
"type": "integer",
"format": "int64",
- "description": "The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount,\nIf no surcharge_details, net_amount = amount",
+ "description": "The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount,\nIf no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount",
"example": 6540
},
"amount_capturable": {
@@ -17500,6 +17500,14 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "order_tax_amount": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MinorUnit"
+ }
+ ],
+ "nullable": true
}
}
},
@@ -17523,6 +17531,38 @@
}
}
},
+ "PaymentsDynamicTaxCalculationResponse": {
+ "type": "object",
+ "required": [
+ "payment_id",
+ "net_amount"
+ ],
+ "properties": {
+ "payment_id": {
+ "type": "string",
+ "description": "The identifier for the payment"
+ },
+ "net_amount": {
+ "$ref": "#/components/schemas/MinorUnit"
+ },
+ "order_tax_amount": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MinorUnit"
+ }
+ ],
+ "nullable": true
+ },
+ "shipping_cost": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MinorUnit"
+ }
+ ],
+ "nullable": true
+ }
+ }
+ },
"PaymentsExternalAuthenticationRequest": {
"type": "object",
"required": [
@@ -18113,7 +18153,7 @@
"net_amount": {
"type": "integer",
"format": "int64",
- "description": "The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount,\nIf no surcharge_details, net_amount = amount",
+ "description": "The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount,\nIf no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount",
"example": 6540
},
"amount_capturable": {
@@ -18610,6 +18650,14 @@
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
+ },
+ "order_tax_amount": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/MinorUnit"
+ }
+ ],
+ "nullable": true
}
}
},
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index d09df597d84..abd795361bb 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -3719,8 +3719,8 @@ pub struct PaymentsResponse {
#[schema(value_type = i64, example = 6540)]
pub amount: MinorUnit,
- /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount,
- /// If no surcharge_details, net_amount = amount
+ /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount,
+ /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount
#[schema(value_type = i64, example = 6540)]
pub net_amount: MinorUnit,
@@ -4020,6 +4020,8 @@ pub struct PaymentsResponse {
example = "Custom_Order_id_123"
)]
pub merchant_order_reference_id: Option<String>,
+ /// order tax amount calculated by tax connectors
+ pub order_tax_amount: Option<MinorUnit>,
}
/// Fee information to be charged on the payment being collected
@@ -4608,8 +4610,15 @@ pub struct PaymentsDynamicTaxCalculationRequest {
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)]
pub struct PaymentsDynamicTaxCalculationResponse {
- /// net amount
+ /// The identifier for the payment
+ #[schema(value_type = String)]
+ pub payment_id: id_type::PaymentId,
+ /// net amount = amount + order_tax_amount + shipping_cost
pub net_amount: MinorUnit,
+ /// order tax amount calculated by tax connectors
+ pub order_tax_amount: Option<MinorUnit>,
+ /// shipping cost for the order
+ pub shipping_cost: Option<MinorUnit>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 4e57ec34208..152037d55fe 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -1,4 +1,4 @@
-use common_utils::{id_type, pii};
+use common_utils::{id_type, pii, types::MinorUnit};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -81,6 +81,8 @@ pub struct PaymentAttempt {
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(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))]
@@ -155,12 +157,27 @@ pub struct PaymentAttempt {
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>,
}
impl PaymentAttempt {
pub fn get_or_calculate_net_amount(&self) -> i64 {
+ let shipping_cost = self
+ .shipping_cost
+ .unwrap_or(MinorUnit::new(0))
+ .get_amount_as_i64();
+ let order_tax_amount = self
+ .order_tax_amount
+ .unwrap_or(MinorUnit::new(0))
+ .get_amount_as_i64();
+
self.net_amount.unwrap_or(
- self.amount + self.surcharge_amount.unwrap_or(0) + self.tax_amount.unwrap_or(0),
+ self.amount
+ + self.surcharge_amount.unwrap_or(0)
+ + self.tax_amount.unwrap_or(0)
+ + shipping_cost
+ + order_tax_amount,
)
}
}
@@ -240,12 +257,22 @@ 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>,
}
impl PaymentAttemptNew {
- /// returns amount + surcharge_amount + tax_amount
+ /// returns amount + surcharge_amount + tax_amount (surcharge) + shipping_cost + order_tax_amount
pub fn calculate_net_amount(&self) -> i64 {
- self.amount + self.surcharge_amount.unwrap_or(0) + self.tax_amount.unwrap_or(0)
+ let shipping_cost = self
+ .shipping_cost
+ .unwrap_or(MinorUnit::new(0))
+ .get_amount_as_i64();
+
+ self.amount
+ + self.surcharge_amount.unwrap_or(0)
+ + self.tax_amount.unwrap_or(0)
+ + shipping_cost
}
pub fn get_or_calculate_net_amount(&self) -> i64 {
@@ -326,6 +353,8 @@ pub enum PaymentAttemptUpdate {
client_source: Option<String>,
client_version: Option<String>,
customer_acceptance: Option<pii::SecretSerdeValue>,
+ shipping_cost: Option<MinorUnit>,
+ order_tax_amount: Option<MinorUnit>,
},
VoidUpdate {
status: storage_enums::AttemptStatus,
@@ -499,11 +528,23 @@ pub struct PaymentAttemptUpdateInternal {
client_version: Option<String>,
customer_acceptance: Option<pii::SecretSerdeValue>,
card_network: Option<String>,
+ shipping_cost: Option<MinorUnit>,
+ order_tax_amount: Option<MinorUnit>,
}
impl PaymentAttemptUpdateInternal {
pub fn populate_derived_fields(self, source: &PaymentAttempt) -> Self {
let mut update_internal = self;
+ let shipping_cost = update_internal
+ .shipping_cost
+ .or(source.shipping_cost)
+ .unwrap_or(MinorUnit::new(0))
+ .get_amount_as_i64();
+ let order_tax_amount = update_internal
+ .order_tax_amount
+ .or(source.order_tax_amount)
+ .unwrap_or(MinorUnit::new(0))
+ .get_amount_as_i64();
update_internal.net_amount = Some(
update_internal.amount.unwrap_or(source.amount)
+ update_internal
@@ -513,7 +554,9 @@ impl PaymentAttemptUpdateInternal {
+ update_internal
.tax_amount
.or(source.tax_amount)
- .unwrap_or(0),
+ .unwrap_or(0)
+ + shipping_cost
+ + order_tax_amount,
);
update_internal.card_network = update_internal
.payment_method_data
@@ -578,6 +621,8 @@ impl PaymentAttemptUpdate {
client_version,
customer_acceptance,
card_network,
+ shipping_cost,
+ order_tax_amount,
} = PaymentAttemptUpdateInternal::from(self).populate_derived_fields(&source);
PaymentAttempt {
amount: amount.unwrap_or(source.amount),
@@ -631,6 +676,8 @@ impl PaymentAttemptUpdate {
client_version: client_version.or(source.client_version),
customer_acceptance: customer_acceptance.or(source.customer_acceptance),
card_network: card_network.or(source.card_network),
+ shipping_cost: shipping_cost.or(source.shipping_cost),
+ order_tax_amount: order_tax_amount.or(source.order_tax_amount),
..source
}
}
@@ -707,6 +754,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::AuthenticationTypeUpdate {
authentication_type,
@@ -759,6 +808,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::ConfirmUpdate {
amount,
@@ -791,6 +842,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_source,
client_version,
customer_acceptance,
+ shipping_cost,
+ order_tax_amount,
} => Self {
amount: Some(amount),
currency: Some(currency),
@@ -839,6 +892,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
unified_message: None,
charge_id: None,
card_network: None,
+ shipping_cost,
+ order_tax_amount,
},
PaymentAttemptUpdate::VoidUpdate {
status,
@@ -892,6 +947,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::RejectUpdate {
status,
@@ -946,6 +1003,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::BlocklistUpdate {
status,
@@ -1000,6 +1059,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::PaymentMethodDetailsUpdate {
payment_method_id,
@@ -1052,6 +1113,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::ResponseUpdate {
status,
@@ -1122,6 +1185,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::ErrorUpdate {
connector,
@@ -1184,6 +1249,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::StatusUpdate { status, updated_by } => Self {
status: Some(status),
@@ -1233,6 +1300,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::UpdateTrackers {
payment_token,
@@ -1291,6 +1360,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::UnresolvedResponseUpdate {
status,
@@ -1350,6 +1421,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::PreprocessingUpdate {
status,
@@ -1407,6 +1480,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::CaptureUpdate {
multiple_capture_count,
@@ -1460,6 +1535,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::AmountToCaptureUpdate {
status,
@@ -1513,6 +1590,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::ConnectorResponse {
authentication_data,
@@ -1569,6 +1648,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {
amount,
@@ -1621,6 +1702,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::AuthenticationUpdate {
status,
@@ -1676,6 +1759,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
PaymentAttemptUpdate::ManualUpdate {
status,
@@ -1734,6 +1819,8 @@ impl From<PaymentAttemptUpdate> for PaymentAttemptUpdateInternal {
client_version: None,
customer_acceptance: None,
card_network: None,
+ shipping_cost: None,
+ order_tax_amount: None,
},
}
}
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 8e6c72eb5ba..6e8918f02a4 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -840,6 +840,8 @@ diesel::table! {
organization_id -> Varchar,
#[max_length = 32]
card_network -> Nullable<Varchar>,
+ shipping_cost -> Nullable<Int8>,
+ order_tax_amount -> Nullable<Int8>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 2deaa3d4ee4..95550068f04 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -820,6 +820,8 @@ diesel::table! {
organization_id -> Varchar,
#[max_length = 32]
card_network -> Nullable<Varchar>,
+ shipping_cost -> Nullable<Int8>,
+ order_tax_amount -> Nullable<Int8>,
}
}
diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs
index 2b1359968fd..f4c8cf30fab 100644
--- a/crates/diesel_models/src/user/sample_data.rs
+++ b/crates/diesel_models/src/user/sample_data.rs
@@ -2,6 +2,7 @@ use common_enums::{
AttemptStatus, AuthenticationType, CaptureMethod, Currency, PaymentExperience, PaymentMethod,
PaymentMethodType,
};
+use common_utils::types::MinorUnit;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -82,6 +83,8 @@ pub struct PaymentAttemptBatchNew {
pub customer_acceptance: Option<common_utils::pii::SecretSerdeValue>,
pub profile_id: common_utils::id_type::ProfileId,
pub organization_id: common_utils::id_type::OrganizationId,
+ pub shipping_cost: Option<MinorUnit>,
+ pub order_tax_amount: Option<MinorUnit>,
}
#[allow(dead_code)]
@@ -157,6 +160,8 @@ impl PaymentAttemptBatchNew {
customer_acceptance: self.customer_acceptance,
profile_id: self.profile_id,
organization_id: self.organization_id,
+ shipping_cost: self.shipping_cost,
+ order_tax_amount: self.order_tax_amount,
}
}
}
diff --git a/crates/hyperswitch_connectors/src/connectors/taxjar.rs b/crates/hyperswitch_connectors/src/connectors/taxjar.rs
index ef8631004a6..009a9cb0c97 100644
--- a/crates/hyperswitch_connectors/src/connectors/taxjar.rs
+++ b/crates/hyperswitch_connectors/src/connectors/taxjar.rs
@@ -65,7 +65,7 @@ impl api::Refund for Taxjar {}
impl api::RefundExecute for Taxjar {}
impl api::RefundSync for Taxjar {}
impl api::PaymentToken for Taxjar {}
-impl api::PaymentTaxCalculation for Taxjar {}
+impl api::TaxCalculation for Taxjar {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Taxjar
diff --git a/crates/hyperswitch_connectors/src/default_implementations.rs b/crates/hyperswitch_connectors/src/default_implementations.rs
index ce1140394b5..1f50150c08d 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -66,8 +66,8 @@ use hyperswitch_interfaces::{
payments::{
ConnectorCustomer, PaymentApprove, PaymentAuthorizeSessionToken,
PaymentIncrementalAuthorization, PaymentReject, PaymentSessionUpdate,
- PaymentTaxCalculation, PaymentsCompleteAuthorize, PaymentsPostProcessing,
- PaymentsPreProcessing,
+ PaymentsCompleteAuthorize, PaymentsPostProcessing, PaymentsPreProcessing,
+ TaxCalculation,
},
ConnectorIntegration, ConnectorMandateRevoke, ConnectorRedirectResponse,
},
@@ -109,7 +109,7 @@ default_imp_for_authorize_session_token!(
macro_rules! default_imp_for_calculate_tax {
($($path:ident::$connector:ident),*) => {
- $( impl PaymentTaxCalculation for $path::$connector {}
+ $( impl TaxCalculation for $path::$connector {}
impl
ConnectorIntegration<
CalculateTax,
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index 95c7ffec007..82ac725de3c 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -75,8 +75,8 @@ use hyperswitch_interfaces::{
ConnectorCustomerV2, MandateSetupV2, PaymentApproveV2, PaymentAuthorizeSessionTokenV2,
PaymentAuthorizeV2, PaymentCaptureV2, PaymentIncrementalAuthorizationV2,
PaymentRejectV2, PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2,
- PaymentTaxCalculationV2, PaymentTokenV2, PaymentV2, PaymentVoidV2,
- PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2,
+ PaymentTokenV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2,
+ PaymentsPostProcessingV2, PaymentsPreProcessingV2, TaxCalculationV2,
},
refunds_v2::{RefundExecuteV2, RefundSyncV2, RefundV2},
ConnectorAccessTokenV2, ConnectorMandateRevokeV2, ConnectorVerifyWebhookSourceV2,
@@ -105,7 +105,7 @@ macro_rules! default_imp_for_new_connector_integration_payment {
impl ConnectorCustomerV2 for $path::$connector{}
impl PaymentsPreProcessingV2 for $path::$connector{}
impl PaymentsPostProcessingV2 for $path::$connector{}
- impl PaymentTaxCalculationV2 for $path::$connector{}
+ impl TaxCalculationV2 for $path::$connector{}
impl PaymentSessionUpdateV2 for $path::$connector{}
impl
ConnectorIntegrationV2<Authorize,PaymentFlowData, PaymentsAuthorizeData, PaymentsResponseData>
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 427ca967b9d..1aaf5218af7 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -184,6 +184,8 @@ pub struct PaymentAttempt {
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub profile_id: id_type::ProfileId,
pub organization_id: id_type::OrganizationId,
+ pub shipping_cost: Option<MinorUnit>,
+ pub order_tax_amount: Option<MinorUnit>,
}
impl PaymentAttempt {
@@ -276,6 +278,8 @@ pub struct PaymentAttemptNew {
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub profile_id: id_type::ProfileId,
pub organization_id: id_type::OrganizationId,
+ pub shipping_cost: Option<MinorUnit>,
+ pub order_tax_amount: Option<MinorUnit>,
}
impl PaymentAttemptNew {
@@ -284,6 +288,8 @@ impl PaymentAttemptNew {
self.amount
+ self.surcharge_amount.unwrap_or_default()
+ self.tax_amount.unwrap_or_default()
+ + self.shipping_cost.unwrap_or_default()
+ + self.order_tax_amount.unwrap_or_default()
}
pub fn populate_derived_fields(self) -> Self {
@@ -359,6 +365,8 @@ pub enum PaymentAttemptUpdate {
client_source: Option<String>,
client_version: Option<String>,
customer_acceptance: Option<pii::SecretSerdeValue>,
+ shipping_cost: Option<MinorUnit>,
+ order_tax_amount: Option<MinorUnit>,
},
RejectUpdate {
status: storage_enums::AttemptStatus,
diff --git a/crates/hyperswitch_interfaces/src/api/payments.rs b/crates/hyperswitch_interfaces/src/api/payments.rs
index 530dd516454..43409680dc5 100644
--- a/crates/hyperswitch_interfaces/src/api/payments.rs
+++ b/crates/hyperswitch_interfaces/src/api/payments.rs
@@ -112,8 +112,8 @@ pub trait PaymentIncrementalAuthorization:
{
}
-/// trait PaymentTaxCalculation
-pub trait PaymentTaxCalculation:
+/// trait TaxCalculation
+pub trait TaxCalculation:
api::ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>
{
}
diff --git a/crates/hyperswitch_interfaces/src/api/payments_v2.rs b/crates/hyperswitch_interfaces/src/api/payments_v2.rs
index 29bc6eee061..cc5fd01f9f8 100644
--- a/crates/hyperswitch_interfaces/src/api/payments_v2.rs
+++ b/crates/hyperswitch_interfaces/src/api/payments_v2.rs
@@ -90,8 +90,8 @@ pub trait PaymentIncrementalAuthorizationV2:
{
}
-///trait PaymentTaxCalculationV2
-pub trait PaymentTaxCalculationV2:
+///trait TaxCalculationV2
+pub trait TaxCalculationV2:
ConnectorIntegrationV2<
CalculateTax,
PaymentFlowData,
@@ -186,7 +186,7 @@ pub trait PaymentV2:
+ PaymentsPostProcessingV2
+ ConnectorCustomerV2
+ PaymentIncrementalAuthorizationV2
- + PaymentTaxCalculationV2
+ + TaxCalculationV2
+ PaymentSessionUpdateV2
{
}
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 93975cc57c5..3b63b7ac20f 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -605,6 +605,7 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::additional_info::UpiAdditionalData,
api_models::payments::additional_info::UpiCollectAdditionalData,
api_models::payments::PaymentsDynamicTaxCalculationRequest,
+ api_models::payments::PaymentsDynamicTaxCalculationResponse,
)),
modifiers(&SecurityAddon)
)]
diff --git a/crates/openapi/src/openapi_v2.rs b/crates/openapi/src/openapi_v2.rs
index dd258843319..5393e8d6fae 100644
--- a/crates/openapi/src/openapi_v2.rs
+++ b/crates/openapi/src/openapi_v2.rs
@@ -520,6 +520,8 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::payments::additional_info::GivexGiftCardAdditionalData,
api_models::payments::additional_info::UpiAdditionalData,
api_models::payments::additional_info::UpiCollectAdditionalData,
+ api_models::payments::PaymentsDynamicTaxCalculationRequest,
+ api_models::payments::PaymentsDynamicTaxCalculationResponse,
)),
modifiers(&SecurityAddon)
)]
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index c0cb446b38f..996224d7bea 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1457,7 +1457,10 @@ impl<'a> ConnectorAuthTypeAndMetadataValidation<'a> {
stax::transformers::StaxAuthType::try_from(self.auth_type)?;
Ok(())
}
- api_enums::Connector::Taxjar => Ok(()),
+ api_enums::Connector::Taxjar => {
+ taxjar::transformers::TaxjarAuthType::try_from(self.auth_type)?;
+ Ok(())
+ }
api_enums::Connector::Stripe => {
stripe::transformers::StripeAuthType::try_from(self.auth_type)?;
Ok(())
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 390ea8e017e..bf52bad4ed3 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -265,7 +265,6 @@ where
.payments_dynamic_tax_calculation(
state,
&mut payment_data,
- &mut should_continue_transaction,
&connector_details,
&business_profile,
&key_store,
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 a1a3cecd8fc..19d67733d3b 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -42,7 +42,7 @@ mod dummy_connector_default_impl {
impl<const T: u8> api::PaymentsPostProcessingV2 for connector::DummyConnector<T> {}
- impl<const T: u8> api::PaymentTaxCalculationV2 for connector::DummyConnector<T> {}
+ impl<const T: u8> api::TaxCalculationV2 for connector::DummyConnector<T> {}
impl<const T: u8> api::PaymentSessionUpdateV2 for connector::DummyConnector<T> {}
@@ -579,7 +579,7 @@ macro_rules! default_imp_for_new_connector_integration_payment {
impl api::ConnectorCustomerV2 for $path::$connector{}
impl api::PaymentsPreProcessingV2 for $path::$connector{}
impl api::PaymentsPostProcessingV2 for $path::$connector{}
- impl api::PaymentTaxCalculationV2 for $path::$connector{}
+ impl api::TaxCalculationV2 for $path::$connector{}
impl api::PaymentSessionUpdateV2 for $path::$connector{}
impl
services::ConnectorIntegrationV2<api::Authorize,types::PaymentFlowData, types::PaymentsAuthorizeData, types::PaymentsResponseData>
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index 6a1d88a583e..1dec8911d31 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -7,8 +7,8 @@ pub mod incremental_authorization_flow;
pub mod psync_flow;
pub mod reject_flow;
pub mod session_flow;
+pub mod session_update_flow;
pub mod setup_mandate_flow;
-pub mod tax_calculation_flow;
use async_trait::async_trait;
@@ -3088,7 +3088,7 @@ default_imp_for_authorize_session_token!(
macro_rules! default_imp_for_calculate_tax {
($($path:ident::$connector:ident),*) => {
- $( impl api::PaymentTaxCalculation for $path::$connector {}
+ $( impl api::TaxCalculation for $path::$connector {}
impl
services::ConnectorIntegration<
api::CalculateTax,
@@ -3100,7 +3100,7 @@ macro_rules! default_imp_for_calculate_tax {
};
}
#[cfg(feature = "dummy_connector")]
-impl<const T: u8> api::PaymentTaxCalculation for connector::DummyConnector<T> {}
+impl<const T: u8> api::TaxCalculation for connector::DummyConnector<T> {}
#[cfg(feature = "dummy_connector")]
impl<const T: u8>
services::ConnectorIntegration<
diff --git a/crates/router/src/core/payments/flows/tax_calculation_flow.rs b/crates/router/src/core/payments/flows/session_update_flow.rs
similarity index 100%
rename from crates/router/src/core/payments/flows/tax_calculation_flow.rs
rename to crates/router/src/core/payments/flows/session_update_flow.rs
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index f8a58158d01..7636801663a 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -3679,6 +3679,8 @@ impl AttemptType {
customer_acceptance: old_payment_attempt.customer_acceptance,
organization_id: old_payment_attempt.organization_id,
profile_id: old_payment_attempt.profile_id,
+ shipping_cost: old_payment_attempt.shipping_cost,
+ order_tax_amount: None,
}
}
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index f002310ab87..841be780e68 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -188,7 +188,6 @@ pub trait Domain<F: Clone, R, D>: Send + Sync {
&'a self,
_state: &SessionState,
_payment_data: &mut D,
- _should_continue_confirm_transaction: &mut bool,
_connector_call_type: &ConnectorCallType,
_business_profile: &domain::BusinessProfile,
_key_store: &domain::MerchantKeyStore,
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index c4abe7ff869..95e254f3411 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -1279,6 +1279,31 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
None => (None, None, None),
};
+ let shipping_cost = payment_data.payment_intent.shipping_cost;
+
+ let pmt_order_tax_amount =
+ payment_data
+ .payment_intent
+ .tax_details
+ .clone()
+ .and_then(|tax| {
+ if tax.payment_method_type.clone().map(|a| a.pmt)
+ == payment_data.payment_attempt.payment_method_type
+ {
+ tax.payment_method_type.map(|a| a.order_tax_amount)
+ } else {
+ None
+ }
+ });
+
+ let order_tax_amount = pmt_order_tax_amount.or_else(|| {
+ payment_data
+ .payment_intent
+ .tax_details
+ .clone()
+ .and_then(|tax| tax.default.map(|a| a.order_tax_amount))
+ });
+
let payment_attempt_fut = tokio::spawn(
async move {
m_db.update_payment_attempt_with_attempt_id(
@@ -1314,6 +1339,8 @@ impl<F: Clone> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for Paymen
client_source,
client_version,
customer_acceptance: payment_data.payment_attempt.customer_acceptance,
+ shipping_cost,
+ order_tax_amount,
},
storage_scheme,
)
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index 88489f4a03b..d66565e84e5 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -580,13 +580,17 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest, PaymentData<F>> for Paymen
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
- _should_continue_confirm_transaction: &mut bool,
_connector_call_type: &ConnectorCallType,
business_profile: &domain::BusinessProfile,
key_store: &domain::MerchantKeyStore,
merchant_account: &domain::MerchantAccount,
) -> CustomResult<(), errors::ApiErrorResponse> {
- if business_profile.is_tax_connector_enabled {
+ let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
+ let skip_external_tax_calculation = payment_data
+ .payment_intent
+ .skip_external_tax_calculation
+ .unwrap_or(false);
+ if is_tax_connector_enabled && !skip_external_tax_calculation {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &state.into();
@@ -1151,6 +1155,8 @@ impl PaymentCreate {
.map(Secret::new),
organization_id: organization_id.clone(),
profile_id,
+ shipping_cost: request.shipping_cost,
+ order_tax_amount: None,
},
additional_pm_data,
))
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index 3b243e86132..484bec14f48 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -521,13 +521,17 @@ impl<F: Clone + Send> Domain<F, api::PaymentsRequest, PaymentData<F>> for Paymen
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
- _should_continue_confirm_transaction: &mut bool,
_connector_call_type: &ConnectorCallType,
business_profile: &domain::BusinessProfile,
key_store: &domain::MerchantKeyStore,
merchant_account: &domain::MerchantAccount,
) -> CustomResult<(), errors::ApiErrorResponse> {
- if business_profile.is_tax_connector_enabled {
+ let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
+ let skip_external_tax_calculation = payment_data
+ .payment_intent
+ .skip_external_tax_calculation
+ .unwrap_or(false);
+ if is_tax_connector_enabled && !skip_external_tax_calculation {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &state.into();
diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rs
index 70514dc7786..1df83612440 100644
--- a/crates/router/src/core/payments/operations/tax_calculation.rs
+++ b/crates/router/src/core/payments/operations/tax_calculation.rs
@@ -215,14 +215,17 @@ impl<F: Clone + Send> Domain<F, api::PaymentsDynamicTaxCalculationRequest, Payme
&'a self,
state: &SessionState,
payment_data: &mut PaymentData<F>,
- should_continue_confirm_transaction: &mut bool,
_connector_call_type: &ConnectorCallType,
business_profile: &domain::BusinessProfile,
key_store: &domain::MerchantKeyStore,
merchant_account: &domain::MerchantAccount,
) -> errors::CustomResult<(), errors::ApiErrorResponse> {
- if business_profile.is_tax_connector_enabled {
- *should_continue_confirm_transaction = false;
+ let is_tax_connector_enabled = business_profile.get_is_tax_connector_enabled();
+ let skip_external_tax_calculation = payment_data
+ .payment_intent
+ .skip_external_tax_calculation
+ .unwrap_or(false);
+ if is_tax_connector_enabled && !skip_external_tax_calculation {
let db = state.store.as_ref();
let key_manager_state: &KeyManagerState = &state.into();
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 57aba020e89..a96fb08e23b 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -571,6 +571,8 @@ pub fn make_new_payment_attempt(
customer_acceptance: Default::default(),
profile_id: old_payment_attempt.profile_id,
organization_id: old_payment_attempt.organization_id,
+ shipping_cost: old_payment_attempt.shipping_cost,
+ order_tax_amount: None,
}
}
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index f0039eb49c1..36961f33753 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -487,19 +487,29 @@ where
) -> RouterResponse<Self> {
let mut amount = payment_data.get_payment_intent().amount;
let shipping_cost = payment_data.get_payment_intent().shipping_cost;
+ if let Some(shipping_cost) = shipping_cost {
+ amount = amount + shipping_cost;
+ }
let order_tax_amount = payment_data
.get_payment_intent()
.tax_details
.clone()
- .and_then(|tax| tax.payment_method_type.map(|a| a.order_tax_amount));
- if let Some(shipping_cost) = shipping_cost {
- amount = amount + shipping_cost;
- }
- if let Some(order_tax_amount) = order_tax_amount {
- amount = amount + order_tax_amount;
+ .and_then(|tax| {
+ tax.payment_method_type
+ .map(|a| a.order_tax_amount)
+ .or_else(|| tax.default.map(|a| a.order_tax_amount))
+ });
+ if let Some(tax_amount) = order_tax_amount {
+ amount = amount + tax_amount;
}
+
Ok(services::ApplicationResponse::JsonWithHeaders((
- Self { net_amount: amount },
+ Self {
+ net_amount: amount,
+ payment_id: payment_data.get_payment_attempt().payment_id.clone(),
+ order_tax_amount,
+ shipping_cost,
+ },
vec![],
)))
}
@@ -1029,6 +1039,21 @@ where
update_mandate_id: d.update_mandate_id.clone(),
});
+ let order_tax_amount = payment_data
+ .get_payment_attempt()
+ .order_tax_amount
+ .or_else(|| {
+ payment_data
+ .get_payment_intent()
+ .tax_details
+ .clone()
+ .and_then(|tax| {
+ tax.payment_method_type
+ .map(|a| a.order_tax_amount)
+ .or_else(|| tax.default.map(|a| a.order_tax_amount))
+ })
+ });
+
let payments_response = api::PaymentsResponse {
payment_id: payment_intent.payment_id,
merchant_id: payment_intent.merchant_id,
@@ -1126,6 +1151,7 @@ where
charges: charges_response,
frm_metadata: payment_intent.frm_metadata,
merchant_order_reference_id: payment_intent.merchant_order_reference_id,
+ order_tax_amount,
};
services::ApplicationResponse::JsonWithHeaders((payments_response, headers))
@@ -1377,6 +1403,7 @@ impl ForeignFrom<(storage::PaymentIntent, storage::PaymentAttempt)> for api::Pay
updated: None,
charges: None,
frm_metadata: None,
+ order_tax_amount: None,
}
}
}
diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs
index af2fffa5091..335110248ab 100644
--- a/crates/router/src/db/address.rs
+++ b/crates/router/src/db/address.rs
@@ -375,9 +375,12 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme =
- decide_storage_scheme::<_, storage_types::Address>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Address>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
let address = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
@@ -458,11 +461,11 @@ mod storage {
payment_id: &payment_id,
};
let field = format!("add_{}", address.address_id);
- let storage_scheme = decide_storage_scheme::<_, storage_types::Address>(
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Address>(
self,
storage_scheme,
Op::Update(key.clone(), &field, Some(address.updated_by.as_str())),
- )
+ ))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
@@ -539,11 +542,11 @@ mod storage {
.await
.change_context(errors::StorageError::EncryptionError)?;
let merchant_id = address_new.merchant_id.clone();
- let storage_scheme = decide_storage_scheme::<_, storage_types::Address>(
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Address>(
self,
storage_scheme,
Op::Insert,
- )
+ ))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs
index 01bfc7ce0ad..9cd044f69eb 100644
--- a/crates/router/src/db/customers.rs
+++ b/crates/router/src/db/customers.rs
@@ -202,9 +202,12 @@ mod storage {
.await
.map_err(|err| report!(errors::StorageError::from(err)))
};
- let storage_scheme =
- decide_storage_scheme::<_, diesel_models::Customer>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
let maybe_customer = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
@@ -273,9 +276,12 @@ mod storage {
.await
.map_err(|err| report!(errors::StorageError::from(err)))
};
- let storage_scheme =
- decide_storage_scheme::<_, diesel_models::Customer>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
let maybe_customer = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
@@ -338,9 +344,12 @@ mod storage {
.await
.map_err(|err| report!(errors::StorageError::from(err)))
};
- let storage_scheme =
- decide_storage_scheme::<_, diesel_models::Customer>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
let maybe_customer = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
@@ -419,11 +428,11 @@ mod storage {
customer_id: &customer_id,
};
let field = format!("cust_{}", customer_id.get_string_repr());
- let storage_scheme = decide_storage_scheme::<_, diesel_models::Customer>(
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(
self,
storage_scheme,
Op::Update(key.clone(), &field, customer.updated_by.as_deref()),
- )
+ ))
.await;
let updated_object = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
@@ -491,9 +500,12 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme =
- decide_storage_scheme::<_, diesel_models::Customer>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
let customer = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
@@ -556,9 +568,12 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme =
- decide_storage_scheme::<_, diesel_models::Customer>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
let customer = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
@@ -653,11 +668,11 @@ mod storage {
.construct_new()
.await
.change_context(errors::StorageError::EncryptionError)?;
- let storage_scheme = decide_storage_scheme::<_, diesel_models::Customer>(
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(
self,
storage_scheme,
Op::Insert,
- )
+ ))
.await;
new_customer.update_storage_scheme(storage_scheme);
let create_customer = match storage_scheme {
@@ -729,11 +744,11 @@ mod storage {
.construct_new()
.await
.change_context(errors::StorageError::EncryptionError)?;
- let storage_scheme = decide_storage_scheme::<_, diesel_models::Customer>(
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(
self,
storage_scheme,
Op::Insert,
- )
+ ))
.await;
new_customer.update_storage_scheme(storage_scheme);
let create_customer = match storage_scheme {
@@ -826,9 +841,12 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme =
- decide_storage_scheme::<_, diesel_models::Customer>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
let customer = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
@@ -895,11 +913,11 @@ mod storage {
};
let key = PartitionKey::GlobalId { id: &id };
let field = format!("cust_{}", id);
- let storage_scheme = decide_storage_scheme::<_, diesel_models::Customer>(
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Customer>(
self,
storage_scheme,
Op::Update(key.clone(), &field, customer.updated_by.as_deref()),
- )
+ ))
.await;
let updated_object = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs
index f59ac2a80b5..24356494471 100644
--- a/crates/router/src/db/mandate.rs
+++ b/crates/router/src/db/mandate.rs
@@ -97,9 +97,12 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme =
- decide_storage_scheme::<_, diesel_models::Mandate>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
@@ -143,9 +146,12 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme =
- decide_storage_scheme::<_, diesel_models::Mandate>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
@@ -220,11 +226,11 @@ mod storage {
mandate_id,
};
let field = format!("mandate_{}", mandate_id);
- let storage_scheme = decide_storage_scheme::<_, diesel_models::Mandate>(
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>(
self,
storage_scheme,
Op::Update(key.clone(), &field, mandate.updated_by.as_deref()),
- )
+ ))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
@@ -312,11 +318,11 @@ mod storage {
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
- let storage_scheme = decide_storage_scheme::<_, diesel_models::Mandate>(
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, diesel_models::Mandate>(
self,
storage_scheme,
Op::Insert,
- )
+ ))
.await;
mandate.update_storage_scheme(storage_scheme);
match storage_scheme {
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index 695ed68b796..0541491ab98 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -173,12 +173,13 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme = decide_storage_scheme::<_, storage_types::PaymentMethod>(
- self,
- storage_scheme,
- Op::Find,
- )
- .await;
+ let storage_scheme =
+ Box::pin(decide_storage_scheme::<_, storage_types::PaymentMethod>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
let get_pm = || async {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
@@ -239,12 +240,13 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme = decide_storage_scheme::<_, storage_types::PaymentMethod>(
- self,
- storage_scheme,
- Op::Find,
- )
- .await;
+ let storage_scheme =
+ Box::pin(decide_storage_scheme::<_, storage_types::PaymentMethod>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
let get_pm = || async {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
@@ -308,12 +310,13 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme = decide_storage_scheme::<_, storage_types::PaymentMethod>(
- self,
- storage_scheme,
- Op::Find,
- )
- .await;
+ let storage_scheme =
+ Box::pin(decide_storage_scheme::<_, storage_types::PaymentMethod>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
let get_pm = || async {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
@@ -390,12 +393,13 @@ mod storage {
payment_method: domain::PaymentMethod,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::PaymentMethod, errors::StorageError> {
- let storage_scheme = decide_storage_scheme::<_, storage_types::PaymentMethod>(
- self,
- storage_scheme,
- Op::Insert,
- )
- .await;
+ let storage_scheme =
+ Box::pin(decide_storage_scheme::<_, storage_types::PaymentMethod>(
+ self,
+ storage_scheme,
+ Op::Insert,
+ ))
+ .await;
let mut payment_method_new = payment_method
.construct_new()
@@ -507,12 +511,13 @@ mod storage {
customer_id: &customer_id,
};
let field = format!("payment_method_id_{}", payment_method.get_id());
- let storage_scheme = decide_storage_scheme::<_, storage_types::PaymentMethod>(
- self,
- storage_scheme,
- Op::Update(key.clone(), &field, payment_method.updated_by.as_deref()),
- )
- .await;
+ let storage_scheme =
+ Box::pin(decide_storage_scheme::<_, storage_types::PaymentMethod>(
+ self,
+ storage_scheme,
+ Op::Update(key.clone(), &field, payment_method.updated_by.as_deref()),
+ ))
+ .await;
let pm = match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
let conn = connection::pg_connection_write(self).await?;
@@ -593,12 +598,13 @@ mod storage {
customer_id: &customer_id,
};
let field = format!("payment_method_id_{}", payment_method.get_id());
- let storage_scheme = decide_storage_scheme::<_, storage_types::PaymentMethod>(
- self,
- storage_scheme,
- Op::Update(key.clone(), &field, payment_method.updated_by.as_deref()),
- )
- .await;
+ let storage_scheme =
+ Box::pin(decide_storage_scheme::<_, storage_types::PaymentMethod>(
+ self,
+ storage_scheme,
+ Op::Update(key.clone(), &field, payment_method.updated_by.as_deref()),
+ ))
+ .await;
let pm = match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
let conn = connection::pg_connection_write(self).await?;
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index e8cebc43aee..808f82b00a4 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -333,9 +333,12 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme =
- decide_storage_scheme::<_, storage_types::Refund>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
@@ -375,9 +378,12 @@ mod storage {
new: storage_types::RefundNew,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<storage_types::Refund, errors::StorageError> {
- let storage_scheme =
- decide_storage_scheme::<_, storage_types::Refund>(self, storage_scheme, Op::Insert)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>(
+ self,
+ storage_scheme,
+ Op::Insert,
+ ))
+ .await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => {
let conn = connection::pg_connection_write(self).await?;
@@ -525,9 +531,12 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme =
- decide_storage_scheme::<_, storage_types::Refund>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
@@ -578,11 +587,11 @@ mod storage {
payment_id: &payment_id,
};
let field = format!("pa_{}_ref_{}", &this.attempt_id, &this.refund_id);
- let storage_scheme = decide_storage_scheme::<_, storage_types::Refund>(
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>(
self,
storage_scheme,
Op::Update(key.clone(), &field, Some(&this.updated_by)),
- )
+ ))
.await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => {
@@ -639,9 +648,12 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme =
- decide_storage_scheme::<_, storage_types::Refund>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
@@ -692,9 +704,12 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme =
- decide_storage_scheme::<_, storage_types::Refund>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
@@ -745,9 +760,12 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme =
- decide_storage_scheme::<_, storage_types::Refund>(self, storage_scheme, Op::Find)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, storage_types::Refund>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
diff --git a/crates/router/src/db/reverse_lookup.rs b/crates/router/src/db/reverse_lookup.rs
index fcf38ca420d..d51ed5ed385 100644
--- a/crates/router/src/db/reverse_lookup.rs
+++ b/crates/router/src/db/reverse_lookup.rs
@@ -93,8 +93,12 @@ mod storage {
new: ReverseLookupNew,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
- let storage_scheme =
- decide_storage_scheme::<_, ReverseLookup>(self, storage_scheme, Op::Insert).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, ReverseLookup>(
+ self,
+ storage_scheme,
+ Op::Insert,
+ ))
+ .await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => {
let conn = connection::pg_connection_write(self).await?;
@@ -154,8 +158,12 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
};
- let storage_scheme =
- decide_storage_scheme::<_, ReverseLookup>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, ReverseLookup>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 18f62764957..ca86003f4b4 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -112,7 +112,7 @@ pub trait Connector:
+ ConnectorMandateRevokeV2
+ ExternalAuthentication
+ ExternalAuthenticationV2
- + PaymentTaxCalculation
+ + TaxCalculation
{
}
@@ -141,7 +141,7 @@ impl<
+ ConnectorMandateRevokeV2
+ ExternalAuthentication
+ ExternalAuthenticationV2
- + PaymentTaxCalculation,
+ + TaxCalculation,
> Connector for T
{
}
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index bbdbb059071..449d1c725c5 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -24,16 +24,16 @@ pub use hyperswitch_domain_models::router_flow_types::payments::{
pub use hyperswitch_interfaces::api::payments::{
ConnectorCustomer, MandateSetup, Payment, PaymentApprove, PaymentAuthorize,
PaymentAuthorizeSessionToken, PaymentCapture, PaymentIncrementalAuthorization, PaymentReject,
- PaymentSession, PaymentSessionUpdate, PaymentSync, PaymentTaxCalculation, PaymentToken,
- PaymentVoid, PaymentsCompleteAuthorize, PaymentsPostProcessing, PaymentsPreProcessing,
+ 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, PaymentTaxCalculationV2,
- PaymentTokenV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2,
- PaymentsPostProcessingV2, PaymentsPreProcessingV2,
+ 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 cfcabadee5d..59f132c0154 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, PaymentTaxCalculationV2,
- PaymentTokenV2, PaymentV2, PaymentVoidV2, PaymentsCompleteAuthorizeV2,
- PaymentsPostProcessingV2, PaymentsPreProcessingV2,
+ PaymentSessionUpdateV2, PaymentSessionV2, PaymentSyncV2, PaymentTokenV2, PaymentV2,
+ PaymentVoidV2, PaymentsCompleteAuthorizeV2, PaymentsPostProcessingV2, PaymentsPreProcessingV2,
+ TaxCalculationV2,
};
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index 950a666dd61..782d5ae76a0 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -184,6 +184,8 @@ mod tests {
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
+ shipping_cost: Default::default(),
+ order_tax_amount: Default::default(),
};
let store = state
@@ -270,6 +272,8 @@ mod tests {
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
+ shipping_cost: Default::default(),
+ order_tax_amount: Default::default(),
};
let store = state
.stores
@@ -369,6 +373,8 @@ mod tests {
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
+ shipping_cost: Default::default(),
+ order_tax_amount: Default::default(),
};
let store = state
.stores
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index 32728fd8fcc..40dd3dad93a 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -330,6 +330,8 @@ pub async fn generate_sample_data(
customer_acceptance: None,
profile_id: profile_id.clone(),
organization_id: org_id.clone(),
+ shipping_cost: None,
+ order_tax_amount: None,
};
let refund = if refunds_count < number_of_refunds && !is_failed_payment {
diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs
index 60c0fed7bb3..f5d5e3d1aea 100644
--- a/crates/router/tests/payments.rs
+++ b/crates/router/tests/payments.rs
@@ -443,6 +443,7 @@ async fn payments_create_core() {
charges: None,
frm_metadata: None,
merchant_order_reference_id: None,
+ order_tax_amount: None,
};
let expected_response =
services::ApplicationResponse::JsonWithHeaders((expected_response, vec![]));
@@ -698,6 +699,7 @@ async fn payments_create_core_adyen_no_redirect() {
charges: None,
frm_metadata: None,
merchant_order_reference_id: None,
+ order_tax_amount: None,
},
vec![],
));
diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs
index c216f1e95e7..e2c86a9b911 100644
--- a/crates/router/tests/payments2.rs
+++ b/crates/router/tests/payments2.rs
@@ -203,6 +203,7 @@ async fn payments_create_core() {
charges: None,
frm_metadata: None,
merchant_order_reference_id: None,
+ order_tax_amount: None,
};
let expected_response =
services::ApplicationResponse::JsonWithHeaders((expected_response, vec![]));
@@ -466,6 +467,7 @@ async fn payments_create_core_adyen_no_redirect() {
charges: None,
frm_metadata: None,
merchant_order_reference_id: None,
+ order_tax_amount: None,
},
vec![],
));
diff --git a/crates/storage_impl/src/lookup.rs b/crates/storage_impl/src/lookup.rs
index 67b8635aba4..943ef1f36f7 100644
--- a/crates/storage_impl/src/lookup.rs
+++ b/crates/storage_impl/src/lookup.rs
@@ -71,8 +71,12 @@ impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> {
new: DieselReverseLookupNew,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<DieselReverseLookup, errors::StorageError> {
- let storage_scheme =
- decide_storage_scheme::<_, DieselReverseLookup>(self, storage_scheme, Op::Insert).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>(
+ self,
+ storage_scheme,
+ Op::Insert,
+ ))
+ .await;
match storage_scheme {
storage_enums::MerchantStorageScheme::PostgresOnly => {
self.router_store
@@ -126,8 +130,12 @@ impl<T: DatabaseStore> ReverseLookupInterface for KVRouterStore<T> {
.get_lookup_by_lookup_id(id, storage_scheme)
.await
};
- let storage_scheme =
- decide_storage_scheme::<_, DieselReverseLookup>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselReverseLookup>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
storage_enums::MerchantStorageScheme::PostgresOnly => database_call().await,
storage_enums::MerchantStorageScheme::RedisKv => {
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index 11205b94db5..6558c14ace3 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -161,6 +161,8 @@ impl PaymentAttemptInterface for MockDb {
customer_acceptance: payment_attempt.customer_acceptance,
organization_id: payment_attempt.organization_id,
profile_id: payment_attempt.profile_id,
+ shipping_cost: payment_attempt.shipping_cost,
+ order_tax_amount: payment_attempt.order_tax_amount,
};
payment_attempts.push(payment_attempt.clone());
Ok(payment_attempt)
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index 3cc04e8af5d..85fe2b22d3e 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -338,9 +338,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_attempt: PaymentAttemptNew,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
- let storage_scheme =
- decide_storage_scheme::<_, DieselPaymentAttempt>(self, storage_scheme, Op::Insert)
- .await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
+ self,
+ storage_scheme,
+ Op::Insert,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
@@ -423,6 +426,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
customer_acceptance: payment_attempt.customer_acceptance.clone(),
organization_id: payment_attempt.organization_id.clone(),
profile_id: payment_attempt.profile_id.clone(),
+ shipping_cost: payment_attempt.shipping_cost,
+ order_tax_amount: payment_attempt.order_tax_amount,
};
let field = format!("pa_{}", created_attempt.attempt_id);
@@ -487,11 +492,11 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_id: &this.payment_id,
};
let field = format!("pa_{}", this.attempt_id);
- let storage_scheme = decide_storage_scheme::<_, DieselPaymentAttempt>(
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
self,
storage_scheme,
Op::Update(key.clone(), &field, Some(&this.updated_by)),
- )
+ ))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
@@ -606,8 +611,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
- let storage_scheme =
- decide_storage_scheme::<_, DieselPaymentAttempt>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
@@ -668,8 +677,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
storage_scheme,
)
};
- let storage_scheme =
- decide_storage_scheme::<_, DieselPaymentAttempt>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
@@ -722,8 +735,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
storage_scheme,
)
};
- let storage_scheme =
- decide_storage_scheme::<_, DieselPaymentAttempt>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
@@ -771,8 +788,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
connector_txn_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
- let storage_scheme =
- decide_storage_scheme::<_, DieselPaymentAttempt>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
@@ -836,8 +857,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
attempt_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
- let storage_scheme =
- decide_storage_scheme::<_, DieselPaymentAttempt>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
@@ -884,8 +909,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
- let storage_scheme =
- decide_storage_scheme::<_, DieselPaymentAttempt>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
@@ -945,8 +974,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
- let storage_scheme =
- decide_storage_scheme::<_, DieselPaymentAttempt>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
@@ -1009,8 +1042,12 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
payment_id: &common_utils::id_type::PaymentId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError> {
- let storage_scheme =
- decide_storage_scheme::<_, DieselPaymentAttempt>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentAttempt>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
@@ -1232,6 +1269,8 @@ impl DataModelExt for PaymentAttempt {
customer_acceptance: self.customer_acceptance,
organization_id: self.organization_id,
profile_id: self.profile_id,
+ shipping_cost: self.shipping_cost,
+ order_tax_amount: self.order_tax_amount,
}
}
@@ -1301,6 +1340,8 @@ impl DataModelExt for PaymentAttempt {
customer_acceptance: storage_model.customer_acceptance,
organization_id: storage_model.organization_id,
profile_id: storage_model.profile_id,
+ shipping_cost: storage_model.shipping_cost,
+ order_tax_amount: storage_model.order_tax_amount,
}
}
}
@@ -1386,6 +1427,8 @@ impl DataModelExt for PaymentAttempt {
customer_acceptance: self.customer_acceptance,
organization_id: self.organization_id,
profile_id: self.profile_id,
+ shipping_cost: self.shipping_cost,
+ order_tax_amount: self.order_tax_amount,
}
}
@@ -1455,6 +1498,8 @@ impl DataModelExt for PaymentAttempt {
customer_acceptance: storage_model.customer_acceptance,
organization_id: storage_model.organization_id,
profile_id: storage_model.profile_id,
+ shipping_cost: storage_model.shipping_cost,
+ order_tax_amount: storage_model.order_tax_amount,
}
}
}
@@ -1540,6 +1585,8 @@ impl DataModelExt for PaymentAttemptNew {
customer_acceptance: self.customer_acceptance,
organization_id: self.organization_id,
profile_id: self.profile_id,
+ shipping_cost: self.shipping_cost,
+ order_tax_amount: self.order_tax_amount,
}
}
@@ -1608,6 +1655,8 @@ impl DataModelExt for PaymentAttemptNew {
customer_acceptance: storage_model.customer_acceptance,
organization_id: storage_model.organization_id,
profile_id: storage_model.profile_id,
+ shipping_cost: storage_model.shipping_cost,
+ order_tax_amount: storage_model.order_tax_amount,
}
}
}
@@ -1733,6 +1782,8 @@ impl DataModelExt for PaymentAttemptUpdate {
client_source,
client_version,
customer_acceptance,
+ shipping_cost,
+ order_tax_amount,
} => DieselPaymentAttemptUpdate::ConfirmUpdate {
amount: amount.get_amount_as_i64(),
currency,
@@ -1766,6 +1817,8 @@ impl DataModelExt for PaymentAttemptUpdate {
client_source,
client_version,
customer_acceptance,
+ shipping_cost,
+ order_tax_amount,
},
Self::VoidUpdate {
status,
@@ -2072,6 +2125,8 @@ impl DataModelExt for PaymentAttemptUpdate {
client_source,
client_version,
customer_acceptance,
+ shipping_cost,
+ order_tax_amount,
} => Self::ConfirmUpdate {
amount: MinorUnit::new(amount),
currency,
@@ -2103,6 +2158,8 @@ impl DataModelExt for PaymentAttemptUpdate {
client_source,
client_version,
customer_acceptance,
+ shipping_cost,
+ order_tax_amount,
},
DieselPaymentAttemptUpdate::VoidUpdate {
status,
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index 90395e15dac..6a29e41569b 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -79,8 +79,12 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
merchant_id: &merchant_id,
payment_id: &payment_id,
};
- let storage_scheme =
- decide_storage_scheme::<_, DieselPaymentIntent>(self, storage_scheme, Op::Insert).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>(
+ self,
+ storage_scheme,
+ Op::Insert,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
@@ -154,11 +158,11 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
payment_id: &payment_id,
};
let field = format!("pi_{}", this.payment_id.get_string_repr());
- let storage_scheme = decide_storage_scheme::<_, DieselPaymentIntent>(
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>(
self,
storage_scheme,
Op::Update(key.clone(), &field, Some(&this.updated_by)),
- )
+ ))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
@@ -243,8 +247,12 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
er.change_context(new_err)
})
};
- let storage_scheme =
- decide_storage_scheme::<_, DieselPaymentIntent>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
let diesel_payment_intent = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs
index 08843a060a7..697b5d91c93 100644
--- a/crates/storage_impl/src/payouts/payout_attempt.rs
+++ b/crates/storage_impl/src/payouts/payout_attempt.rs
@@ -44,8 +44,12 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
payouts: &Payouts,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
- let storage_scheme =
- decide_storage_scheme::<_, DieselPayoutAttempt>(self, storage_scheme, Op::Insert).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>(
+ self,
+ storage_scheme,
+ Op::Insert,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
@@ -144,11 +148,11 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
payout_attempt_id: &this.payout_id,
};
let field = format!("poa_{}", this.payout_attempt_id);
- let storage_scheme = decide_storage_scheme::<_, DieselPayoutAttempt>(
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>(
self,
storage_scheme,
Op::Update(key.clone(), &field, None),
- )
+ ))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
@@ -240,8 +244,12 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
payout_attempt_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
- let storage_scheme =
- decide_storage_scheme::<_, DieselPayoutAttempt>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index 7307de7c3f6..b6e1c1ac35f 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -82,8 +82,12 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
new: PayoutsNew,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
- let storage_scheme =
- decide_storage_scheme::<_, DieselPayouts>(self, storage_scheme, Op::Insert).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>(
+ self,
+ storage_scheme,
+ Op::Insert,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store.insert_payout(new, storage_scheme).await
@@ -168,11 +172,11 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
payout_id: &this.payout_id,
};
let field = format!("po_{}", this.payout_id);
- let storage_scheme = decide_storage_scheme::<_, DieselPayouts>(
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>(
self,
storage_scheme,
Op::Update(key.clone(), &field, None),
- )
+ ))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
@@ -235,8 +239,12 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
er.change_context(new_err)
})
};
- let storage_scheme =
- decide_storage_scheme::<_, DieselPayouts>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
@@ -279,8 +287,12 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
er.change_context(new_err)
})
};
- let storage_scheme =
- decide_storage_scheme::<_, DieselPayouts>(self, storage_scheme, Op::Find).await;
+ let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>(
+ self,
+ storage_scheme,
+ Op::Find,
+ ))
+ .await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
let maybe_payouts = database_call().await?;
diff --git a/migrations/2024-09-10-080050_add_shipping_cost_and_order_tax_amount_to_payment_attempt/down.sql b/migrations/2024-09-10-080050_add_shipping_cost_and_order_tax_amount_to_payment_attempt/down.sql
new file mode 100644
index 00000000000..8ad0af96f00
--- /dev/null
+++ b/migrations/2024-09-10-080050_add_shipping_cost_and_order_tax_amount_to_payment_attempt/down.sql
@@ -0,0 +1,3 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE payment_attempt DROP COLUMN IF EXISTS shipping_cost;
+ALTER TABLE payment_attempt DROP COLUMN IF EXISTS order_tax_amount;
\ No newline at end of file
diff --git a/migrations/2024-09-10-080050_add_shipping_cost_and_order_tax_amount_to_payment_attempt/up.sql b/migrations/2024-09-10-080050_add_shipping_cost_and_order_tax_amount_to_payment_attempt/up.sql
new file mode 100644
index 00000000000..2122db364c9
--- /dev/null
+++ b/migrations/2024-09-10-080050_add_shipping_cost_and_order_tax_amount_to_payment_attempt/up.sql
@@ -0,0 +1,4 @@
+-- Your SQL goes here
+ALTER TABLE payment_attempt ADD COLUMN IF NOT EXISTS shipping_cost BIGINT;
+ALTER TABLE payment_attempt
+ADD COLUMN IF NOT EXISTS order_tax_amount BIGINT;
|
refactor
|
Update shipping_cost and order_tax_amount to net_amount of payment_attempt (#5844)
|
5965d0f8acf486909951e427b578aae8d630de13
|
2025-02-27 13:33:01
|
Sagnik Mitra
|
feat(connector): [PAYSTACK] Template PR (#7285)
| false
|
diff --git a/api-reference-v2/openapi_spec.json b/api-reference-v2/openapi_spec.json
index 1ec27163f3e..23219414f67 100644
--- a/api-reference-v2/openapi_spec.json
+++ b/api-reference-v2/openapi_spec.json
@@ -7517,6 +7517,7 @@
"payme",
"payone",
"paypal",
+ "paystack",
"payu",
"placetopay",
"powertranz",
@@ -20093,6 +20094,7 @@
"payme",
"payone",
"paypal",
+ "paystack",
"payu",
"placetopay",
"powertranz",
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index 7f7d97ce110..9aea807b39a 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -9624,6 +9624,7 @@
"payme",
"payone",
"paypal",
+ "paystack",
"payu",
"placetopay",
"powertranz",
@@ -24547,6 +24548,7 @@
"payme",
"payone",
"paypal",
+ "paystack",
"payu",
"placetopay",
"powertranz",
diff --git a/config/config.example.toml b/config/config.example.toml
index 341ff3e613b..641c06b366e 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -247,6 +247,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
payone.base_url = "https://payment.preprod.payone.com/"
paypal.base_url = "https://api-m.sandbox.paypal.com/"
+paystack.base_url = "https://api.paystack.co"
payu.base_url = "https://secure.snd.payu.com/"
placetopay.base_url = "https://test.placetopay.com/rest/gateway"
plaid.base_url = "https://sandbox.plaid.com"
@@ -330,6 +331,7 @@ cards = [
"mollie",
"moneris",
"paypal",
+ "paystack",
"shift4",
"square",
"stax",
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index fb405385702..af2c7500add 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -92,6 +92,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
payone.base_url = "https://payment.preprod.payone.com/"
paypal.base_url = "https://api-m.sandbox.paypal.com/"
+paystack.base_url = "https://api.paystack.co"
payu.base_url = "https://secure.snd.payu.com/"
placetopay.base_url = "https://test.placetopay.com/rest/gateway"
plaid.base_url = "https://sandbox.plaid.com"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index b05c6193346..e79bb79f8fa 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -96,6 +96,7 @@ payeezy.base_url = "https://api.payeezy.com/"
payme.base_url = "https://live.payme.io/"
payone.base_url = "https://payment.payone.com/"
paypal.base_url = "https://api-m.paypal.com/"
+paystack.base_url = "https://api.paystack.co"
payu.base_url = "https://secure.payu.com/api/"
placetopay.base_url = "https://checkout.placetopay.com/rest/gateway"
plaid.base_url = "https://production.plaid.com"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 0de2bd26f20..67682388d4a 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -96,6 +96,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
payone.base_url = "https://payment.preprod.payone.com/"
paypal.base_url = "https://api-m.sandbox.paypal.com/"
+paystack.base_url = "https://api.paystack.co"
payu.base_url = "https://secure.snd.payu.com/"
placetopay.base_url = "https://test.placetopay.com/rest/gateway"
plaid.base_url = "https://sandbox.plaid.com"
diff --git a/config/development.toml b/config/development.toml
index aa63f76b885..f5d258d4789 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -198,6 +198,7 @@ cards = [
"payme",
"payone",
"paypal",
+ "paystack",
"payu",
"placetopay",
"plaid",
@@ -317,6 +318,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
payone.base_url = "https://payment.preprod.payone.com/"
paypal.base_url = "https://api-m.sandbox.paypal.com/"
+paystack.base_url = "https://api.paystack.co"
payu.base_url = "https://secure.snd.payu.com/"
placetopay.base_url = "https://test.placetopay.com/rest/gateway"
plaid.base_url = "https://sandbox.plaid.com"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 048bf6dd960..993ecaa0a06 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -179,6 +179,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
payone.base_url = "https://payment.preprod.payone.com/"
paypal.base_url = "https://api-m.sandbox.paypal.com/"
+paystack.base_url = "https://api.paystack.co"
payu.base_url = "https://secure.snd.payu.com/"
placetopay.base_url = "https://test.placetopay.com/rest/gateway"
plaid.base_url = "https://sandbox.plaid.com"
@@ -278,6 +279,7 @@ cards = [
"payme",
"payone",
"paypal",
+ "paystack",
"payu",
"placetopay",
"plaid",
diff --git a/crates/common_enums/src/connector_enums.rs b/crates/common_enums/src/connector_enums.rs
index 47f2ddadc92..9cd896d5c35 100644
--- a/crates/common_enums/src/connector_enums.rs
+++ b/crates/common_enums/src/connector_enums.rs
@@ -109,6 +109,7 @@ pub enum RoutableConnectors {
Payme,
Payone,
Paypal,
+ Paystack,
Payu,
Placetopay,
Powertranz,
@@ -250,6 +251,7 @@ pub enum Connector {
Payme,
Payone,
Paypal,
+ Paystack,
Payu,
Placetopay,
Powertranz,
@@ -398,6 +400,7 @@ impl Connector {
| Self::Payme
| Self::Payone
| Self::Paypal
+ | Self::Paystack
| Self::Payu
| Self::Placetopay
| Self::Powertranz
@@ -529,6 +532,7 @@ impl From<RoutableConnectors> for Connector {
RoutableConnectors::Payme => Self::Payme,
RoutableConnectors::Payone => Self::Payone,
RoutableConnectors::Paypal => Self::Paypal,
+ RoutableConnectors::Paystack => Self::Paystack,
RoutableConnectors::Payu => Self::Payu,
RoutableConnectors::Placetopay => Self::Placetopay,
RoutableConnectors::Powertranz => Self::Powertranz,
diff --git a/crates/connector_configs/src/connector.rs b/crates/connector_configs/src/connector.rs
index ff4152c5141..34ce0a7f000 100644
--- a/crates/connector_configs/src/connector.rs
+++ b/crates/connector_configs/src/connector.rs
@@ -220,6 +220,7 @@ pub struct ConnectorConfig {
pub paypal: Option<ConnectorTomlConfig>,
#[cfg(feature = "payouts")]
pub paypal_payout: Option<ConnectorTomlConfig>,
+ pub paystack: Option<ConnectorTomlConfig>,
pub payu: Option<ConnectorTomlConfig>,
pub placetopay: Option<ConnectorTomlConfig>,
pub plaid: Option<ConnectorTomlConfig>,
@@ -385,6 +386,7 @@ impl ConnectorConfig {
Connector::Payme => Ok(connector_data.payme),
Connector::Payone => Err("Use get_payout_connector_config".to_string()),
Connector::Paypal => Ok(connector_data.paypal),
+ Connector::Paystack => Ok(connector_data.paystack),
Connector::Payu => Ok(connector_data.payu),
Connector::Placetopay => Ok(connector_data.placetopay),
Connector::Plaid => Ok(connector_data.plaid),
diff --git a/crates/hyperswitch_connectors/src/connectors.rs b/crates/hyperswitch_connectors/src/connectors.rs
index 0b6042ef931..97a2bdb77bb 100644
--- a/crates/hyperswitch_connectors/src/connectors.rs
+++ b/crates/hyperswitch_connectors/src/connectors.rs
@@ -46,6 +46,7 @@ pub mod novalnet;
pub mod nuvei;
pub mod paybox;
pub mod payeezy;
+pub mod paystack;
pub mod payu;
pub mod placetopay;
pub mod powertranz;
@@ -80,10 +81,10 @@ pub use self::{
iatapay::Iatapay, inespay::Inespay, itaubank::Itaubank, jpmorgan::Jpmorgan, klarna::Klarna,
mifinity::Mifinity, mollie::Mollie, moneris::Moneris, multisafepay::Multisafepay,
nexinets::Nexinets, nexixpay::Nexixpay, nomupay::Nomupay, novalnet::Novalnet, nuvei::Nuvei,
- 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,
+ paybox::Paybox, payeezy::Payeezy, paystack::Paystack, 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/paystack.rs b/crates/hyperswitch_connectors/src/connectors/paystack.rs
new file mode 100644
index 00000000000..a88b60cc210
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/paystack.rs
@@ -0,0 +1,568 @@
+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 paystack;
+
+use crate::{constants::headers, types::ResponseRouterData, utils};
+
+#[derive(Clone)]
+pub struct Paystack {
+ amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
+}
+
+impl Paystack {
+ pub fn new() -> &'static Self {
+ &Self {
+ amount_converter: &StringMinorUnitForConnector,
+ }
+ }
+}
+
+impl api::Payment for Paystack {}
+impl api::PaymentSession for Paystack {}
+impl api::ConnectorAccessToken for Paystack {}
+impl api::MandateSetup for Paystack {}
+impl api::PaymentAuthorize for Paystack {}
+impl api::PaymentSync for Paystack {}
+impl api::PaymentCapture for Paystack {}
+impl api::PaymentVoid for Paystack {}
+impl api::Refund for Paystack {}
+impl api::RefundExecute for Paystack {}
+impl api::RefundSync for Paystack {}
+impl api::PaymentToken for Paystack {}
+
+impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
+ for Paystack
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paystack
+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 Paystack {
+ fn id(&self) -> &'static str {
+ "paystack"
+ }
+
+ fn get_currency_unit(&self) -> api::CurrencyUnit {
+ api::CurrencyUnit::Minor
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
+ connectors.paystack.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
+ let auth = paystack::PaystackAuthType::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: paystack::PaystackErrorResponse = res
+ .response
+ .parse_struct("PaystackErrorResponse")
+ .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 Paystack {
+ //TODO: implement functions when support enabled
+}
+
+impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Paystack {
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paystack {}
+
+impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
+ for Paystack
+{
+}
+
+impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paystack {
+ 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 = paystack::PaystackRouterData::from((amount, req));
+ let connector_req = paystack::PaystackPaymentsRequest::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: paystack::PaystackPaymentsResponse = res
+ .response
+ .parse_struct("Paystack 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 Paystack {
+ 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: paystack::PaystackPaymentsResponse = res
+ .response
+ .parse_struct("paystack 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 Paystack {
+ 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: paystack::PaystackPaymentsResponse = res
+ .response
+ .parse_struct("Paystack 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 Paystack {}
+
+impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paystack {
+ 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 = paystack::PaystackRouterData::from((refund_amount, req));
+ let connector_req = paystack::PaystackRefundRequest::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: paystack::RefundResponse = res
+ .response
+ .parse_struct("paystack 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 Paystack {
+ 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: paystack::RefundResponse = res
+ .response
+ .parse_struct("paystack 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 Paystack {
+ 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 Paystack {}
diff --git a/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs b/crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs
new file mode 100644
index 00000000000..8a07997fbdc
--- /dev/null
+++ b/crates/hyperswitch_connectors/src/connectors/paystack/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 PaystackRouterData<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 PaystackRouterData<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 PaystackPaymentsRequest {
+ amount: StringMinorUnit,
+ card: PaystackCard,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct PaystackCard {
+ number: cards::CardNumber,
+ expiry_month: Secret<String>,
+ expiry_year: Secret<String>,
+ cvc: Secret<String>,
+ complete: bool,
+}
+
+impl TryFrom<&PaystackRouterData<&PaymentsAuthorizeRouterData>> for PaystackPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: &PaystackRouterData<&PaymentsAuthorizeRouterData>,
+ ) -> Result<Self, Self::Error> {
+ match item.router_data.request.payment_method_data.clone() {
+ PaymentMethodData::Card(req_card) => {
+ let card = PaystackCard {
+ 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 PaystackAuthType {
+ pub(super) api_key: Secret<String>,
+}
+
+impl TryFrom<&ConnectorAuthType> for PaystackAuthType {
+ 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 PaystackPaymentStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<PaystackPaymentStatus> for common_enums::AttemptStatus {
+ fn from(item: PaystackPaymentStatus) -> Self {
+ match item {
+ PaystackPaymentStatus::Succeeded => Self::Charged,
+ PaystackPaymentStatus::Failed => Self::Failure,
+ PaystackPaymentStatus::Processing => Self::Authorizing,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct PaystackPaymentsResponse {
+ status: PaystackPaymentStatus,
+ id: String,
+}
+
+impl<F, T> TryFrom<ResponseRouterData<F, PaystackPaymentsResponse, T, PaymentsResponseData>>
+ for RouterData<F, T, PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: ResponseRouterData<F, PaystackPaymentsResponse, 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,
+ charges: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct PaystackRefundRequest {
+ pub amount: StringMinorUnit,
+}
+
+impl<F> TryFrom<&PaystackRouterData<&RefundsRouterData<F>>> for PaystackRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &PaystackRouterData<&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 PaystackErrorResponse {
+ 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 146175801ff..243afaa5f41 100644
--- a/crates/hyperswitch_connectors/src/default_implementations.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations.rs
@@ -139,6 +139,7 @@ default_imp_for_authorize_session_token!(
connectors::Nexixpay,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -228,6 +229,7 @@ default_imp_for_calculate_tax!(
connectors::Novalnet,
connectors::Nuvei,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -315,6 +317,7 @@ default_imp_for_session_update!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::UnifiedAuthenticationService,
@@ -401,6 +404,7 @@ default_imp_for_post_session_tokens!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Fiuu,
@@ -475,6 +479,7 @@ default_imp_for_complete_authorize!(
connectors::Novalnet,
connectors::Nexinets,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Rapyd,
@@ -553,6 +558,7 @@ default_imp_for_incremental_authorization!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -642,6 +648,7 @@ default_imp_for_create_customer!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -719,6 +726,7 @@ default_imp_for_connector_redirect_response!(
connectors::Nexinets,
connectors::Nexixpay,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -794,6 +802,7 @@ default_imp_for_pre_processing_steps!(
connectors::Nexinets,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -879,6 +888,7 @@ default_imp_for_post_processing_steps!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -966,6 +976,7 @@ default_imp_for_approve!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1053,6 +1064,7 @@ default_imp_for_reject!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1140,6 +1152,7 @@ default_imp_for_webhook_source_verification!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1228,6 +1241,7 @@ default_imp_for_accept_dispute!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1315,6 +1329,7 @@ default_imp_for_submit_evidence!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1402,6 +1417,7 @@ default_imp_for_defend_dispute!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1498,6 +1514,7 @@ default_imp_for_file_upload!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1580,6 +1597,7 @@ default_imp_for_payouts!(
connectors::Novalnet,
connectors::Nuvei,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1663,6 +1681,7 @@ default_imp_for_payouts_create!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1751,6 +1770,7 @@ default_imp_for_payouts_retrieve!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1839,6 +1859,7 @@ default_imp_for_payouts_eligibility!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1926,6 +1947,7 @@ default_imp_for_payouts_fulfill!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -2014,6 +2036,7 @@ default_imp_for_payouts_cancel!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -2102,6 +2125,7 @@ default_imp_for_payouts_quote!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -2190,6 +2214,7 @@ default_imp_for_payouts_recipient!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -2278,6 +2303,7 @@ default_imp_for_payouts_recipient_account!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -2367,6 +2393,7 @@ default_imp_for_frm_sale!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -2456,6 +2483,7 @@ default_imp_for_frm_checkout!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -2545,6 +2573,7 @@ default_imp_for_frm_transaction!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -2634,6 +2663,7 @@ default_imp_for_frm_fulfillment!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -2723,6 +2753,7 @@ default_imp_for_frm_record_return!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -2808,6 +2839,7 @@ default_imp_for_revoking_mandates!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -2894,6 +2926,7 @@ default_imp_for_uas_pre_authentication!(
connectors::Nexixpay,
connectors::Nuvei,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Powertranz,
connectors::Prophetpay,
@@ -2979,6 +3012,7 @@ default_imp_for_uas_post_authentication!(
connectors::Nexixpay,
connectors::Nuvei,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Powertranz,
connectors::Prophetpay,
@@ -3064,6 +3098,7 @@ default_imp_for_uas_authentication!(
connectors::Nexixpay,
connectors::Nuvei,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Powertranz,
connectors::Prophetpay,
@@ -3150,6 +3185,7 @@ default_imp_for_uas_authentication_confirmation!(
connectors::Nexixpay,
connectors::Nuvei,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Powertranz,
connectors::Prophetpay,
diff --git a/crates/hyperswitch_connectors/src/default_implementations_v2.rs b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
index d0ffd3a230c..003c3cc46d1 100644
--- a/crates/hyperswitch_connectors/src/default_implementations_v2.rs
+++ b/crates/hyperswitch_connectors/src/default_implementations_v2.rs
@@ -248,6 +248,7 @@ default_imp_for_new_connector_integration_payment!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -336,6 +337,7 @@ default_imp_for_new_connector_integration_refund!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -419,6 +421,7 @@ default_imp_for_new_connector_integration_connector_access_token!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -507,6 +510,7 @@ default_imp_for_new_connector_integration_accept_dispute!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -594,6 +598,7 @@ default_imp_for_new_connector_integration_submit_evidence!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -682,6 +687,7 @@ default_imp_for_new_connector_integration_defend_dispute!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -780,6 +786,7 @@ default_imp_for_new_connector_integration_file_upload!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -870,6 +877,7 @@ default_imp_for_new_connector_integration_payouts_create!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -960,6 +968,7 @@ default_imp_for_new_connector_integration_payouts_eligibility!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1050,6 +1059,7 @@ default_imp_for_new_connector_integration_payouts_fulfill!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1140,6 +1150,7 @@ default_imp_for_new_connector_integration_payouts_cancel!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1230,6 +1241,7 @@ default_imp_for_new_connector_integration_payouts_quote!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1320,6 +1332,7 @@ default_imp_for_new_connector_integration_payouts_recipient!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1410,6 +1423,7 @@ default_imp_for_new_connector_integration_payouts_sync!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1500,6 +1514,7 @@ default_imp_for_new_connector_integration_payouts_recipient_account!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1588,6 +1603,7 @@ default_imp_for_new_connector_integration_webhook_source_verification!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1678,6 +1694,7 @@ default_imp_for_new_connector_integration_frm_sale!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1768,6 +1785,7 @@ default_imp_for_new_connector_integration_frm_checkout!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1858,6 +1876,7 @@ default_imp_for_new_connector_integration_frm_transaction!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -1948,6 +1967,7 @@ default_imp_for_new_connector_integration_frm_fulfillment!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -2038,6 +2058,7 @@ default_imp_for_new_connector_integration_frm_record_return!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
@@ -2125,6 +2146,7 @@ default_imp_for_new_connector_integration_revoking_mandates!(
connectors::Nuvei,
connectors::Paybox,
connectors::Payeezy,
+ connectors::Paystack,
connectors::Payu,
connectors::Placetopay,
connectors::Powertranz,
diff --git a/crates/hyperswitch_interfaces/src/configs.rs b/crates/hyperswitch_interfaces/src/configs.rs
index d5656f3a477..4c4801801f0 100644
--- a/crates/hyperswitch_interfaces/src/configs.rs
+++ b/crates/hyperswitch_interfaces/src/configs.rs
@@ -73,6 +73,7 @@ pub struct Connectors {
pub payme: ConnectorParams,
pub payone: ConnectorParams,
pub paypal: ConnectorParams,
+ pub paystack: ConnectorParams,
pub payu: ConnectorParams,
pub placetopay: ConnectorParams,
pub plaid: ConnectorParams,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 4bf57cb16f0..de9d86fdd79 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -41,11 +41,11 @@ pub use hyperswitch_connectors::connectors::{
klarna::Klarna, mifinity, mifinity::Mifinity, mollie, mollie::Mollie, moneris,
moneris::Moneris, multisafepay, multisafepay::Multisafepay, nexinets, nexinets::Nexinets,
nexixpay, nexixpay::Nexixpay, nomupay, nomupay::Nomupay, novalnet, novalnet::Novalnet, nuvei,
- nuvei::Nuvei, 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,
+ nuvei::Nuvei, paybox, paybox::Paybox, payeezy, payeezy::Payeezy, paystack, paystack::Paystack,
+ 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,
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 81d32dc4ba7..4d7cc1620fa 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -1496,6 +1496,10 @@ impl ConnectorAuthTypeAndMetadataValidation<'_> {
payone::transformers::PayoneAuthType::try_from(self.auth_type)?;
Ok(())
}
+ api_enums::Connector::Paystack => {
+ paystack::transformers::PaystackAuthType::try_from(self.auth_type)?;
+ Ok(())
+ }
api_enums::Connector::Payu => {
payu::transformers::PayuAuthType::try_from(self.auth_type)?;
Ok(())
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 1219363b212..997a40c9393 100644
--- a/crates/router/src/core/payments/connector_integration_v2_impls.rs
+++ b/crates/router/src/core/payments/connector_integration_v2_impls.rs
@@ -1030,6 +1030,7 @@ default_imp_for_new_connector_integration_payouts!(
connector::Payme,
connector::Payone,
connector::Paypal,
+ connector::Paystack,
connector::Payu,
connector::Powertranz,
connector::Rapyd,
@@ -1496,6 +1497,7 @@ default_imp_for_new_connector_integration_frm!(
connector::Payme,
connector::Payone,
connector::Paypal,
+ connector::Paystack,
connector::Payu,
connector::Powertranz,
connector::Rapyd,
@@ -1873,6 +1875,7 @@ default_imp_for_new_connector_integration_connector_authentication!(
connector::Payme,
connector::Payone,
connector::Paypal,
+ connector::Paystack,
connector::Payu,
connector::Placetopay,
connector::Powertranz,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index f55c1f58f60..e9e3ea10cd6 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -452,6 +452,7 @@ default_imp_for_connector_request_id!(
connector::Payme,
connector::Payone,
connector::Paypal,
+ connector::Paystack,
connector::Payu,
connector::Placetopay,
connector::Plaid,
@@ -1413,6 +1414,7 @@ default_imp_for_fraud_check!(
connector::Payme,
connector::Payone,
connector::Paypal,
+ connector::Paystack,
connector::Payu,
connector::Placetopay,
connector::Plaid,
@@ -1948,6 +1950,7 @@ default_imp_for_connector_authentication!(
connector::Payme,
connector::Payone,
connector::Paypal,
+ connector::Paystack,
connector::Payu,
connector::Placetopay,
connector::Plaid,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 1bc93394957..c5ca0e72abf 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -545,6 +545,9 @@ impl ConnectorData {
enums::Connector::Paypal => {
Ok(ConnectorEnum::Old(Box::new(connector::Paypal::new())))
}
+ enums::Connector::Paystack => {
+ Ok(ConnectorEnum::Old(Box::new(connector::Paystack::new())))
+ }
// enums::Connector::Thunes => Ok(ConnectorEnum::Old(Box::new(connector::Thunes))),
enums::Connector::Trustpay => {
Ok(ConnectorEnum::Old(Box::new(connector::Trustpay::new())))
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 5bd6e746033..0dd11a2f387 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -282,6 +282,7 @@ impl ForeignTryFrom<api_enums::Connector> for common_enums::RoutableConnectors {
api_enums::Connector::Payme => Self::Payme,
api_enums::Connector::Payone => Self::Payone,
api_enums::Connector::Paypal => Self::Paypal,
+ api_enums::Connector::Paystack => Self::Paystack,
api_enums::Connector::Payu => Self::Payu,
api_models::enums::Connector::Placetopay => Self::Placetopay,
api_enums::Connector::Plaid => Self::Plaid,
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index f2fdfddfd63..d0eb96efcc8 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -69,6 +69,7 @@ mod payeezy;
mod payme;
mod payone;
mod paypal;
+mod paystack;
mod payu;
mod placetopay;
mod plaid;
diff --git a/crates/router/tests/connectors/paystack.rs b/crates/router/tests/connectors/paystack.rs
new file mode 100644
index 00000000000..2aaac95b208
--- /dev/null
+++ b/crates/router/tests/connectors/paystack.rs
@@ -0,0 +1,421 @@
+use hyperswitch_domain_models::payment_method_data::{Card, PaymentMethodData};
+use masking::Secret;
+use router::types::{self, api, storage::enums};
+use test_utils::connector_auth;
+
+use crate::utils::{self, ConnectorActions};
+
+#[derive(Clone, Copy)]
+struct PaystackTest;
+impl ConnectorActions for PaystackTest {}
+impl utils::Connector for PaystackTest {
+ fn get_data(&self) -> api::ConnectorData {
+ use router::connector::Paystack;
+ utils::construct_connector_data_old(
+ Box::new(Paystack::new()),
+ types::Connector::Plaid,
+ api::GetToken::Connector,
+ None,
+ )
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ utils::to_connector_auth_type(
+ connector_auth::ConnectorAuthentication::new()
+ .paystack
+ .expect("Missing connector authentication configuration")
+ .into(),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "paystack".to_string()
+ }
+}
+
+static CONNECTOR: PaystackTest = PaystackTest {};
+
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ None
+}
+
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ None
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Partially captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ payment_method_details(),
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: 50,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+}
+
+// Voids a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_void_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_void_payment(
+ payment_method_details(),
+ Some(types::PaymentsCancelData {
+ connector_transaction_id: String::from(""),
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Void payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
+}
+
+// Refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Synchronizes a refund using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_manually_captured_refund() {
+ let refund_response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ capture_method: Some(enums::CaptureMethod::Automatic),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_auto_captured_payment() {
+ let response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_succeeded_payment() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_succeeded_payment_multiple_times() {
+ CONNECTOR
+ .make_payment_and_multiple_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await;
+}
+
+// Synchronizes a refund using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_refund() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Cards Negative scenarios
+// Creates a payment with incorrect CVC.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's security code is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration month is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: PaymentMethodData::Card(Card {
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration year is invalid.".to_string(),
+ );
+}
+
+// Voids a payment using automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_fail_void_payment_for_auto_capture() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(txn_id.unwrap(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ void_response.response.unwrap_err().message,
+ "You cannot cancel this PaymentIntent because it has a status of succeeded."
+ );
+}
+
+// Captures a payment using invalid connector payment id.
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ capture_response.response.unwrap_err().message,
+ String::from("No such payment_intent: '123456789'")
+ );
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+#[actix_web::test]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
+ );
+}
+
+// Connector dependent test cases goes here
+
+// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index 45ac315f241..6509e1e411f 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -314,4 +314,7 @@ api_key="API Key"
api_key= "API Key"
[moneris]
-api_key= "API Key"
\ No newline at end of file
+api_key= "API Key"
+
+[paystack]
+api_key = "API Key"
\ No newline at end of file
diff --git a/crates/test_utils/src/connector_auth.rs b/crates/test_utils/src/connector_auth.rs
index 0f4e7250faa..521e58136aa 100644
--- a/crates/test_utils/src/connector_auth.rs
+++ b/crates/test_utils/src/connector_auth.rs
@@ -74,6 +74,7 @@ pub struct ConnectorAuthentication {
pub payme: Option<BodyKey>,
pub payone: Option<HeaderKey>,
pub paypal: Option<BodyKey>,
+ pub paystack: Option<HeaderKey>,
pub payu: Option<BodyKey>,
pub placetopay: Option<BodyKey>,
pub plaid: Option<BodyKey>,
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index 212819e0c3a..2a6a14ec755 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -145,6 +145,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
payone.base_url = "https://payment.preprod.payone.com/"
paypal.base_url = "https://api-m.sandbox.paypal.com/"
+paystack.base_url = "https://api.paystack.co"
payu.base_url = "https://secure.snd.payu.com/"
placetopay.base_url = "https://test.placetopay.com/rest/gateway"
plaid.base_url = "https://sandbox.plaid.com"
@@ -244,6 +245,7 @@ cards = [
"payme",
"payone",
"paypal",
+ "paystack",
"payu",
"placetopay",
"plaid",
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 021854ab3f1..f2c55f54adc 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 getnet globalpay globepay gocardless gpayments helcim iatapay inespay itaubank jpmorgan klarna mifinity mollie moneris 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 cryptopay cybersource datatrans deutschebank digitalvirgo dlocal dummyconnector ebanx elavon fiserv fiservemea fiuu forte getnet globalpay globepay gocardless gpayments helcim iatapay inespay itaubank jpmorgan klarna mifinity mollie moneris multisafepay netcetera nexinets nexixpay nomupay noon novalnet nuvei opayo opennode paybox payeezy payme payone paypal paystack 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
|
[PAYSTACK] Template PR (#7285)
|
df739a302b062277647afe5c3888015272fdc2cf
|
2024-02-19 15:28:56
|
SamraatBansal
|
fix(connector): [noon] Fail the payment for specific error_response (#3674)
| false
|
diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs
index 33cb94da182..d9e9417df8e 100644
--- a/crates/router/src/connector/noon.rs
+++ b/crates/router/src/connector/noon.rs
@@ -137,12 +137,18 @@ impl ConnectorCommon for Noon {
Ok(noon_error_response) => {
event_builder.map(|i| i.set_error_response_body(&noon_error_response));
router_env::logger::info!(connector_response=?noon_error_response);
+ // Adding in case of timeouts, if psync gives 4xx with this code, fail the payment
+ let attempt_status = if noon_error_response.result_code == 19001 {
+ Some(enums::AttemptStatus::Failure)
+ } else {
+ None
+ };
Ok(ErrorResponse {
status_code: res.status_code,
- code: consts::NO_ERROR_CODE.to_string(),
+ code: noon_error_response.result_code.to_string(),
message: noon_error_response.class_description,
reason: Some(noon_error_response.message),
- attempt_status: None,
+ attempt_status,
connector_transaction_id: None,
})
}
|
fix
|
[noon] Fail the payment for specific error_response (#3674)
|
e098415bb694f76839e3b9c59f218e353cdd15c8
|
2024-07-19 10:34:54
|
github-actions
|
chore(version): 2024.07.19.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 421ef15d409..81e590a7726 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,40 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 2024.07.19.0
+
+### Features
+
+- **connector:** [Itau Bank] Template for payment flows ([#5304](https://github.com/juspay/hyperswitch/pull/5304)) ([`ef1418f`](https://github.com/juspay/hyperswitch/commit/ef1418f978835a8df149181bc5e19053775490f2))
+
+### Bug Fixes
+
+- **core:** [payouts] failure of payout retrieve when token is expired ([#5362](https://github.com/juspay/hyperswitch/pull/5362)) ([`817d06c`](https://github.com/juspay/hyperswitch/commit/817d06c7faa14493674931ba51ab6c32769602d1))
+
+### Refactors
+
+- **blocklist:** Change primary key of blocklist table ([#5356](https://github.com/juspay/hyperswitch/pull/5356)) ([`93047ae`](https://github.com/juspay/hyperswitch/commit/93047ae616b6a5240c2be13f8c5267e5fa616eab))
+- **merchant_account:** Change primary key for merchant account ([#5327](https://github.com/juspay/hyperswitch/pull/5327)) ([`a0c367e`](https://github.com/juspay/hyperswitch/commit/a0c367ee8c7f04cfdf1f9d4863447f24279a537f))
+- **router:** Remove id dependency from merchant connector account, dispute and mandate ([#5330](https://github.com/juspay/hyperswitch/pull/5330)) ([`6d74527`](https://github.com/juspay/hyperswitch/commit/6d74527f4428c8cb61e89d59385bfb2dd8056c2e))
+- **routing:** Remove backwards compatibility for the routing crate ([#3015](https://github.com/juspay/hyperswitch/pull/3015)) ([`78a7804`](https://github.com/juspay/hyperswitch/commit/78a7804b9c8b4db881b112fc72e31cfd3e97a82d))
+
+### Documentation
+
+- Updating Error codes for documentation purposes ([#5314](https://github.com/juspay/hyperswitch/pull/5314)) ([`fe14336`](https://github.com/juspay/hyperswitch/commit/fe14336f78b15e948b10d09b197fb1d529939b5c))
+
+### Miscellaneous Tasks
+
+- **postman:** Update Postman collection files ([`93dd60c`](https://github.com/juspay/hyperswitch/commit/93dd60c9ab8180ed7688959e32a3c2730c2bfad2))
+- Increasing log coverage for payment method list ([#5042](https://github.com/juspay/hyperswitch/pull/5042)) ([`edb581e`](https://github.com/juspay/hyperswitch/commit/edb581e8e3307714c1ebc3dec65fc73aeb2d7cb0))
+
+### Build System / Dependencies
+
+- Remove unused dependencies ([#5343](https://github.com/juspay/hyperswitch/pull/5343)) ([`7f582e4`](https://github.com/juspay/hyperswitch/commit/7f582e4737c1c7dfe906e7d01de239e131511f84))
+
+**Full Changelog:** [`2024.07.18.0...2024.07.19.0`](https://github.com/juspay/hyperswitch/compare/2024.07.18.0...2024.07.19.0)
+
+- - -
+
## 2024.07.18.0
### Features
|
chore
|
2024.07.19.0
|
e271ced69e64ac65d8e16a699531b12cbe4289dc
|
2023-07-18 19:34:52
|
Sakil Mostak
|
feat(connector): [Adyen] Implement Vipps in Wallets (#1554)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 90dd1f22e92..ef5f9afa806 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -981,6 +981,8 @@ pub enum WalletData {
SamsungPay(Box<SamsungPayWalletData>),
/// Wallet data for Twint Redirection
TwintRedirect {},
+ /// Wallet data for Vipps Redirection
+ VippsRedirect {},
/// The wallet data for WeChat Pay Redirection
WeChatPayRedirect(Box<WeChatPayRedirection>),
/// The wallet data for WeChat Pay
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index a05089d4b8b..23456f53eaf 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -593,6 +593,7 @@ pub enum PaymentMethodType {
Trustly,
Twint,
UpiCollect,
+ Vipps,
Walley,
WeChatPay,
}
diff --git a/crates/common_enums/src/transformers.rs b/crates/common_enums/src/transformers.rs
index 1218e983bc6..4d2e1b2e58c 100644
--- a/crates/common_enums/src/transformers.rs
+++ b/crates/common_enums/src/transformers.rs
@@ -1577,6 +1577,7 @@ impl From<PaymentMethodType> for PaymentMethod {
PaymentMethodType::Trustly => Self::BankRedirect,
PaymentMethodType::Twint => Self::Wallet,
PaymentMethodType::UpiCollect => Self::Upi,
+ PaymentMethodType::Vipps => Self::Wallet,
PaymentMethodType::Walley => Self::PayLater,
PaymentMethodType::WeChatPay => Self::Wallet,
}
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 7a43f6f314a..4ec7c616e99 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -310,6 +310,7 @@ pub enum AdyenPaymentMethod<'a> {
BacsDirectDebit(Box<BacsDirectDebitData>),
SamsungPay(Box<SamsungPayPmData>),
Twint(Box<TwintWalletData>),
+ Vipps(Box<VippsWalletData>),
}
#[derive(Debug, Clone, Serialize)]
@@ -674,6 +675,12 @@ pub struct TwintWalletData {
payment_type: PaymentType,
}
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct VippsWalletData {
+ #[serde(rename = "type")]
+ payment_type: PaymentType,
+}
+
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdyenPayLaterData {
#[serde(rename = "type")]
@@ -754,6 +761,7 @@ pub enum PaymentType {
BacsDirectDebit,
Samsungpay,
Twint,
+ Vipps,
}
pub struct AdyenTestBankNames<'a>(&'a str);
@@ -1242,6 +1250,12 @@ impl<'a> TryFrom<&api::WalletData> for AdyenPaymentMethod<'a> {
};
Ok(AdyenPaymentMethod::Twint(Box::new(data)))
}
+ api_models::payments::WalletData::VippsRedirect { .. } => {
+ let data = VippsWalletData {
+ payment_type: PaymentType::Vipps,
+ };
+ Ok(AdyenPaymentMethod::Vipps(Box::new(data)))
+ }
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index 4335aece5c1..0ca51fe51d0 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -175,6 +175,7 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod {
| api_enums::PaymentMethodType::MobilePay
| api_enums::PaymentMethodType::SamsungPay
| api_enums::PaymentMethodType::Twint
+ | api_enums::PaymentMethodType::Vipps
| api_enums::PaymentMethodType::WeChatPay
| api_enums::PaymentMethodType::GoPay
| api_enums::PaymentMethodType::Gcash
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 911279bbf98..d1dfb1550b1 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -6839,6 +6839,7 @@
"trustly",
"twint",
"upi_collect",
+ "vipps",
"walley",
"we_chat_pay"
]
@@ -9090,6 +9091,18 @@
}
}
},
+ {
+ "type": "object",
+ "required": [
+ "vipps_redirect"
+ ],
+ "properties": {
+ "vipps_redirect": {
+ "type": "object",
+ "description": "Wallet data for Vipps Redirection"
+ }
+ }
+ },
{
"type": "object",
"required": [
|
feat
|
[Adyen] Implement Vipps in Wallets (#1554)
|
8c5703df545007d8b61679bd57d0a58986ec10ce
|
2023-07-14 17:13:54
|
chikke srujan
|
test(connector): [stripe] Add ui test for affirm (#1694)
| false
|
diff --git a/crates/router/tests/connectors/selenium.rs b/crates/router/tests/connectors/selenium.rs
index b49575a94b5..f4408a67364 100644
--- a/crates/router/tests/connectors/selenium.rs
+++ b/crates/router/tests/connectors/selenium.rs
@@ -425,6 +425,55 @@ pub trait SeleniumTest {
self.complete_actions(&web_driver, default_actions).await?;
self.complete_actions(&web_driver, actions).await
}
+ async fn make_affirm_payment(
+ &self,
+ driver: WebDriver,
+ url: &str,
+ actions: Vec<Event<'_>>,
+ ) -> Result<(), WebDriverError> {
+ self.complete_actions(
+ &driver,
+ vec![
+ Event::Trigger(Trigger::Goto(url)),
+ Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
+ ],
+ )
+ .await?;
+ let mut affirm_actions = vec![
+ Event::RunIf(
+ Assert::IsPresent("Big purchase? No problem."),
+ vec![
+ Event::Trigger(Trigger::SendKeys(
+ By::Css("input.focusable-form-field.pro11TnYcue.pro284gg8sY"),
+ "(833) 549-5574", // any test phone number accepted by affirm
+ )),
+ Event::Trigger(Trigger::Click(By::Css(
+ "button.sc-aXZVg.gCRVeN.pro35Wfly4z.pro300N0DVx.profBy8oj9g",
+ ))),
+ Event::Trigger(Trigger::SendKeys(
+ By::Css("input.focusable-form-field.pro3g2JlS3A.pro284gg8sY"),
+ "1234",
+ )),
+ ],
+ ),
+ Event::Trigger(Trigger::Click(By::Css(
+ "button.sc-aXZVg.fiBhTR.sc-gEkIjz.lfdPCG.pro35Wfly4z.pro4JEtdJCo.profBy8oj9g",
+ ))),
+ Event::Trigger(Trigger::Click(By::Css(
+ "div.proXxAyyoTg.pro1jhMLxqa.pro3Q3lI-I9",
+ ))),
+ Event::Trigger(Trigger::Click(By::Css(
+ "button.sc-aXZVg.gCRVeN.pro35Wfly4z.pro300N0DVx.pro3JiyGdDb.pro1Ss7c7oj",
+ ))),
+ 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",
+ ))),
+ ];
+ affirm_actions.extend(actions);
+ self.complete_actions(&driver, affirm_actions).await
+ }
async fn make_paypal_payment(
&self,
web_driver: WebDriver,
diff --git a/crates/router/tests/connectors/stripe_ui.rs b/crates/router/tests/connectors/stripe_ui.rs
index 81087ae5ee5..f8a1cdc6b77 100644
--- a/crates/router/tests/connectors/stripe_ui.rs
+++ b/crates/router/tests/connectors/stripe_ui.rs
@@ -380,6 +380,19 @@ async fn should_make_stripe_sepa_bank_debit_payment(c: WebDriver) -> Result<(),
Ok(())
}
+async fn should_make_stripe_affirm_paylater_payment(
+ driver: WebDriver,
+) -> Result<(), WebDriverError> {
+ let conn = StripeSeleniumTest {};
+ conn.make_affirm_payment(
+ driver,
+ &format!("{CHEKOUT_BASE_URL}/saved/110"),
+ vec![Event::Assert(Assert::IsPresent("succeeded"))],
+ )
+ .await?;
+ Ok(())
+}
+
#[test]
#[serial]
fn should_make_3ds_payment_test() {
@@ -483,3 +496,9 @@ fn should_make_stripe_ach_bank_debit_payment_test() {
fn should_make_stripe_sepa_bank_debit_payment_test() {
tester!(should_make_stripe_sepa_bank_debit_payment);
}
+
+#[test]
+#[serial]
+fn should_make_stripe_affirm_paylater_payment_test() {
+ tester!(should_make_stripe_affirm_paylater_payment);
+}
|
test
|
[stripe] Add ui test for affirm (#1694)
|
b4e77170559d5912758f18d2db46bf25eb5277b2
|
2024-08-01 16:34:31
|
Kashif
|
fix(open_payment_links): send displaySavedPaymentMethods as false explicitly for open payment links (#5501)
| false
|
diff --git a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
index 6269b3546af..71f0875f42e 100644
--- a/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
+++ b/crates/router/src/core/payment_link/payment_link_initiate/payment_link_initiator.js
@@ -41,6 +41,7 @@ function initializeSDK() {
var unifiedCheckoutOptions = {
displaySavedPaymentMethodsCheckbox: false,
+ displaySavedPaymentMethods: false,
layout: {
type: type, //accordion , tabs, spaced accordion
spacedAccordionItems: paymentDetails.sdk_layout === "spaced_accordion",
|
fix
|
send displaySavedPaymentMethods as false explicitly for open payment links (#5501)
|
ba2efac4fa2af22f81b0841350a334bc36e91022
|
2023-10-07 23:26:28
|
Nabeel Hussain M N
|
feat(connector): [Multisafepay] Use transaction_id as reference to transaction (#2451)
| false
|
diff --git a/crates/router/src/connector/multisafepay/transformers.rs b/crates/router/src/connector/multisafepay/transformers.rs
index 2fa8a4c9030..dfc7bad277d 100644
--- a/crates/router/src/connector/multisafepay/transformers.rs
+++ b/crates/router/src/connector/multisafepay/transformers.rs
@@ -530,7 +530,9 @@ impl<F, T>
Ok(Self {
status: enums::AttemptStatus::from(status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
- resource_id: types::ResponseId::ConnectorTransactionId(item.response.data.order_id),
+ resource_id: types::ResponseId::ConnectorTransactionId(
+ item.response.data.order_id.clone(),
+ ),
redirection_data,
mandate_reference: item
.response
@@ -543,7 +545,7 @@ impl<F, T>
}),
connector_metadata: None,
network_txn_id: None,
- connector_response_reference_id: None,
+ connector_response_reference_id: Some(item.response.data.order_id.clone()),
}),
..item.data
})
|
feat
|
[Multisafepay] Use transaction_id as reference to transaction (#2451)
|
d2968c94978a57422fa46a8195d906736a95b864
|
2023-11-13 22:19:37
|
Sai Harsha Vardhan
|
feat(router): add automatic retries and step up 3ds flow (#2834)
| false
|
diff --git a/crates/router/Cargo.toml b/crates/router/Cargo.toml
index 5e8cb7a7297..4d9c315a10b 100644
--- a/crates/router/Cargo.toml
+++ b/crates/router/Cargo.toml
@@ -9,7 +9,7 @@ readme = "README.md"
license.workspace = true
[features]
-default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "profile_specific_fallback_routing"]
+default = ["kv_store", "stripe", "oltp", "olap", "backwards_compatibility", "accounts_cache", "dummy_connector", "payouts", "profile_specific_fallback_routing", "retry"]
s3 = ["dep:aws-sdk-s3", "dep:aws-config"]
kms = ["external_services/kms", "dep:aws-config"]
email = ["external_services/email", "dep:aws-config"]
@@ -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 = []
-
+retry = []
[dependencies]
actix-cors = "0.6.4"
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index a114b20380b..5c8089271bd 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -3,6 +3,8 @@ pub mod customers;
pub mod flows;
pub mod helpers;
pub mod operations;
+#[cfg(feature = "retry")]
+pub mod retry;
pub mod routing;
pub mod tokenization;
pub mod transformers;
@@ -231,7 +233,7 @@ where
state,
&merchant_account,
&key_store,
- connector_data,
+ connector_data.clone(),
&operation,
&mut payment_data,
&customer,
@@ -242,6 +244,33 @@ where
)
.await?;
+ #[cfg(feature = "retry")]
+ let mut router_data = router_data;
+ #[cfg(feature = "retry")]
+ {
+ use crate::core::payments::retry::{self, GsmValidation};
+ let config_bool =
+ retry::config_should_call_gsm(&*state.store, &merchant_account.merchant_id)
+ .await;
+
+ if config_bool && router_data.should_call_gsm() {
+ router_data = retry::do_gsm_actions(
+ state,
+ &mut payment_data,
+ connectors,
+ connector_data,
+ router_data,
+ &merchant_account,
+ &key_store,
+ &operation,
+ &customer,
+ &validate_result,
+ schedule_time,
+ )
+ .await?;
+ };
+ }
+
let operation = Box::new(PaymentResponse);
let db = &*state.store;
connector_http_status_code = router_data.connector_http_status_code;
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
new file mode 100644
index 00000000000..f58e9ea298f
--- /dev/null
+++ b/crates/router/src/core/payments/retry.rs
@@ -0,0 +1,579 @@
+use std::{str::FromStr, vec::IntoIter};
+
+use diesel_models::enums as storage_enums;
+use error_stack::{IntoReport, ResultExt};
+use router_env::{
+ logger,
+ tracing::{self, instrument},
+};
+
+use crate::{
+ core::{
+ errors::{self, RouterResult, StorageErrorExt},
+ payment_methods::PaymentMethodRetrieve,
+ payments::{
+ self,
+ flows::{ConstructFlowSpecificData, Feature},
+ operations,
+ },
+ },
+ db::StorageInterface,
+ routes,
+ routes::{app, metrics},
+ services::{self, RedirectForm},
+ types,
+ types::{api, domain, storage},
+ utils,
+};
+
+#[instrument(skip_all)]
+#[allow(clippy::too_many_arguments)]
+pub async fn do_gsm_actions<F, ApiRequest, FData, Ctx>(
+ state: &app::AppState,
+ payment_data: &mut payments::PaymentData<F>,
+ mut connectors: IntoIter<api::ConnectorData>,
+ original_connector_data: api::ConnectorData,
+ mut router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+ operation: &operations::BoxedOperation<'_, F, ApiRequest, Ctx>,
+ customer: &Option<domain::Customer>,
+ validate_result: &operations::ValidateResult<'_>,
+ schedule_time: Option<time::PrimitiveDateTime>,
+) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
+where
+ F: Clone + Send + Sync,
+ FData: Send + Sync,
+ payments::PaymentResponse: operations::Operation<F, FData, Ctx>,
+
+ payments::PaymentData<F>: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
+ types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
+ dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>,
+ Ctx: PaymentMethodRetrieve,
+{
+ let mut retries = None;
+
+ metrics::AUTO_RETRY_ELIGIBLE_REQUEST_COUNT.add(&metrics::CONTEXT, 1, &[]);
+
+ let mut initial_gsm = get_gsm(state, &router_data).await;
+
+ //Check if step-up to threeDS is possible and merchant has enabled
+ let step_up_possible = initial_gsm
+ .clone()
+ .map(|gsm| gsm.step_up_possible)
+ .unwrap_or(false);
+ let is_no_three_ds_payment = matches!(
+ payment_data.payment_attempt.authentication_type,
+ Some(storage_enums::AuthenticationType::NoThreeDs)
+ );
+ let should_step_up = if step_up_possible && is_no_three_ds_payment {
+ is_step_up_enabled_for_merchant_connector(
+ state,
+ &merchant_account.merchant_id,
+ original_connector_data.connector_name,
+ )
+ .await
+ } else {
+ false
+ };
+
+ if should_step_up {
+ router_data = do_retry(
+ &state.clone(),
+ original_connector_data,
+ operation,
+ customer,
+ merchant_account,
+ key_store,
+ payment_data,
+ router_data,
+ validate_result,
+ schedule_time,
+ true,
+ )
+ .await?;
+ }
+ // Step up is not applicable so proceed with auto retries flow
+ else {
+ loop {
+ // Use initial_gsm for first time alone
+ let gsm = match initial_gsm.as_ref() {
+ Some(gsm) => Some(gsm.clone()),
+ None => get_gsm(state, &router_data).await,
+ };
+
+ match get_gsm_decision(gsm) {
+ api_models::gsm::GsmDecision::Retry => {
+ retries = get_retries(state, retries, &merchant_account.merchant_id).await;
+
+ if retries.is_none() || retries == Some(0) {
+ metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(&metrics::CONTEXT, 1, &[]);
+ logger::info!("retries exhausted for auto_retry payment");
+ break;
+ }
+
+ if connectors.len() == 0 {
+ logger::info!("connectors exhausted for auto_retry payment");
+ metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(&metrics::CONTEXT, 1, &[]);
+ break;
+ }
+
+ let connector = super::get_connector_data(&mut connectors)?;
+
+ router_data = do_retry(
+ &state.clone(),
+ connector,
+ operation,
+ customer,
+ merchant_account,
+ key_store,
+ payment_data,
+ router_data,
+ validate_result,
+ schedule_time,
+ //this is an auto retry payment, but not step-up
+ false,
+ )
+ .await?;
+
+ retries = retries.map(|i| i - 1);
+ }
+ api_models::gsm::GsmDecision::Requeue => {
+ Err(errors::ApiErrorResponse::NotImplemented {
+ message: errors::api_error_response::NotImplementedMessage::Reason(
+ "Requeue not implemented".to_string(),
+ ),
+ })
+ .into_report()?
+ }
+ api_models::gsm::GsmDecision::DoDefault => break,
+ }
+ initial_gsm = None;
+ }
+ }
+ Ok(router_data)
+}
+
+#[instrument(skip_all)]
+pub async fn is_step_up_enabled_for_merchant_connector(
+ state: &app::AppState,
+ merchant_id: &str,
+ connector_name: types::Connector,
+) -> bool {
+ let key = format!("step_up_enabled_{merchant_id}");
+ let db = &*state.store;
+ db.find_config_by_key_unwrap_or(key.as_str(), Some("[]".to_string()))
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .and_then(|step_up_config| {
+ serde_json::from_str::<Vec<types::Connector>>(&step_up_config.config)
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Step-up config parsing failed")
+ })
+ .map_err(|err| {
+ logger::error!(step_up_config_error=?err);
+ })
+ .ok()
+ .map(|connectors_enabled| connectors_enabled.contains(&connector_name))
+ .unwrap_or(false)
+}
+
+#[instrument(skip_all)]
+pub async fn get_retries(
+ state: &app::AppState,
+ retries: Option<i32>,
+ merchant_id: &str,
+) -> Option<i32> {
+ match retries {
+ Some(retries) => Some(retries),
+ None => {
+ let key = format!("max_auto_retries_enabled_{merchant_id}");
+ let db = &*state.store;
+ db.find_config_by_key(key.as_str())
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .and_then(|retries_config| {
+ retries_config
+ .config
+ .parse::<i32>()
+ .into_report()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Retries config parsing failed")
+ })
+ .map_err(|err| {
+ logger::error!(retries_error=?err);
+ None::<i32>
+ })
+ .ok()
+ }
+ }
+}
+
+#[instrument(skip_all)]
+pub async fn get_gsm<F, FData>(
+ state: &app::AppState,
+ router_data: &types::RouterData<F, FData, types::PaymentsResponseData>,
+) -> Option<storage::gsm::GatewayStatusMap> {
+ let error_response = router_data.response.as_ref().err();
+ let error_code = error_response.map(|err| err.code.to_owned());
+ let error_message = error_response.map(|err| err.message.to_owned());
+ let get_gsm = || async {
+ let connector_name = router_data.connector.to_string();
+ let flow = get_flow_name::<F>()?;
+ state.store.find_gsm_rule(
+ connector_name.clone(),
+ flow.clone(),
+ "sub_flow".to_string(),
+ error_code.clone().unwrap_or_default(), // TODO: make changes in connector to get a mandatory code in case of success or error response
+ error_message.clone().unwrap_or_default(),
+ )
+ .await
+ .map_err(|err| {
+ if err.current_context().is_db_not_found() {
+ logger::warn!(
+ "GSM miss for connector - {}, flow - {}, error_code - {:?}, error_message - {:?}",
+ connector_name,
+ flow,
+ error_code,
+ error_message
+ );
+ metrics::AUTO_RETRY_GSM_MISS_COUNT.add(&metrics::CONTEXT, 1, &[]);
+ } else {
+ metrics::AUTO_RETRY_GSM_FETCH_FAILURE_COUNT.add(&metrics::CONTEXT, 1, &[]);
+ };
+ err.change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("failed to fetch decision from gsm")
+ })
+ };
+ get_gsm()
+ .await
+ .map_err(|err| {
+ // warn log should suffice here because we are not propagating this error
+ logger::warn!(get_gsm_decision_fetch_error=?err, "error fetching gsm decision");
+ err
+ })
+ .ok()
+}
+
+#[instrument(skip_all)]
+pub fn get_gsm_decision(
+ option_gsm: Option<storage::gsm::GatewayStatusMap>,
+) -> api_models::gsm::GsmDecision {
+ let option_gsm_decision = option_gsm
+ .and_then(|gsm| {
+ api_models::gsm::GsmDecision::from_str(gsm.decision.as_str())
+ .into_report()
+ .map_err(|err| {
+ let api_error = err.change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("gsm decision parsing failed");
+ logger::warn!(get_gsm_decision_parse_error=?api_error, "error fetching gsm decision");
+ api_error
+ })
+ .ok()
+ });
+
+ if option_gsm_decision.is_some() {
+ metrics::AUTO_RETRY_GSM_MATCH_COUNT.add(&metrics::CONTEXT, 1, &[]);
+ }
+ option_gsm_decision.unwrap_or_default()
+}
+
+#[inline]
+fn get_flow_name<F>() -> RouterResult<String> {
+ Ok(std::any::type_name::<F>()
+ .to_string()
+ .rsplit("::")
+ .next()
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable("Flow stringify failed")?
+ .to_string())
+}
+
+#[allow(clippy::too_many_arguments)]
+#[instrument(skip_all)]
+pub async fn do_retry<F, ApiRequest, FData, Ctx>(
+ state: &routes::AppState,
+ connector: api::ConnectorData,
+ operation: &operations::BoxedOperation<'_, F, ApiRequest, Ctx>,
+ customer: &Option<domain::Customer>,
+ merchant_account: &domain::MerchantAccount,
+ key_store: &domain::MerchantKeyStore,
+ payment_data: &mut payments::PaymentData<F>,
+ router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
+ validate_result: &operations::ValidateResult<'_>,
+ schedule_time: Option<time::PrimitiveDateTime>,
+ is_step_up: bool,
+) -> RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
+where
+ F: Clone + Send + Sync,
+ FData: Send + Sync,
+ payments::PaymentResponse: operations::Operation<F, FData, Ctx>,
+
+ payments::PaymentData<F>: ConstructFlowSpecificData<F, FData, types::PaymentsResponseData>,
+ types::RouterData<F, FData, types::PaymentsResponseData>: Feature<F, FData>,
+ dyn api::Connector: services::api::ConnectorIntegration<F, FData, types::PaymentsResponseData>,
+ Ctx: PaymentMethodRetrieve,
+{
+ metrics::AUTO_RETRY_PAYMENT_COUNT.add(&metrics::CONTEXT, 1, &[]);
+
+ modify_trackers(
+ state,
+ connector.connector_name.to_string(),
+ payment_data,
+ merchant_account.storage_scheme,
+ router_data,
+ is_step_up,
+ )
+ .await?;
+
+ payments::call_connector_service(
+ state,
+ merchant_account,
+ key_store,
+ connector,
+ operation,
+ payment_data,
+ customer,
+ payments::CallConnectorAction::Trigger,
+ validate_result,
+ schedule_time,
+ api::HeaderPayload::default(),
+ )
+ .await
+}
+
+#[instrument(skip_all)]
+pub async fn modify_trackers<F, FData>(
+ state: &routes::AppState,
+ connector: String,
+ payment_data: &mut payments::PaymentData<F>,
+ storage_scheme: storage_enums::MerchantStorageScheme,
+ router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
+ is_step_up: bool,
+) -> RouterResult<()>
+where
+ F: Clone + Send,
+ FData: Send,
+{
+ let new_attempt_count = payment_data.payment_intent.attempt_count + 1;
+ let new_payment_attempt = make_new_payment_attempt(
+ connector,
+ payment_data.payment_attempt.clone(),
+ new_attempt_count,
+ is_step_up,
+ );
+
+ let db = &*state.store;
+
+ match router_data.response {
+ Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id,
+ connector_metadata,
+ redirection_data,
+ ..
+ }) => {
+ let encoded_data = payment_data.payment_attempt.encoded_data.clone();
+
+ let authentication_data = redirection_data
+ .map(|data| utils::Encode::<RedirectForm>::encode_to_value(&data))
+ .transpose()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Could not parse the connector response")?;
+
+ db.update_payment_attempt_with_attempt_id(
+ payment_data.payment_attempt.clone(),
+ storage::PaymentAttemptUpdate::ResponseUpdate {
+ status: router_data.status,
+ connector: None,
+ connector_transaction_id: match resource_id {
+ types::ResponseId::NoResponseId => None,
+ types::ResponseId::ConnectorTransactionId(id)
+ | types::ResponseId::EncodedData(id) => Some(id),
+ },
+ connector_response_reference_id: payment_data
+ .payment_attempt
+ .connector_response_reference_id
+ .clone(),
+ authentication_type: None,
+ payment_method_id: Some(router_data.payment_method_id),
+ mandate_id: payment_data
+ .mandate_id
+ .clone()
+ .map(|mandate| mandate.mandate_id),
+ connector_metadata,
+ payment_token: None,
+ error_code: None,
+ error_message: None,
+ error_reason: None,
+ amount_capturable: if router_data.status.is_terminal_status() {
+ Some(0)
+ } else {
+ None
+ },
+ updated_by: storage_scheme.to_string(),
+ authentication_data,
+ encoded_data,
+ },
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ }
+ Ok(_) => {
+ logger::error!("unexpected response: this response was not expected in Retry flow");
+ return Ok(());
+ }
+ Err(error_response) => {
+ db.update_payment_attempt_with_attempt_id(
+ payment_data.payment_attempt.clone(),
+ storage::PaymentAttemptUpdate::ErrorUpdate {
+ connector: None,
+ error_code: Some(Some(error_response.code)),
+ error_message: Some(Some(error_response.message)),
+ status: storage_enums::AttemptStatus::Failure,
+ error_reason: Some(error_response.reason),
+ amount_capturable: Some(0),
+ updated_by: storage_scheme.to_string(),
+ },
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+ }
+ }
+
+ let payment_attempt = db
+ .insert_payment_attempt(new_payment_attempt, storage_scheme)
+ .await
+ .to_duplicate_response(errors::ApiErrorResponse::DuplicatePayment {
+ payment_id: payment_data.payment_intent.payment_id.clone(),
+ })?;
+
+ // update payment_attempt, connector_response and payment_intent in payment_data
+ payment_data.payment_attempt = payment_attempt;
+
+ payment_data.payment_intent = db
+ .update_payment_intent(
+ payment_data.payment_intent.clone(),
+ storage::PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate {
+ active_attempt_id: payment_data.payment_attempt.attempt_id.clone(),
+ attempt_count: new_attempt_count,
+ updated_by: storage_scheme.to_string(),
+ },
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
+
+ Ok(())
+}
+
+#[instrument(skip_all)]
+pub fn make_new_payment_attempt(
+ connector: String,
+ old_payment_attempt: storage::PaymentAttempt,
+ new_attempt_count: i16,
+ is_step_up: bool,
+) -> storage::PaymentAttemptNew {
+ let created_at @ modified_at @ last_synced = Some(common_utils::date_time::now());
+ storage::PaymentAttemptNew {
+ connector: Some(connector),
+ attempt_id: utils::get_payment_attempt_id(
+ &old_payment_attempt.payment_id,
+ new_attempt_count,
+ ),
+ payment_id: old_payment_attempt.payment_id,
+ merchant_id: old_payment_attempt.merchant_id,
+ status: old_payment_attempt.status,
+ amount: old_payment_attempt.amount,
+ currency: old_payment_attempt.currency,
+ save_to_locker: old_payment_attempt.save_to_locker,
+
+ offer_amount: old_payment_attempt.offer_amount,
+ surcharge_amount: old_payment_attempt.surcharge_amount,
+ tax_amount: old_payment_attempt.tax_amount,
+ payment_method_id: old_payment_attempt.payment_method_id,
+ payment_method: old_payment_attempt.payment_method,
+ payment_method_type: old_payment_attempt.payment_method_type,
+ capture_method: old_payment_attempt.capture_method,
+ capture_on: old_payment_attempt.capture_on,
+ confirm: old_payment_attempt.confirm,
+ authentication_type: if is_step_up {
+ Some(storage_enums::AuthenticationType::ThreeDs)
+ } else {
+ old_payment_attempt.authentication_type
+ },
+
+ amount_to_capture: old_payment_attempt.amount_to_capture,
+ mandate_id: old_payment_attempt.mandate_id,
+ browser_info: old_payment_attempt.browser_info,
+ payment_token: old_payment_attempt.payment_token,
+
+ created_at,
+ modified_at,
+ last_synced,
+ ..storage::PaymentAttemptNew::default()
+ }
+}
+
+pub async fn config_should_call_gsm(db: &dyn StorageInterface, merchant_id: &String) -> bool {
+ let config = db
+ .find_config_by_key_unwrap_or(
+ format!("should_call_gsm_{}", merchant_id).as_str(),
+ Some("false".to_string()),
+ )
+ .await;
+ match config {
+ Ok(conf) => conf.config == "true",
+ Err(err) => {
+ logger::error!("{err}");
+ false
+ }
+ }
+}
+
+pub trait GsmValidation<F: Send + Clone + Sync, FData: Send + Sync, Resp> {
+ // TODO : move this function to appropriate place later.
+ fn should_call_gsm(&self) -> bool;
+}
+
+impl<F: Send + Clone + Sync, FData: Send + Sync>
+ GsmValidation<F, FData, types::PaymentsResponseData>
+ for types::RouterData<F, FData, types::PaymentsResponseData>
+{
+ #[inline(always)]
+ fn should_call_gsm(&self) -> bool {
+ if self.response.is_err() {
+ true
+ } else {
+ match self.status {
+ storage_enums::AttemptStatus::Started
+ | storage_enums::AttemptStatus::AuthenticationPending
+ | storage_enums::AttemptStatus::AuthenticationSuccessful
+ | storage_enums::AttemptStatus::Authorized
+ | storage_enums::AttemptStatus::Charged
+ | storage_enums::AttemptStatus::Authorizing
+ | storage_enums::AttemptStatus::CodInitiated
+ | storage_enums::AttemptStatus::Voided
+ | storage_enums::AttemptStatus::VoidInitiated
+ | storage_enums::AttemptStatus::CaptureInitiated
+ | storage_enums::AttemptStatus::RouterDeclined
+ | storage_enums::AttemptStatus::VoidFailed
+ | storage_enums::AttemptStatus::AutoRefunded
+ | storage_enums::AttemptStatus::CaptureFailed
+ | storage_enums::AttemptStatus::PartialCharged
+ | storage_enums::AttemptStatus::Pending
+ | storage_enums::AttemptStatus::PaymentMethodAwaited
+ | storage_enums::AttemptStatus::ConfirmationAwaited
+ | storage_enums::AttemptStatus::Unresolved
+ | storage_enums::AttemptStatus::DeviceDataCollectionPending => false,
+
+ storage_enums::AttemptStatus::AuthenticationFailed
+ | storage_enums::AttemptStatus::AuthorizationFailed
+ | storage_enums::AttemptStatus::Failure => true,
+ }
+ }
+ }
+}
diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rs
index 34d818eaa39..a8e6f9d2a89 100644
--- a/crates/router/src/routes/metrics.rs
+++ b/crates/router/src/routes/metrics.rs
@@ -102,5 +102,13 @@ counter_metric!(APPLE_PAY_SIMPLIFIED_FLOW_SUCCESSFUL_PAYMENT, GLOBAL_METER);
counter_metric!(APPLE_PAY_MANUAL_FLOW_FAILED_PAYMENT, GLOBAL_METER);
counter_metric!(APPLE_PAY_SIMPLIFIED_FLOW_FAILED_PAYMENT, GLOBAL_METER);
+// Metrics for Auto Retries
+counter_metric!(AUTO_RETRY_ELIGIBLE_REQUEST_COUNT, GLOBAL_METER);
+counter_metric!(AUTO_RETRY_GSM_MISS_COUNT, GLOBAL_METER);
+counter_metric!(AUTO_RETRY_GSM_FETCH_FAILURE_COUNT, GLOBAL_METER);
+counter_metric!(AUTO_RETRY_GSM_MATCH_COUNT, GLOBAL_METER);
+counter_metric!(AUTO_RETRY_EXHAUSTED_COUNT, GLOBAL_METER);
+counter_metric!(AUTO_RETRY_PAYMENT_COUNT, GLOBAL_METER);
+
pub mod request;
pub mod utils;
|
feat
|
add automatic retries and step up 3ds flow (#2834)
|
9f0d8efa8dad45a773f4cab6978288f2209e4abf
|
2024-12-10 16:51:12
|
Prasunna Soppa
|
fix(core): add validation to check if routable connector supports network tokenization in CIT repeat flow (#6749)
| false
|
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 53ec0129896..041fb52091b 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -588,6 +588,7 @@ pub async fn retrieve_payment_method_with_token(
mandate_id,
payment_method_info,
business_profile,
+ payment_attempt.connector.clone(),
)
.await
.map(|card| Some((card, enums::PaymentMethod::Card)))?
@@ -622,6 +623,7 @@ pub async fn retrieve_payment_method_with_token(
mandate_id,
payment_method_info,
business_profile,
+ payment_attempt.connector.clone(),
)
.await
.map(|card| Some((card, enums::PaymentMethod::Card)))?
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 01bac9a2124..923f6d24fe8 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -1916,6 +1916,7 @@ pub async fn retrieve_card_with_permanent_token(
mandate_id: Option<api_models::payments::MandateIds>,
payment_method_info: Option<domain::PaymentMethod>,
business_profile: &domain::Profile,
+ connector: Option<String>,
) -> RouterResult<domain::PaymentMethodData> {
let customer_id = payment_intent
.customer_id
@@ -1986,7 +1987,28 @@ pub async fn retrieve_card_with_permanent_token(
.attach_printable("Payment method data is not present"),
(Some(ref pm_data), None) => {
// Regular (non-mandate) Payment flow
- if let Some(token_ref) = pm_data.network_token_requestor_reference_id.clone() {
+ let network_tokenization_supported_connectors = &state
+ .conf
+ .network_tokenization_supported_connectors
+ .connector_list;
+ let connector_variant = connector
+ .as_ref()
+ .map(|conn| {
+ api_enums::Connector::from_str(conn.as_str())
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "connector",
+ })
+ .attach_printable_lazy(|| {
+ format!("unable to parse connector name {connector:?}")
+ })
+ })
+ .transpose()?;
+ if let (Some(_conn), Some(token_ref)) = (
+ connector_variant
+ .filter(|conn| network_tokenization_supported_connectors.contains(conn)),
+ pm_data.network_token_requestor_reference_id.clone(),
+ ) {
+ logger::info!("Fetching network token data from tokenization service");
match network_tokenization::get_token_from_tokenization_service(
state, token_ref, pm_data,
)
@@ -2016,6 +2038,8 @@ pub async fn retrieve_card_with_permanent_token(
}
}
} else {
+ logger::info!("Either the connector is not in the NT supported list or token requestor reference ID is absent");
+ logger::info!("Falling back to fetch card details from locker");
fetch_card_details_from_locker(
state,
customer_id,
@@ -5773,6 +5797,7 @@ pub async fn get_payment_method_details_from_payment_token(
None,
None,
business_profile,
+ payment_attempt.connector.clone(),
)
.await
.map(|card| Some((card, enums::PaymentMethod::Card))),
@@ -5791,6 +5816,7 @@ pub async fn get_payment_method_details_from_payment_token(
None,
None,
business_profile,
+ payment_attempt.connector.clone(),
)
.await
.map(|card| Some((card, enums::PaymentMethod::Card))),
|
fix
|
add validation to check if routable connector supports network tokenization in CIT repeat flow (#6749)
|
1e45bb5d0f58047987cd98a063b5ffa770750423
|
2024-02-19 21:20:09
|
Swangi Kumari
|
feat(connector-config): [Volt] Add config changes for open_banking_uk (#3700)
| false
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 611c581a3df..1a132933433 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -445,7 +445,7 @@ pay_easy = { country = "JP", currency = "JPY" }
boleto = { country = "BR", currency = "BRL" }
[pm_filters.volt]
-open_banking_uk = {country = "DE,GB", currency = "EUR,GBP"}
+open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
[pm_filters.zen]
credit = { not_available_flows = { capture_method = "manual" } }
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index 70975b8cdbd..dba591ae679 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -248,7 +248,7 @@ klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,C
sofort = { country = "AT,BE,DE,IT,NL,ES", currency = "EUR" }
[pm_filters.volt]
-open_banking_uk = {country = "DE,GB", currency = "EUR,GBP"}
+open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
[pm_filters.worldpay]
apple_pay.country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US"
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index acd3935a746..48bb9d33e3f 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -263,7 +263,7 @@ klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,C
sofort = { country = "AT,BE,DE,IT,NL,ES", currency = "EUR" }
[pm_filters.volt]
-open_banking_uk = {country = "DE,GB", currency = "EUR,GBP"}
+open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
[pm_filters.worldpay]
apple_pay.country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US"
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 564a2d9e984..8723f871c34 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -264,7 +264,7 @@ klarna = { country = "AU,AT,BE,CA,CZ,DK,FI,FR,DE,GR,IE,IT,NL,NZ,NO,PL,PT,ES,SE,C
sofort = { country = "AT,BE,DE,IT,NL,ES", currency = "EUR" }
[pm_filters.volt]
-open_banking_uk = {country = "DE,GB", currency = "EUR,GBP"}
+open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
[pm_filters.worldpay]
apple_pay.country = "AU,CN,HK,JP,MO,MY,NZ,SG,TW,AM,AT,AZ,BY,BE,BG,HR,CY,CZ,DK,EE,FO,FI,FR,GE,DE,GR,GL,GG,HU,IS,IE,IM,IT,KZ,JE,LV,LI,LT,LU,MT,MD,MC,ME,NL,NO,PL,PT,RO,SM,RS,SK,SI,ES,SE,CH,UA,GB,AR,CO,CR,BR,MX,PE,BH,IL,JO,KW,PS,QA,SA,AE,CA,UM,US"
diff --git a/config/development.toml b/config/development.toml
index 5eef33eafd9..d69719bd419 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -304,7 +304,7 @@ ideal = { country = "NL", currency = "EUR" }
cashapp = { country = "US", currency = "USD" }
[pm_filters.volt]
-open_banking_uk = {country = "DE,GB", currency = "EUR,GBP"}
+open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
[pm_filters.adyen]
google_pay = { country = "AU,NZ,JP,HK,SG,MY,TH,VN,BH,AE,KW,BR,ES,GB,SE,NO,SK,AT,NL,DE,HU,CY,LU,CH,BE,FR,DK,RO,HR,LI,MT,SI,GR,PT,IE,CZ,EE,LT,LV,IT,PL,TR,IS,CA,US", currency = "AED,ALL,AMD,ANG,AOA,ARS,AUD,AWG,AZN,BAM,BBD,BDT,BGN,BHD,BMD,BND,BOB,BRL,BSD,BWP,BYN,BZD,CAD,CHF,CLP,CNY,COP,CRC,CUP,CVE,CZK,DJF,DKK,DOP,DZD,EGP,ETB,EUR,FJD,FKP,GBP,GEL,GHS,GIP,GMD,GNF,GTQ,GYD,HKD,HNL,HTG,HUF,IDR,ILS,INR,IQD,JMD,JOD,JPY,KES,KGS,KHR,KMF,KRW,KWD,KYD,KZT,LAK,LBP,LKR,LYD,MAD,MDL,MKD,MMK,MNT,MOP,MRU,MUR,MVR,MWK,MXN,MYR,MZN,NAD,NGN,NIO,NOK,NPR,NZD,OMR,PAB,PEN,PGK,PHP,PKR,PLN,PYG,QAR,RON,RSD,RUB,RWF,SAR,SBD,SCR,SEK,SGD,SHP,SLE,SOS,SRD,STN,SVC,SZL,THB,TND,TOP,TRY,TTD,TWD,TZS,UAH,UGX,USD,UYU,UZS,VES,VND,VUV,WST,XAF,XCD,XOF,XPF,YER,ZAR,ZMW" }
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 178788677e5..3f7c64624fa 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -307,7 +307,7 @@ pay_easy = {country = "JP", currency = "JPY"}
boleto = { country = "BR", currency = "BRL" }
[pm_filters.volt]
-open_banking_uk = {country = "DE,GB", currency = "EUR,GBP"}
+open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
[pm_filters.zen]
credit = { not_available_flows = { capture_method = "manual" } }
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index d9b5433ab6e..2f35958ae6d 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -187,7 +187,7 @@ cards = [
]
[pm_filters.volt]
-open_banking_uk = {country = "DE,GB", currency = "EUR,GBP"}
+open_banking_uk = {country = "DE,GB,AT,BE,CY,EE,ES,FI,FR,GR,HR,IE,IT,LT,LU,LV,MT,NL,PT,SI,SK,BG,CZ,DK,HU,NO,PL,RO,SE,AU,BR", currency = "EUR,GBP,DKK,NOK,PLN,SEK,AUD,BRL"}
[pm_filters.adyen]
boleto = { country = "BR", currency = "BRL" }
|
feat
|
[Volt] Add config changes for open_banking_uk (#3700)
|
76cb15e01de748f9328d57968d6ddee9831720aa
|
2023-06-19 17:39:21
|
Pa1NarK
|
fix(core): save payment_method_type when creating a record in the payment_method table (#1378)
| false
|
diff --git a/crates/router/src/core/payments/flows/authorize_flow.rs b/crates/router/src/core/payments/flows/authorize_flow.rs
index 49d30f6e87e..36d40d7480e 100644
--- a/crates/router/src/core/payments/flows/authorize_flow.rs
+++ b/crates/router/src/core/payments/flows/authorize_flow.rs
@@ -84,6 +84,7 @@ impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAu
resp.to_owned(),
maybe_customer,
merchant_account,
+ self.request.payment_method_type.clone(),
)
.await?;
diff --git a/crates/router/src/core/payments/flows/verify_flow.rs b/crates/router/src/core/payments/flows/verify_flow.rs
index 274ad4fcdc0..a70e4419b33 100644
--- a/crates/router/src/core/payments/flows/verify_flow.rs
+++ b/crates/router/src/core/payments/flows/verify_flow.rs
@@ -67,6 +67,7 @@ impl Feature<api::Verify, types::VerifyRequestData> for types::VerifyRouterData
resp.to_owned(),
maybe_customer,
merchant_account,
+ self.request.payment_method_type.clone(),
)
.await?;
@@ -177,12 +178,14 @@ impl types::VerifyRouterData {
.await
.to_verify_failed_response()?;
+ let payment_method_type = self.request.payment_method_type.clone();
let pm_id = tokenization::save_payment_method(
state,
connector,
resp.to_owned(),
maybe_customer,
merchant_account,
+ payment_method_type,
)
.await?;
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 6d6017f6f81..b29d89a3811 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -729,13 +729,14 @@ where
#[instrument(skip_all)]
pub(crate) async fn get_payment_method_create_request(
- payment_method: Option<&api::PaymentMethodData>,
- payment_method_type: Option<storage_enums::PaymentMethod>,
+ payment_method_data: Option<&api::PaymentMethodData>,
+ payment_method: Option<storage_enums::PaymentMethod>,
+ payment_method_type: Option<storage_enums::PaymentMethodType>,
customer: &domain::Customer,
) -> RouterResult<api::PaymentMethodCreate> {
- match payment_method {
- Some(pm_data) => match payment_method_type {
- Some(payment_method_type) => match pm_data {
+ match payment_method_data {
+ Some(pm_data) => match payment_method {
+ Some(payment_method) => match pm_data {
api::PaymentMethodData::Card(card) => {
let card_detail = api::CardDetail {
card_number: card.card_number.clone(),
@@ -745,8 +746,8 @@ pub(crate) async fn get_payment_method_create_request(
};
let customer_id = customer.customer_id.clone();
let payment_method_request = api::PaymentMethodCreate {
- payment_method: payment_method_type.foreign_into(),
- payment_method_type: None,
+ payment_method: payment_method.foreign_into(),
+ payment_method_type: payment_method_type.map(ForeignInto::foreign_into),
payment_method_issuer: card.card_issuer.clone(),
payment_method_issuer_code: None,
card: Some(card_detail),
@@ -761,8 +762,8 @@ pub(crate) async fn get_payment_method_create_request(
}
_ => {
let payment_method_request = api::PaymentMethodCreate {
- payment_method: payment_method_type.foreign_into(),
- payment_method_type: None,
+ payment_method: payment_method.foreign_into(),
+ payment_method_type: payment_method_type.map(ForeignInto::foreign_into),
payment_method_issuer: None,
payment_method_issuer_code: None,
card: None,
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index b60d9a68aa4..6cf6cbb28bb 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -15,6 +15,7 @@ use crate::{
self,
api::{self, PaymentMethodCreateExt},
domain,
+ storage::enums as storage_enums,
},
utils::OptionExt,
};
@@ -25,6 +26,7 @@ pub async fn save_payment_method<F: Clone, FData>(
resp: types::RouterData<F, FData, types::PaymentsResponseData>,
maybe_customer: &Option<domain::Customer>,
merchant_account: &domain::MerchantAccount,
+ payment_method_type: Option<storage_enums::PaymentMethodType>,
) -> RouterResult<Option<String>>
where
FData: mandate::MandateBehaviour,
@@ -53,6 +55,7 @@ where
let payment_method_create_request = helpers::get_payment_method_create_request(
Some(&resp.request.get_payment_method_data()),
Some(resp.payment_method),
+ payment_method_type,
&customer,
)
.await?;
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 320896b34d1..c8cf6405a73 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -885,6 +885,7 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::VerifyRequestDat
router_return_url,
email: payment_data.email,
return_url: payment_data.payment_intent.return_url,
+ payment_method_type: attempt.payment_method_type.clone(),
})
}
}
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index a694e878aa6..881d4e7a2b2 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -339,6 +339,7 @@ pub struct VerifyRequestData {
pub router_return_url: Option<String>,
pub email: Option<Email>,
pub return_url: Option<String>,
+ pub payment_method_type: Option<storage_enums::PaymentMethodType>,
}
#[derive(Debug, Clone)]
|
fix
|
save payment_method_type when creating a record in the payment_method table (#1378)
|
050df5022cd3d44db23ca75f81158fb7c2429f86
|
2024-03-05 14:55:58
|
Sahkal Poddar
|
feat(router): add incoming header request logs (#3939)
| false
|
diff --git a/config/deployments/integration_test.toml b/config/deployments/integration_test.toml
index dd755c9dd22..b7585f0c2ef 100644
--- a/config/deployments/integration_test.toml
+++ b/config/deployments/integration_test.toml
@@ -290,3 +290,6 @@ outgoing_enabled = true
[webhook_source_verification_call]
connectors_with_webhook_source_verification_call = "paypal"
+
+[unmasked_headers]
+keys = "user-agent"
\ No newline at end of file
diff --git a/config/deployments/production.toml b/config/deployments/production.toml
index 9c2f25b24ff..a105c4c0e94 100644
--- a/config/deployments/production.toml
+++ b/config/deployments/production.toml
@@ -304,3 +304,6 @@ outgoing_enabled = true
[webhook_source_verification_call]
connectors_with_webhook_source_verification_call = "paypal"
+
+[unmasked_headers]
+keys = "user-agent"
\ No newline at end of file
diff --git a/config/deployments/sandbox.toml b/config/deployments/sandbox.toml
index 5c052e5c85f..ed718caa30d 100644
--- a/config/deployments/sandbox.toml
+++ b/config/deployments/sandbox.toml
@@ -306,3 +306,6 @@ outgoing_enabled = true
[webhook_source_verification_call]
connectors_with_webhook_source_verification_call = "paypal"
+
+[unmasked_headers]
+keys = "user-agent"
\ No newline at end of file
diff --git a/config/development.toml b/config/development.toml
index 8b3c036af4d..5d7366a89f3 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -571,3 +571,6 @@ enabled = true
[file_storage]
file_storage_backend = "file_system"
+
+[unmasked_headers]
+keys = "user-agent"
\ No newline at end of file
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index a2beb445b7a..f6de5ada7fa 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -430,3 +430,6 @@ source = "logs"
[file_storage]
file_storage_backend = "file_system"
+
+[unmasked_headers]
+keys = "user-agent"
\ No newline at end of file
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 1306cdd80bb..bbcc2b5bceb 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -353,5 +353,6 @@ pub(crate) async fn fetch_raw_secrets(
#[cfg(feature = "olap")]
connector_onboarding,
cors: conf.cors,
+ unmasked_headers: conf.unmasked_headers,
}
}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 8fb55491fe4..00897951ba8 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -115,6 +115,13 @@ pub struct Settings<S: SecretState> {
pub events: EventsConfig,
#[cfg(feature = "olap")]
pub connector_onboarding: SecretStateContainer<ConnectorOnboarding, S>,
+ pub unmasked_headers: UnmaskedHeaders,
+}
+
+#[derive(Debug, Deserialize, Clone, Default)]
+pub struct UnmaskedHeaders {
+ #[serde(deserialize_with = "deserialize_hashset")]
+ pub keys: HashSet<String>,
}
#[cfg(feature = "frm")]
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index f01b0ffc346..bc8e3b99d23 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1121,11 +1121,35 @@ where
{
let request_method = request.method().as_str();
let url_path = request.path();
+
+ let unmasked_incoming_header_keys = state.conf().unmasked_headers.keys;
+
+ let incoming_request_header = request.headers();
+
+ let incoming_header_to_log: HashMap<String, http::header::HeaderValue> =
+ incoming_request_header
+ .iter()
+ .fold(HashMap::new(), |mut acc, (key, value)| {
+ let key = key.to_string();
+ if unmasked_incoming_header_keys.contains(&key.as_str().to_lowercase()) {
+ acc.insert(key.clone(), value.clone());
+ } else {
+ acc.insert(
+ key.clone(),
+ http::header::HeaderValue::from_static("**MASKED**"),
+ );
+ }
+ acc
+ });
+
tracing::Span::current().record("request_method", request_method);
tracing::Span::current().record("request_url_path", url_path);
let start_instant = Instant::now();
- logger::info!(tag = ?Tag::BeginRequest, payload = ?payload);
+
+ logger::info!(
+ tag = ?Tag::BeginRequest, payload = ?payload,
+ headers = ?incoming_header_to_log);
let server_wrap_util_res = metrics::request::record_request_time_metric(
server_wrap_util(
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index aa0d75d609f..8ab6d33c984 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -293,3 +293,6 @@ enabled = true
client_id = ""
client_secret = ""
partner_id = ""
+
+[unmasked_headers]
+keys = "user-agent"
\ No newline at end of file
|
feat
|
add incoming header request logs (#3939)
|
6d09bf774535c3bfa78b0c8a0255d89a22d03e11
|
2023-10-09 12:28:16
|
github-actions
|
chore(version): v1.53.0
| false
|
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 65292e4fcaf..4e00211e15f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,36 @@ All notable changes to HyperSwitch will be documented here.
- - -
+## 1.53.0 (2023-10-09)
+
+### Features
+
+- **connector:**
+ - [Braintree] implement dispute webhook ([#2031](https://github.com/juspay/hyperswitch/pull/2031)) ([`eeccd10`](https://github.com/juspay/hyperswitch/commit/eeccd106ae569bd60011ed71495d7978998161f8))
+ - [Paypal] Implement 3DS for Cards ([#2443](https://github.com/juspay/hyperswitch/pull/2443)) ([`d95a64d`](https://github.com/juspay/hyperswitch/commit/d95a64d6c9b870bdc38aa091cf9bf660b1ea404e))
+ - [Cybersource] Use connector_response_reference_id as reference to merchant ([#2470](https://github.com/juspay/hyperswitch/pull/2470)) ([`a2dfc48`](https://github.com/juspay/hyperswitch/commit/a2dfc48318363db051f311ee7f911de0db0eb868))
+ - [Coinbase] Add order id as the reference id ([#2469](https://github.com/juspay/hyperswitch/pull/2469)) ([`9c2fff5`](https://github.com/juspay/hyperswitch/commit/9c2fff5ab44cdd4f285b6d1437f37869b517963e))
+ - [Multisafepay] Use transaction_id as reference to transaction ([#2451](https://github.com/juspay/hyperswitch/pull/2451)) ([`ba2efac`](https://github.com/juspay/hyperswitch/commit/ba2efac4fa2af22f81b0841350a334bc36e91022))
+
+### Bug Fixes
+
+- Add startup config log to drainer ([#2482](https://github.com/juspay/hyperswitch/pull/2482)) ([`5038234`](https://github.com/juspay/hyperswitch/commit/503823408b782968fb59f6ff5d7df417b9aa7dbe))
+- Fetch data directly from DB in OLAP functions ([#2475](https://github.com/juspay/hyperswitch/pull/2475)) ([`12b5341`](https://github.com/juspay/hyperswitch/commit/12b534197276ccc4aa9575e6b518bcc50b597bee))
+
+### Refactors
+
+- **connector:** [trustpay] refactor trustpay and handled variants errors ([#2484](https://github.com/juspay/hyperswitch/pull/2484)) ([`3f1e7c2`](https://github.com/juspay/hyperswitch/commit/3f1e7c2152a839a6fe69f60b906277ca831e7611))
+- **merchant_account:** Make `organization_id` as mandatory ([#2458](https://github.com/juspay/hyperswitch/pull/2458)) ([`53b4816`](https://github.com/juspay/hyperswitch/commit/53b4816d27fe7794cb482887ed17ddb4386bd2f7))
+
+### Miscellaneous Tasks
+
+- Env changes for gocardless mandate ([#2485](https://github.com/juspay/hyperswitch/pull/2485)) ([`65ca5f1`](https://github.com/juspay/hyperswitch/commit/65ca5f12da54715e5db785d122e2ec9714147c68))
+
+**Full Changelog:** [`v1.52.0...v1.53.0`](https://github.com/juspay/hyperswitch/compare/v1.52.0...v1.53.0)
+
+- - -
+
+
## 1.52.0 (2023-10-06)
### Features
|
chore
|
v1.53.0
|
f56f9d643451b9a7ff961b21fc6ec0eefac0ebdf
|
2023-07-07 19:51:07
|
Arjun Karthik
|
feat(connector): [PowerTranz] Add template code for PowerTranz connector (#1650)
| false
|
diff --git a/config/config.example.toml b/config/config.example.toml
index a58a18385c3..f1910c8f5e5 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -183,6 +183,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
paypal.base_url = "https://www.sandbox.paypal.com/"
payu.base_url = "https://secure.snd.payu.com/"
+powertranz.base_url = "https://staging.ptranz.com/api/spi/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
shift4.base_url = "https://api.shift4.com/"
stripe.base_url = "https://api.stripe.com/"
diff --git a/config/development.toml b/config/development.toml
index c1deac2a9f6..83d596858b6 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -86,6 +86,7 @@ cards = [
"payme",
"paypal",
"payu",
+ "powertranz",
"shift4",
"stripe",
"trustpay",
@@ -142,6 +143,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
paypal.base_url = "https://www.sandbox.paypal.com/"
payu.base_url = "https://secure.snd.payu.com/"
+powertranz.base_url = "https://staging.ptranz.com/api/spi/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
shift4.base_url = "https://api.shift4.com/"
stripe.base_url = "https://api.stripe.com/"
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 0d218569f91..454805d63b6 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -104,6 +104,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
paypal.base_url = "https://www.sandbox.paypal.com/"
payu.base_url = "https://secure.snd.payu.com/"
+powertranz.base_url = "https://staging.ptranz.com/api/spi/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
shift4.base_url = "https://api.shift4.com/"
stripe.base_url = "https://api.stripe.com/"
@@ -150,6 +151,7 @@ cards = [
"payme",
"paypal",
"payu",
+ "powertranz",
"shift4",
"stripe",
"trustpay",
diff --git a/crates/api_models/src/enums.rs b/crates/api_models/src/enums.rs
index 89c1277975b..82b28e16107 100644
--- a/crates/api_models/src/enums.rs
+++ b/crates/api_models/src/enums.rs
@@ -656,6 +656,7 @@ pub enum Connector {
Payme,
Paypal,
Payu,
+ //Powertranz,
Rapyd,
Shift4,
Stripe,
@@ -761,6 +762,7 @@ pub enum RoutableConnectors {
Payme,
Paypal,
Payu,
+ //Powertranz,
Rapyd,
Shift4,
Stripe,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 7acafa4c52b..4db7068834d 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -423,6 +423,7 @@ pub struct Connectors {
pub payme: ConnectorParams,
pub paypal: ConnectorParams,
pub payu: ConnectorParams,
+ pub powertranz: ConnectorParams,
pub rapyd: ConnectorParams,
pub shift4: ConnectorParams,
pub stripe: ConnectorParamsWithFileUploadUrl,
diff --git a/crates/router/src/connector.rs b/crates/router/src/connector.rs
index 45466661705..a9a387c482b 100644
--- a/crates/router/src/connector.rs
+++ b/crates/router/src/connector.rs
@@ -32,6 +32,7 @@ pub mod payeezy;
pub mod payme;
pub mod paypal;
pub mod payu;
+pub mod powertranz;
pub mod rapyd;
pub mod shift4;
pub mod stripe;
@@ -51,6 +52,6 @@ pub use self::{
globepay::Globepay, iatapay::Iatapay, klarna::Klarna, mollie::Mollie,
multisafepay::Multisafepay, nexinets::Nexinets, nmi::Nmi, noon::Noon, nuvei::Nuvei,
opayo::Opayo, opennode::Opennode, payeezy::Payeezy, payme::Payme, paypal::Paypal, payu::Payu,
- rapyd::Rapyd, shift4::Shift4, stripe::Stripe, trustpay::Trustpay, worldline::Worldline,
- worldpay::Worldpay, zen::Zen,
+ powertranz::Powertranz, rapyd::Rapyd, shift4::Shift4, stripe::Stripe, trustpay::Trustpay,
+ worldline::Worldline, worldpay::Worldpay, zen::Zen,
};
diff --git a/crates/router/src/connector/powertranz.rs b/crates/router/src/connector/powertranz.rs
new file mode 100644
index 00000000000..d9880b1143c
--- /dev/null
+++ b/crates/router/src/connector/powertranz.rs
@@ -0,0 +1,513 @@
+mod transformers;
+
+use std::fmt::Debug;
+
+use error_stack::{IntoReport, ResultExt};
+use masking::ExposeInterface;
+use transformers as powertranz;
+
+use crate::{
+ configs::settings,
+ core::errors::{self, CustomResult},
+ headers,
+ services::{
+ self,
+ request::{self, Mask},
+ ConnectorIntegration,
+ },
+ types::{
+ self,
+ api::{self, ConnectorCommon, ConnectorCommonExt},
+ ErrorResponse, Response,
+ },
+ utils::{self, BytesExt},
+};
+
+#[derive(Debug, Clone)]
+pub struct Powertranz;
+
+impl api::Payment for Powertranz {}
+impl api::PaymentSession for Powertranz {}
+impl api::ConnectorAccessToken for Powertranz {}
+impl api::PreVerify for Powertranz {}
+impl api::PaymentAuthorize for Powertranz {}
+impl api::PaymentSync for Powertranz {}
+impl api::PaymentCapture for Powertranz {}
+impl api::PaymentVoid for Powertranz {}
+impl api::Refund for Powertranz {}
+impl api::RefundExecute for Powertranz {}
+impl api::RefundSync for Powertranz {}
+impl api::PaymentToken for Powertranz {}
+
+impl
+ ConnectorIntegration<
+ api::PaymentMethodToken,
+ types::PaymentMethodTokenizationData,
+ types::PaymentsResponseData,
+ > for Powertranz
+{
+ // Not Implemented (R)
+}
+
+impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Powertranz
+where
+ Self: ConnectorIntegration<Flow, Request, Response>,
+{
+ fn build_headers(
+ &self,
+ req: &types::RouterData<Flow, Request, Response>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ let mut header = vec![(
+ headers::CONTENT_TYPE.to_string(),
+ types::PaymentsAuthorizeType::get_content_type(self)
+ .to_string()
+ .into(),
+ )];
+ let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
+ header.append(&mut api_key);
+ Ok(header)
+ }
+}
+
+impl ConnectorCommon for Powertranz {
+ fn id(&self) -> &'static str {
+ "powertranz"
+ }
+
+ fn common_get_content_type(&self) -> &'static str {
+ "application/json"
+ }
+
+ fn base_url<'a>(&self, connectors: &'a settings::Connectors) -> &'a str {
+ connectors.powertranz.base_url.as_ref()
+ }
+
+ fn get_auth_header(
+ &self,
+ auth_type: &types::ConnectorAuthType,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ let auth = powertranz::PowertranzAuthType::try_from(auth_type)
+ .change_context(errors::ConnectorError::FailedToObtainAuthType)?;
+ Ok(vec![(
+ headers::AUTHORIZATION.to_string(),
+ auth.api_key.expose().into_masked(),
+ )])
+ }
+
+ fn build_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ let response: powertranz::PowertranzErrorResponse = res
+ .response
+ .parse_struct("PowertranzErrorResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+
+ Ok(ErrorResponse {
+ status_code: res.status_code,
+ code: response.code,
+ message: response.message,
+ reason: response.reason,
+ })
+ }
+}
+
+impl ConnectorIntegration<api::Session, types::PaymentsSessionData, types::PaymentsResponseData>
+ for Powertranz
+{
+ //TODO: implement sessions flow
+}
+
+impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, types::AccessToken>
+ for Powertranz
+{
+}
+
+impl ConnectorIntegration<api::Verify, types::VerifyRequestData, types::PaymentsResponseData>
+ for Powertranz
+{
+}
+
+impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>
+ for Powertranz
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsAuthorizeRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
+ let req_obj = powertranz::PowertranzPaymentsRequest::try_from(req)?;
+ let powertranz_req = types::RequestBody::log_and_get_request_body(
+ &req_obj,
+ utils::Encode::<powertranz::PowertranzPaymentsRequest>::encode_to_string_of_json,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(powertranz_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsAuthorizeRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsAuthorizeType::get_url(
+ self, req, connectors,
+ )?)
+ .attach_default_headers()
+ .headers(types::PaymentsAuthorizeType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsAuthorizeType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsAuthorizeRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsAuthorizeRouterData, errors::ConnectorError> {
+ let response: powertranz::PowertranzPaymentsResponse = res
+ .response
+ .parse_struct("Powertranz PaymentsAuthorizeResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsResponseData>
+ for Powertranz
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Get)
+ .url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsSyncRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsSyncRouterData, errors::ConnectorError> {
+ let response: powertranz::PowertranzPaymentsResponse = res
+ .response
+ .parse_struct("powertranz PaymentsSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::PaymentsResponseData>
+ for Powertranz
+{
+ fn get_headers(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ _req: &types::PaymentsCaptureRouterData,
+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::PaymentsCaptureRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::PaymentsCaptureType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::PaymentsCaptureType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::PaymentsCaptureRouterData,
+ res: Response,
+ ) -> CustomResult<types::PaymentsCaptureRouterData, errors::ConnectorError> {
+ let response: powertranz::PowertranzPaymentsResponse = res
+ .response
+ .parse_struct("Powertranz PaymentsCaptureResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
+ for Powertranz
+{
+}
+
+impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
+ for Powertranz
+{
+ fn get_headers(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundsRouterData<api::Execute>,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn get_request_body(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ ) -> CustomResult<Option<types::RequestBody>, errors::ConnectorError> {
+ let req_obj = powertranz::PowertranzRefundRequest::try_from(req)?;
+ let powertranz_req = types::RequestBody::log_and_get_request_body(
+ &req_obj,
+ utils::Encode::<powertranz::PowertranzRefundRequest>::encode_to_string_of_json,
+ )
+ .change_context(errors::ConnectorError::RequestEncodingFailed)?;
+ Ok(Some(powertranz_req))
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ let request = services::RequestBuilder::new()
+ .method(services::Method::Post)
+ .url(&types::RefundExecuteType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundExecuteType::get_headers(
+ self, req, connectors,
+ )?)
+ .body(types::RefundExecuteType::get_request_body(self, req)?)
+ .build();
+ Ok(Some(request))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundsRouterData<api::Execute>,
+ res: Response,
+ ) -> CustomResult<types::RefundsRouterData<api::Execute>, errors::ConnectorError> {
+ let response: powertranz::RefundResponse = res
+ .response
+ .parse_struct("powertranz RefundResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponseData>
+ for Powertranz
+{
+ fn get_headers(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
+ self.build_headers(req, connectors)
+ }
+
+ fn get_content_type(&self) -> &'static str {
+ self.common_get_content_type()
+ }
+
+ fn get_url(
+ &self,
+ _req: &types::RefundSyncRouterData,
+ _connectors: &settings::Connectors,
+ ) -> CustomResult<String, errors::ConnectorError> {
+ Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ }
+
+ fn build_request(
+ &self,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
+ ) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
+ Ok(Some(
+ services::RequestBuilder::new()
+ .method(services::Method::Get)
+ .url(&types::RefundSyncType::get_url(self, req, connectors)?)
+ .attach_default_headers()
+ .headers(types::RefundSyncType::get_headers(self, req, connectors)?)
+ .body(types::RefundSyncType::get_request_body(self, req)?)
+ .build(),
+ ))
+ }
+
+ fn handle_response(
+ &self,
+ data: &types::RefundSyncRouterData,
+ res: Response,
+ ) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
+ let response: powertranz::RefundResponse = res
+ .response
+ .parse_struct("powertranz RefundSyncResponse")
+ .change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
+ types::RouterData::try_from(types::ResponseRouterData {
+ response,
+ data: data.clone(),
+ http_code: res.status_code,
+ })
+ }
+
+ fn get_error_response(
+ &self,
+ res: Response,
+ ) -> CustomResult<ErrorResponse, errors::ConnectorError> {
+ self.build_error_response(res)
+ }
+}
+
+#[async_trait::async_trait]
+impl api::IncomingWebhook for Powertranz {
+ fn get_webhook_object_reference_id(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::webhooks::ObjectReferenceId, errors::ConnectorError> {
+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ }
+
+ fn get_webhook_event_type(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<api::IncomingWebhookEvent, errors::ConnectorError> {
+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ }
+
+ fn get_webhook_resource_object(
+ &self,
+ _request: &api::IncomingWebhookRequestDetails<'_>,
+ ) -> CustomResult<serde_json::Value, errors::ConnectorError> {
+ Err(errors::ConnectorError::WebhooksNotImplemented).into_report()
+ }
+}
diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs
new file mode 100644
index 00000000000..379e7aa1579
--- /dev/null
+++ b/crates/router/src/connector/powertranz/transformers.rs
@@ -0,0 +1,210 @@
+use masking::Secret;
+use serde::{Deserialize, Serialize};
+
+use crate::{
+ connector::utils::PaymentsAuthorizeRequestData,
+ core::errors,
+ types::{self, api, storage::enums},
+};
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct PowertranzPaymentsRequest {
+ amount: i64,
+ card: PowertranzCard,
+}
+
+#[derive(Default, Debug, Serialize, Eq, PartialEq)]
+pub struct PowertranzCard {
+ name: Secret<String>,
+ number: cards::CardNumber,
+ expiry_month: Secret<String>,
+ expiry_year: Secret<String>,
+ cvc: Secret<String>,
+ complete: bool,
+}
+
+impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
+ match item.request.payment_method_data.clone() {
+ api::PaymentMethodData::Card(req_card) => {
+ let card = PowertranzCard {
+ name: req_card.card_holder_name,
+ number: req_card.card_number,
+ expiry_month: req_card.card_exp_month,
+ expiry_year: req_card.card_exp_year,
+ cvc: req_card.card_cvc,
+ complete: item.request.is_auto_capture()?,
+ };
+ Ok(Self {
+ amount: item.request.amount,
+ card,
+ })
+ }
+ _ => Err(errors::ConnectorError::NotImplemented("Payment methods".to_string()).into()),
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// Auth Struct
+pub struct PowertranzAuthType {
+ pub(super) api_key: Secret<String>,
+}
+
+impl TryFrom<&types::ConnectorAuthType> for PowertranzAuthType {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(auth_type: &types::ConnectorAuthType) -> Result<Self, Self::Error> {
+ match auth_type {
+ types::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
+ api_key: Secret::new(api_key.to_string()),
+ }),
+ _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
+ }
+ }
+}
+// PaymentsResponse
+//TODO: Append the remaining status flags
+#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
+#[serde(rename_all = "lowercase")]
+pub enum PowertranzPaymentStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<PowertranzPaymentStatus> for enums::AttemptStatus {
+ fn from(item: PowertranzPaymentStatus) -> Self {
+ match item {
+ PowertranzPaymentStatus::Succeeded => Self::Charged,
+ PowertranzPaymentStatus::Failed => Self::Failure,
+ PowertranzPaymentStatus::Processing => Self::Authorizing,
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
+pub struct PowertranzPaymentsResponse {
+ status: PowertranzPaymentStatus,
+ id: String,
+}
+
+impl<F, T>
+ TryFrom<
+ types::ResponseRouterData<F, PowertranzPaymentsResponse, T, types::PaymentsResponseData>,
+ > for types::RouterData<F, T, types::PaymentsResponseData>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::ResponseRouterData<
+ F,
+ PowertranzPaymentsResponse,
+ T,
+ types::PaymentsResponseData,
+ >,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ status: enums::AttemptStatus::from(item.response.status),
+ response: Ok(types::PaymentsResponseData::TransactionResponse {
+ resource_id: types::ResponseId::ConnectorTransactionId(item.response.id),
+ redirection_data: None,
+ mandate_reference: None,
+ connector_metadata: None,
+ network_txn_id: None,
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+// REFUND :
+// Type definition for RefundRequest
+#[derive(Default, Debug, Serialize)]
+pub struct PowertranzRefundRequest {
+ pub amount: i64,
+}
+
+impl<F> TryFrom<&types::RefundsRouterData<F>> for PowertranzRefundRequest {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(item: &types::RefundsRouterData<F>) -> Result<Self, Self::Error> {
+ Ok(Self {
+ amount: item.request.refund_amount,
+ })
+ }
+}
+
+// Type definition for Refund Response
+
+#[allow(dead_code)]
+#[derive(Debug, Serialize, Default, Deserialize, Clone)]
+pub enum RefundStatus {
+ Succeeded,
+ Failed,
+ #[default]
+ Processing,
+}
+
+impl From<RefundStatus> for enums::RefundStatus {
+ fn from(item: RefundStatus) -> Self {
+ match item {
+ RefundStatus::Succeeded => Self::Success,
+ RefundStatus::Failed => Self::Failure,
+ RefundStatus::Processing => Self::Pending,
+ //TODO: Review mapping
+ }
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Clone, Serialize, Deserialize)]
+pub struct RefundResponse {
+ id: String,
+ status: RefundStatus,
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
+ for types::RefundsRouterData<api::Execute>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::Execute, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
+ for types::RefundsRouterData<api::RSync>
+{
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(
+ item: types::RefundsResponseRouterData<api::RSync, RefundResponse>,
+ ) -> Result<Self, Self::Error> {
+ Ok(Self {
+ response: Ok(types::RefundsResponseData {
+ connector_refund_id: item.response.id.to_string(),
+ refund_status: enums::RefundStatus::from(item.response.status),
+ }),
+ ..item.data
+ })
+ }
+}
+
+//TODO: Fill the struct with respective fields
+#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
+pub struct PowertranzErrorResponse {
+ pub status_code: u16,
+ pub code: String,
+ pub message: String,
+ pub reason: Option<String>,
+}
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index bd63e9e3c1e..5971a8e52d6 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -162,6 +162,7 @@ default_imp_for_complete_authorize!(
connector::Payeezy,
connector::Payme,
connector::Payu,
+ connector::Powertranz,
connector::Rapyd,
connector::Stripe,
connector::Trustpay,
@@ -229,6 +230,7 @@ default_imp_for_create_customer!(
connector::Paypal,
connector::Payme,
connector::Payu,
+ connector::Powertranz,
connector::Rapyd,
connector::Shift4,
connector::Trustpay,
@@ -290,6 +292,7 @@ default_imp_for_connector_redirect_response!(
connector::Payeezy,
connector::Payme,
connector::Payu,
+ connector::Powertranz,
connector::Rapyd,
connector::Shift4,
connector::Worldline,
@@ -338,6 +341,7 @@ default_imp_for_connector_request_id!(
connector::Payeezy,
connector::Payme,
connector::Payu,
+ connector::Powertranz,
connector::Rapyd,
connector::Shift4,
connector::Stripe,
@@ -408,6 +412,7 @@ default_imp_for_accept_dispute!(
connector::Paypal,
connector::Payme,
connector::Payu,
+ connector::Powertranz,
connector::Rapyd,
connector::Shift4,
connector::Stripe,
@@ -498,6 +503,7 @@ default_imp_for_file_upload!(
connector::Paypal,
connector::Payme,
connector::Payu,
+ connector::Powertranz,
connector::Rapyd,
connector::Shift4,
connector::Trustpay,
@@ -565,6 +571,7 @@ default_imp_for_submit_evidence!(
connector::Paypal,
connector::Payme,
connector::Payu,
+ connector::Powertranz,
connector::Rapyd,
connector::Shift4,
connector::Trustpay,
@@ -632,6 +639,7 @@ default_imp_for_defend_dispute!(
connector::Paypal,
connector::Payme,
connector::Payu,
+ connector::Powertranz,
connector::Rapyd,
connector::Stripe,
connector::Shift4,
@@ -702,6 +710,7 @@ default_imp_for_pre_processing_steps!(
connector::Paypal,
connector::Payme,
connector::Payu,
+ connector::Powertranz,
connector::Rapyd,
connector::Shift4,
connector::Worldline,
diff --git a/crates/router/src/types/api.rs b/crates/router/src/types/api.rs
index 0c5d9ae5ef7..311fd7a4f39 100644
--- a/crates/router/src/types/api.rs
+++ b/crates/router/src/types/api.rs
@@ -242,6 +242,7 @@ impl ConnectorData {
// "payeezy" => Ok(Box::new(&connector::Payeezy)), As psync and rsync are not supported by this connector, it is added as template code for future usage
enums::Connector::Payme => Ok(Box::new(&connector::Payme)),
enums::Connector::Payu => Ok(Box::new(&connector::Payu)),
+ //enums::Connector::Powertranz => Ok(Box::new(&connector::powertranz)),
enums::Connector::Rapyd => Ok(Box::new(&connector::Rapyd)),
enums::Connector::Shift4 => Ok(Box::new(&connector::Shift4)),
enums::Connector::Stripe => Ok(Box::new(&connector::Stripe)),
diff --git a/crates/router/tests/connectors/connector_auth.rs b/crates/router/tests/connectors/connector_auth.rs
index 378170cd1f4..4e2e8901bbc 100644
--- a/crates/router/tests/connectors/connector_auth.rs
+++ b/crates/router/tests/connectors/connector_auth.rs
@@ -38,6 +38,7 @@ pub struct ConnectorAuthentication {
pub payme: Option<BodyKey>,
pub paypal: Option<BodyKey>,
pub payu: Option<BodyKey>,
+ pub powertranz: Option<HeaderKey>,
pub rapyd: Option<BodyKey>,
pub shift4: Option<HeaderKey>,
pub stripe: Option<HeaderKey>,
diff --git a/crates/router/tests/connectors/main.rs b/crates/router/tests/connectors/main.rs
index 829dc87b3e0..64ce4ad14f8 100644
--- a/crates/router/tests/connectors/main.rs
+++ b/crates/router/tests/connectors/main.rs
@@ -49,6 +49,7 @@ mod paypal;
mod paypal_ui;
mod payu;
mod payu_ui;
+mod powertranz;
mod rapyd;
mod selenium;
mod shift4;
diff --git a/crates/router/tests/connectors/powertranz.rs b/crates/router/tests/connectors/powertranz.rs
new file mode 100644
index 00000000000..67d0bfd2e43
--- /dev/null
+++ b/crates/router/tests/connectors/powertranz.rs
@@ -0,0 +1,420 @@
+use masking::Secret;
+use router::types::{self, api, storage::enums};
+
+use crate::{
+ connector_auth,
+ utils::{self, ConnectorActions},
+};
+
+#[derive(Clone, Copy)]
+struct PowertranzTest;
+impl ConnectorActions for PowertranzTest {}
+impl utils::Connector for PowertranzTest {
+ fn get_data(&self) -> types::api::ConnectorData {
+ use router::connector::Powertranz;
+ types::api::ConnectorData {
+ connector: Box::new(&Powertranz),
+ connector_name: types::Connector::DummyConnector1,
+ get_token: types::api::GetToken::Connector,
+ }
+ }
+
+ fn get_auth_token(&self) -> types::ConnectorAuthType {
+ types::ConnectorAuthType::from(
+ connector_auth::ConnectorAuthentication::new()
+ .powertranz
+ .expect("Missing connector authentication configuration"),
+ )
+ }
+
+ fn get_name(&self) -> String {
+ "powertranz".to_string()
+ }
+}
+
+static CONNECTOR: PowertranzTest = PowertranzTest {};
+
+fn get_default_payment_info() -> Option<utils::PaymentInfo> {
+ None
+}
+
+fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
+ None
+}
+
+// Cards Positive Tests
+// Creates a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_only_authorize_payment() {
+ let response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized);
+}
+
+// Captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(payment_method_details(), None, get_default_payment_info())
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Partially captures a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_capture_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_capture_payment(
+ payment_method_details(),
+ Some(types::PaymentsCaptureData {
+ amount_to_capture: 50,
+ ..utils::PaymentCaptureType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Capture payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_authorized_payment() {
+ let authorize_response = CONNECTOR
+ .authorize_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .expect("Authorize payment response");
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Authorized,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("PSync response");
+ assert_eq!(response.status, enums::AttemptStatus::Authorized,);
+}
+
+// Voids a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_void_authorized_payment() {
+ let response = CONNECTOR
+ .authorize_and_void_payment(
+ payment_method_details(),
+ Some(types::PaymentsCancelData {
+ connector_transaction_id: String::from(""),
+ cancellation_reason: Some("requested_by_customer".to_string()),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .expect("Void payment response");
+ assert_eq!(response.status, enums::AttemptStatus::Voided);
+}
+
+// Refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_manually_captured_payment() {
+ let response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Synchronizes a refund using the manual capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_manually_captured_refund() {
+ let refund_response = CONNECTOR
+ .capture_payment_and_refund(
+ payment_method_details(),
+ None,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_make_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+}
+
+// Synchronizes a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_auto_captured_payment() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let response = CONNECTOR
+ .psync_retry_till_status_matches(
+ enums::AttemptStatus::Charged,
+ Some(types::PaymentsSyncData {
+ connector_transaction_id: router::types::ResponseId::ConnectorTransactionId(
+ txn_id.unwrap(),
+ ),
+ capture_method: Some(enums::CaptureMethod::Automatic),
+ ..Default::default()
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(response.status, enums::AttemptStatus::Charged,);
+}
+
+// Refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_auto_captured_payment() {
+ let response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Partially refunds a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_partially_refund_succeeded_payment() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ refund_response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_refund_succeeded_payment_multiple_times() {
+ CONNECTOR
+ .make_payment_and_multiple_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 50,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await;
+}
+
+// Synchronizes a refund using the automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_sync_refund() {
+ let refund_response = CONNECTOR
+ .make_payment_and_refund(payment_method_details(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ let response = CONNECTOR
+ .rsync_retry_till_status_matches(
+ enums::RefundStatus::Success,
+ refund_response.response.unwrap().connector_refund_id,
+ None,
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap().refund_status,
+ enums::RefundStatus::Success,
+ );
+}
+
+// Cards Negative scenerios
+// Creates a payment with incorrect CVC.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_cvc() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethodData::Card(api::Card {
+ card_cvc: Secret::new("12345".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's security code is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry month.
+#[actix_web::test]
+async fn should_fail_payment_for_invalid_exp_month() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethodData::Card(api::Card {
+ card_exp_month: Secret::new("20".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration month is invalid.".to_string(),
+ );
+}
+
+// Creates a payment with incorrect expiry year.
+#[actix_web::test]
+async fn should_fail_payment_for_incorrect_expiry_year() {
+ let response = CONNECTOR
+ .make_payment(
+ Some(types::PaymentsAuthorizeData {
+ payment_method_data: types::api::PaymentMethodData::Card(api::Card {
+ card_exp_year: Secret::new("2000".to_string()),
+ ..utils::CCardType::default().0
+ }),
+ ..utils::PaymentAuthorizeType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Your card's expiration year is invalid.".to_string(),
+ );
+}
+
+// Voids a payment using automatic capture flow (Non 3DS).
+#[actix_web::test]
+async fn should_fail_void_payment_for_auto_capture() {
+ let authorize_response = CONNECTOR
+ .make_payment(payment_method_details(), get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
+ let txn_id = utils::get_connector_transaction_id(authorize_response.response);
+ assert_ne!(txn_id, None, "Empty connector transaction id");
+ let void_response = CONNECTOR
+ .void_payment(txn_id.unwrap(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ void_response.response.unwrap_err().message,
+ "You cannot cancel this PaymentIntent because it has a status of succeeded."
+ );
+}
+
+// Captures a payment using invalid connector payment id.
+#[actix_web::test]
+async fn should_fail_capture_for_invalid_payment() {
+ let capture_response = CONNECTOR
+ .capture_payment("123456789".to_string(), None, get_default_payment_info())
+ .await
+ .unwrap();
+ assert_eq!(
+ capture_response.response.unwrap_err().message,
+ String::from("No such payment_intent: '123456789'")
+ );
+}
+
+// Refunds a payment with refund amount higher than payment amount.
+#[actix_web::test]
+async fn should_fail_for_refund_amount_higher_than_payment_amount() {
+ let response = CONNECTOR
+ .make_payment_and_refund(
+ payment_method_details(),
+ Some(types::RefundsData {
+ refund_amount: 150,
+ ..utils::PaymentRefundType::default().0
+ }),
+ get_default_payment_info(),
+ )
+ .await
+ .unwrap();
+ assert_eq!(
+ response.response.unwrap_err().message,
+ "Refund amount (₹1.50) is greater than charge amount (₹1.00)",
+ );
+}
+
+// Connector dependent test cases goes here
+
+// [#478]: add unit tests for non 3DS, wallets & webhooks in connector tests
diff --git a/crates/router/tests/connectors/sample_auth.toml b/crates/router/tests/connectors/sample_auth.toml
index 483943e11ab..f0e2474ba8e 100644
--- a/crates/router/tests/connectors/sample_auth.toml
+++ b/crates/router/tests/connectors/sample_auth.toml
@@ -145,3 +145,7 @@ key1 = "Evoucher PMT API Key"
[globepay]
api_key="API Key"
+
+
+[powertranz]
+api_key="API Key"
diff --git a/loadtest/config/development.toml b/loadtest/config/development.toml
index d50fd2a76eb..6d952698601 100644
--- a/loadtest/config/development.toml
+++ b/loadtest/config/development.toml
@@ -91,6 +91,7 @@ payeezy.base_url = "https://api-cert.payeezy.com/"
payme.base_url = "https://sandbox.payme.io/"
paypal.base_url = "https://www.sandbox.paypal.com/"
payu.base_url = "https://secure.snd.payu.com/"
+powertranz.base_url = "https://staging.ptranz.com/api/spi/"
rapyd.base_url = "https://sandboxapi.rapyd.net"
shift4.base_url = "https://api.shift4.com/"
stripe.base_url = "https://api.stripe.com/"
@@ -136,6 +137,7 @@ cards = [
"payme",
"paypal",
"payu",
+ "powertranz",
"shift4",
"stripe",
"trustpay",
diff --git a/scripts/add_connector.sh b/scripts/add_connector.sh
index 1be1a11768f..79b12113177 100755
--- a/scripts/add_connector.sh
+++ b/scripts/add_connector.sh
@@ -4,7 +4,7 @@ function find_prev_connector() {
git checkout $self
cp $self $self.tmp
# add new connector to existing list and sort it
- connectors=(aci adyen airwallex applepay authorizedotnet bambora bitpay bluesnap braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu rapyd shift4 stripe trustpay worldline worldpay "$1")
+ connectors=(aci adyen airwallex applepay authorizedotnet bambora bitpay bluesnap braintree cashtocode checkout coinbase cryptopay cybersource dlocal dummyconnector fiserv forte globalpay globepay iatapay klarna mollie multisafepay nexinets noon nuvei opayo opennode payeezy payme paypal payu powertranz rapyd shift4 stripe trustpay worldline worldpay "$1")
IFS=$'\n' sorted=($(sort <<<"${connectors[*]}")); unset IFS
res=`echo ${sorted[@]}`
sed -i'' -e "s/^ connectors=.*/ connectors=($res \"\$1\")/" $self.tmp
|
feat
|
[PowerTranz] Add template code for PowerTranz connector (#1650)
|
7068fbfbe2f561f71c2358d8d2a744d28672a892
|
2024-07-24 19:18:25
|
Narayan Bhat
|
refactor(merchant_id): create domain type for `merchant_id` (#5408)
| false
|
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index a9dda658d4c..41d97b17115 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -11675,7 +11675,7 @@
"type": "string",
"description": "The identifier for the Merchant Account",
"example": "y3oqhf46pyzuxjbcn2giaqnb44",
- "maxLength": 255
+ "maxLength": 64
},
"merchant_name": {
"type": "string",
@@ -18100,7 +18100,6 @@
"PayoutCreateRequest": {
"type": "object",
"required": [
- "merchant_id",
"currency",
"confirm",
"payout_type",
@@ -18125,6 +18124,7 @@
"type": "string",
"description": "This is an identifier for the merchant account. This is inferred from the API key\nprovided during the request",
"example": "merchant_1668273825",
+ "nullable": true,
"maxLength": 255
},
"amount": {
diff --git a/crates/analytics/src/active_payments/core.rs b/crates/analytics/src/active_payments/core.rs
index b5ca3e2d0ba..c341ebbcb7c 100644
--- a/crates/analytics/src/active_payments/core.rs
+++ b/crates/analytics/src/active_payments/core.rs
@@ -20,7 +20,7 @@ use crate::{
pub async fn get_metrics(
pool: &AnalyticsProvider,
publishable_key: &String,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
req: GetActivePaymentsMetricRequest,
) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<
diff --git a/crates/analytics/src/active_payments/metrics.rs b/crates/analytics/src/active_payments/metrics.rs
index 5526f30fd6e..a1e1c5c85e9 100644
--- a/crates/analytics/src/active_payments/metrics.rs
+++ b/crates/analytics/src/active_payments/metrics.rs
@@ -29,7 +29,7 @@ where
{
async fn load_metrics(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
time_range: &TimeRange,
pool: &T,
@@ -53,7 +53,7 @@ where
{
async fn load_metrics(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
time_range: &TimeRange,
pool: &T,
@@ -66,7 +66,7 @@ where
match self {
Self::ActivePayments => {
ActivePayments
- .load_metrics(publishable_key, merchant_id, time_range, pool)
+ .load_metrics(merchant_id, publishable_key, time_range, pool)
.await
}
}
diff --git a/crates/analytics/src/active_payments/metrics/active_payments.rs b/crates/analytics/src/active_payments/metrics/active_payments.rs
index 30621c98c7e..567820f825c 100644
--- a/crates/analytics/src/active_payments/metrics/active_payments.rs
+++ b/crates/analytics/src/active_payments/metrics/active_payments.rs
@@ -28,7 +28,7 @@ where
{
async fn load_metrics(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
time_range: &TimeRange,
pool: &T,
@@ -51,7 +51,7 @@ where
query_builder
.add_custom_filter_clause(
"merchant_id",
- format!("'{}','{}'", merchant_id, publishable_key),
+ format!("'{}','{}'", merchant_id.get_string_repr(), publishable_key),
FilterTypes::In,
)
.switch()?;
diff --git a/crates/analytics/src/api_event/core.rs b/crates/analytics/src/api_event/core.rs
index c7d6d9ac339..305de7e69c8 100644
--- a/crates/analytics/src/api_event/core.rs
+++ b/crates/analytics/src/api_event/core.rs
@@ -31,17 +31,17 @@ use crate::{
pub async fn api_events_core(
pool: &AnalyticsProvider,
req: ApiLogsRequest,
- merchant_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<Vec<ApiLogsResult>> {
let data = match pool {
AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented(
"API Events not implemented for SQLX",
))
.attach_printable("SQL Analytics is not implemented for API Events"),
- AnalyticsProvider::Clickhouse(pool) => get_api_event(&merchant_id, req, pool).await,
+ AnalyticsProvider::Clickhouse(pool) => get_api_event(merchant_id, req, pool).await,
AnalyticsProvider::CombinedSqlx(_sqlx_pool, ckh_pool)
| AnalyticsProvider::CombinedCkh(_sqlx_pool, ckh_pool) => {
- get_api_event(&merchant_id, req, ckh_pool).await
+ get_api_event(merchant_id, req, ckh_pool).await
}
}
.switch()?;
@@ -51,7 +51,7 @@ pub async fn api_events_core(
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetApiEventFiltersRequest,
- merchant_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<ApiEventFiltersResponse> {
use api_models::analytics::{api_event::ApiEventDimensions, ApiEventFilterValue};
@@ -68,7 +68,7 @@ pub async fn get_filters(
AnalyticsProvider::Clickhouse(ckh_pool)
| AnalyticsProvider::CombinedSqlx(_, ckh_pool)
| AnalyticsProvider::CombinedCkh(_, ckh_pool) => {
- get_api_event_filter_for_dimension(dim, &merchant_id, &req.time_range, ckh_pool)
+ get_api_event_filter_for_dimension(dim, merchant_id, &req.time_range, ckh_pool)
.await
}
}
@@ -92,7 +92,7 @@ pub async fn get_filters(
#[instrument(skip_all)]
pub async fn get_api_event_metrics(
pool: &AnalyticsProvider,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
req: GetApiEventMetricRequest,
) -> AnalyticsResult<MetricsResponse<ApiMetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<ApiEventMetricsBucketIdentifier, ApiEventMetricRow> =
diff --git a/crates/analytics/src/api_event/events.rs b/crates/analytics/src/api_event/events.rs
index 4be3a3420da..039172d1e08 100644
--- a/crates/analytics/src/api_event/events.rs
+++ b/crates/analytics/src/api_event/events.rs
@@ -14,7 +14,7 @@ use crate::{
pub trait ApiLogsFilterAnalytics: LoadRow<ApiLogsResult> {}
pub async fn get_api_event<T>(
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
query_param: ApiLogsRequest,
pool: &T,
) -> FiltersResult<Vec<ApiLogsResult>>
@@ -102,7 +102,7 @@ where
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct ApiLogsResult {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: Option<String>,
pub refund_id: Option<String>,
pub payment_method_id: Option<String>,
diff --git a/crates/analytics/src/api_event/filters.rs b/crates/analytics/src/api_event/filters.rs
index 87414ebad4b..62fd8789018 100644
--- a/crates/analytics/src/api_event/filters.rs
+++ b/crates/analytics/src/api_event/filters.rs
@@ -12,7 +12,7 @@ pub trait ApiEventFilterAnalytics: LoadRow<ApiEventFilter> {}
pub async fn get_api_event_filter_for_dimension<T>(
dimension: ApiEventDimensions,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<ApiEventFilter>>
diff --git a/crates/analytics/src/api_event/metrics.rs b/crates/analytics/src/api_event/metrics.rs
index 1a08b56a595..ac29ec15169 100644
--- a/crates/analytics/src/api_event/metrics.rs
+++ b/crates/analytics/src/api_event/metrics.rs
@@ -43,7 +43,7 @@ where
async fn load_metrics(
&self,
dimensions: &[ApiEventDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -64,7 +64,7 @@ where
async fn load_metrics(
&self,
dimensions: &[ApiEventDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/api_event/metrics/api_count.rs b/crates/analytics/src/api_event/metrics/api_count.rs
index cb9d559292d..f00c01bbf38 100644
--- a/crates/analytics/src/api_event/metrics/api_count.rs
+++ b/crates/analytics/src/api_event/metrics/api_count.rs
@@ -30,7 +30,7 @@ where
async fn load_metrics(
&self,
_dimensions: &[ApiEventDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/api_event/metrics/latency.rs b/crates/analytics/src/api_event/metrics/latency.rs
index 20fb6489451..5d71da2a0aa 100644
--- a/crates/analytics/src/api_event/metrics/latency.rs
+++ b/crates/analytics/src/api_event/metrics/latency.rs
@@ -33,7 +33,7 @@ where
async fn load_metrics(
&self,
_dimensions: &[ApiEventDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/api_event/metrics/status_code_count.rs b/crates/analytics/src/api_event/metrics/status_code_count.rs
index a5130169213..b4fff367b62 100644
--- a/crates/analytics/src/api_event/metrics/status_code_count.rs
+++ b/crates/analytics/src/api_event/metrics/status_code_count.rs
@@ -30,7 +30,7 @@ where
async fn load_metrics(
&self,
_dimensions: &[ApiEventDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/auth_events/core.rs b/crates/analytics/src/auth_events/core.rs
index e50a6aaf530..250dc07fee7 100644
--- a/crates/analytics/src/auth_events/core.rs
+++ b/crates/analytics/src/auth_events/core.rs
@@ -17,7 +17,7 @@ use crate::{
#[instrument(skip_all)]
pub async fn get_metrics(
pool: &AnalyticsProvider,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &String,
req: GetAuthEventMetricRequest,
) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> {
diff --git a/crates/analytics/src/auth_events/metrics.rs b/crates/analytics/src/auth_events/metrics.rs
index 6690850a80e..da5bf6309fe 100644
--- a/crates/analytics/src/auth_events/metrics.rs
+++ b/crates/analytics/src/auth_events/metrics.rs
@@ -44,7 +44,7 @@ where
{
async fn load_metrics(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -64,7 +64,7 @@ where
{
async fn load_metrics(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs
index 80c80db92fe..4fee15e2afd 100644
--- a/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs
+++ b/crates/analytics/src/auth_events/metrics/authentication_attempt_count.rs
@@ -29,7 +29,7 @@ where
{
async fn load_metrics(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs
index bfcfbaf3a6a..06de7a694fc 100644
--- a/crates/analytics/src/auth_events/metrics/authentication_success_count.rs
+++ b/crates/analytics/src/auth_events/metrics/authentication_success_count.rs
@@ -29,7 +29,7 @@ where
{
async fn load_metrics(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs
index b146c053d3d..2f744f15e90 100644
--- a/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs
+++ b/crates/analytics/src/auth_events/metrics/challenge_attempt_count.rs
@@ -29,7 +29,7 @@ where
{
async fn load_metrics(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_publishable_key: &str,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs
index b2921bb3ece..551810d8e5a 100644
--- a/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs
+++ b/crates/analytics/src/auth_events/metrics/challenge_flow_count.rs
@@ -29,7 +29,7 @@ where
{
async fn load_metrics(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs
index f6553f84f8c..c6c7d1cda08 100644
--- a/crates/analytics/src/auth_events/metrics/challenge_success_count.rs
+++ b/crates/analytics/src/auth_events/metrics/challenge_success_count.rs
@@ -29,7 +29,7 @@ where
{
async fn load_metrics(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_publishable_key: &str,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs
index 42261f09b3e..69b4eeba4a6 100644
--- a/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs
+++ b/crates/analytics/src/auth_events/metrics/frictionless_flow_count.rs
@@ -29,7 +29,7 @@ where
{
async fn load_metrics(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs
index 4d7eed972f4..6ea26a90979 100644
--- a/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs
+++ b/crates/analytics/src/auth_events/metrics/frictionless_success_count.rs
@@ -29,7 +29,7 @@ where
{
async fn load_metrics(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_publishable_key: &str,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -52,7 +52,7 @@ where
}
query_builder
- .add_filter_clause("merchant_id", merchant_id)
+ .add_filter_clause("merchant_id", merchant_id.get_string_repr())
.switch()?;
query_builder
diff --git a/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs b/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs
index 05173bcb9da..ca67400a9b2 100644
--- a/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs
+++ b/crates/analytics/src/auth_events/metrics/three_ds_sdk_count.rs
@@ -29,7 +29,7 @@ where
{
async fn load_metrics(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/connector_events/core.rs b/crates/analytics/src/connector_events/core.rs
index a7f5b978428..ae1405ed472 100644
--- a/crates/analytics/src/connector_events/core.rs
+++ b/crates/analytics/src/connector_events/core.rs
@@ -8,7 +8,7 @@ use crate::{errors::AnalyticsResult, types::FiltersError, AnalyticsProvider};
pub async fn connector_events_core(
pool: &AnalyticsProvider,
req: ConnectorEventsRequest,
- merchant_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<Vec<ConnectorEventsResult>> {
let data = match pool {
AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented(
@@ -18,7 +18,7 @@ pub async fn connector_events_core(
AnalyticsProvider::Clickhouse(ckh_pool)
| AnalyticsProvider::CombinedSqlx(_, ckh_pool)
| AnalyticsProvider::CombinedCkh(_, ckh_pool) => {
- get_connector_events(&merchant_id, req, ckh_pool).await
+ get_connector_events(merchant_id, req, ckh_pool).await
}
}
.switch()?;
diff --git a/crates/analytics/src/connector_events/events.rs b/crates/analytics/src/connector_events/events.rs
index 0a13074d729..9bdbba3297e 100644
--- a/crates/analytics/src/connector_events/events.rs
+++ b/crates/analytics/src/connector_events/events.rs
@@ -10,7 +10,7 @@ use crate::{
pub trait ConnectorEventLogAnalytics: LoadRow<ConnectorEventsResult> {}
pub async fn get_connector_events<T>(
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
query_param: ConnectorEventsRequest,
pool: &T,
) -> FiltersResult<Vec<ConnectorEventsResult>>
@@ -56,7 +56,7 @@ where
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct ConnectorEventsResult {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: String,
pub connector_name: Option<String>,
pub request_id: Option<String>,
diff --git a/crates/analytics/src/disputes/core.rs b/crates/analytics/src/disputes/core.rs
index d2279180255..b67716291b6 100644
--- a/crates/analytics/src/disputes/core.rs
+++ b/crates/analytics/src/disputes/core.rs
@@ -27,7 +27,7 @@ use crate::{
pub async fn get_metrics(
pool: &AnalyticsProvider,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
req: GetDisputeMetricRequest,
) -> AnalyticsResult<MetricsResponse<DisputeMetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<
@@ -123,7 +123,7 @@ pub async fn get_metrics(
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetDisputeFilterRequest,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<DisputeFiltersResponse> {
let mut res = DisputeFiltersResponse::default();
for dim in req.group_by_names {
diff --git a/crates/analytics/src/disputes/filters.rs b/crates/analytics/src/disputes/filters.rs
index 9b03c4de940..e9b6d26bee7 100644
--- a/crates/analytics/src/disputes/filters.rs
+++ b/crates/analytics/src/disputes/filters.rs
@@ -11,7 +11,7 @@ pub trait DisputeFilterAnalytics: LoadRow<DisputeFilterRow> {}
pub async fn get_dispute_filter_for_dimension<T>(
dimension: DisputeDimensions,
- merchant: &String,
+ merchant: &common_utils::id_type::MerchantId,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<DisputeFilterRow>>
diff --git a/crates/analytics/src/disputes/metrics.rs b/crates/analytics/src/disputes/metrics.rs
index e397785528c..d2ae23d0ace 100644
--- a/crates/analytics/src/disputes/metrics.rs
+++ b/crates/analytics/src/disputes/metrics.rs
@@ -52,7 +52,7 @@ where
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &DisputeFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -73,7 +73,7 @@ where
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &DisputeFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/disputes/metrics/dispute_status_metric.rs b/crates/analytics/src/disputes/metrics/dispute_status_metric.rs
index 005be320eb5..776f94282ce 100644
--- a/crates/analytics/src/disputes/metrics/dispute_status_metric.rs
+++ b/crates/analytics/src/disputes/metrics/dispute_status_metric.rs
@@ -29,7 +29,7 @@ where
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &DisputeFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/disputes/metrics/total_amount_disputed.rs b/crates/analytics/src/disputes/metrics/total_amount_disputed.rs
index cf299ebfa9d..8b45dab3950 100644
--- a/crates/analytics/src/disputes/metrics/total_amount_disputed.rs
+++ b/crates/analytics/src/disputes/metrics/total_amount_disputed.rs
@@ -29,7 +29,7 @@ where
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &DisputeFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs b/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs
index ddf6338f01f..f72ca914e63 100644
--- a/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs
+++ b/crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs
@@ -29,7 +29,7 @@ where
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &DisputeFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/frm/core.rs b/crates/analytics/src/frm/core.rs
index 9c9e73b49a8..d2b79ad2773 100644
--- a/crates/analytics/src/frm/core.rs
+++ b/crates/analytics/src/frm/core.rs
@@ -25,7 +25,7 @@ use crate::{
pub async fn get_metrics(
pool: &AnalyticsProvider,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
req: GetFrmMetricRequest,
) -> AnalyticsResult<MetricsResponse<FrmMetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<FrmMetricsBucketIdentifier, FrmMetricsAccumulator> =
@@ -114,7 +114,7 @@ pub async fn get_metrics(
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetFrmFilterRequest,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<FrmFiltersResponse> {
let mut res = FrmFiltersResponse::default();
for dim in req.group_by_names {
diff --git a/crates/analytics/src/frm/filters.rs b/crates/analytics/src/frm/filters.rs
index c019f61d427..91cde898bb7 100644
--- a/crates/analytics/src/frm/filters.rs
+++ b/crates/analytics/src/frm/filters.rs
@@ -18,7 +18,7 @@ pub trait FrmFilterAnalytics: LoadRow<FrmFilterRow> {}
pub async fn get_frm_filter_for_dimension<T>(
dimension: FrmDimensions,
- merchant: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<FrmFilterRow>>
@@ -39,7 +39,7 @@ where
.switch()?;
query_builder
- .add_filter_clause("merchant_id", merchant)
+ .add_filter_clause("merchant_id", merchant_id)
.switch()?;
query_builder.set_distinct();
diff --git a/crates/analytics/src/frm/metrics.rs b/crates/analytics/src/frm/metrics.rs
index 8f904090983..7f5b4ea32be 100644
--- a/crates/analytics/src/frm/metrics.rs
+++ b/crates/analytics/src/frm/metrics.rs
@@ -42,7 +42,7 @@ where
async fn load_metrics(
&self,
dimensions: &[FrmDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &FrmFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -63,7 +63,7 @@ where
async fn load_metrics(
&self,
dimensions: &[FrmDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &FrmFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/frm/metrics/frm_blocked_rate.rs b/crates/analytics/src/frm/metrics/frm_blocked_rate.rs
index 5f331feab6c..7154478c026 100644
--- a/crates/analytics/src/frm/metrics/frm_blocked_rate.rs
+++ b/crates/analytics/src/frm/metrics/frm_blocked_rate.rs
@@ -27,7 +27,7 @@ where
async fn load_metrics(
&self,
dimensions: &[FrmDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &FrmFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs b/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs
index b72345c4e3a..168a256ffa6 100644
--- a/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs
+++ b/crates/analytics/src/frm/metrics/frm_triggered_attempts.rs
@@ -28,7 +28,7 @@ where
async fn load_metrics(
&self,
dimensions: &[FrmDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &FrmFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/lib.rs b/crates/analytics/src/lib.rs
index 34dcc35d9ee..7755740e1df 100644
--- a/crates/analytics/src/lib.rs
+++ b/crates/analytics/src/lib.rs
@@ -112,7 +112,7 @@ impl AnalyticsProvider {
&self,
metric: &PaymentMetrics,
dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -216,7 +216,7 @@ impl AnalyticsProvider {
&self,
distribution: &Distribution,
dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -326,7 +326,7 @@ impl AnalyticsProvider {
&self,
metric: &PaymentIntentMetrics,
dimensions: &[PaymentIntentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -431,7 +431,7 @@ impl AnalyticsProvider {
&self,
metric: &RefundMetrics,
dimensions: &[RefundDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &RefundFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -531,7 +531,7 @@ impl AnalyticsProvider {
&self,
metric: &FrmMetrics,
dimensions: &[FrmDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &FrmFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -631,7 +631,7 @@ impl AnalyticsProvider {
&self,
metric: &DisputeMetrics,
dimensions: &[DisputeDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &DisputeFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -769,7 +769,7 @@ impl AnalyticsProvider {
pub async fn get_active_payments_metrics(
&self,
metric: &ActivePaymentsMetrics,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
time_range: &TimeRange,
) -> types::MetricsResult<
@@ -796,7 +796,7 @@ impl AnalyticsProvider {
pub async fn get_auth_event_metrics(
&self,
metric: &AuthEventMetrics,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
publishable_key: &str,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -827,7 +827,7 @@ impl AnalyticsProvider {
&self,
metric: &ApiEventMetrics,
dimensions: &[ApiEventDimensions],
- pub_key: &str,
+ pub_key: &common_utils::id_type::MerchantId,
filters: &ApiEventFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/outgoing_webhook_event/core.rs b/crates/analytics/src/outgoing_webhook_event/core.rs
index a78def2751e..bf94e2a158e 100644
--- a/crates/analytics/src/outgoing_webhook_event/core.rs
+++ b/crates/analytics/src/outgoing_webhook_event/core.rs
@@ -8,7 +8,7 @@ use crate::{errors::AnalyticsResult, types::FiltersError, AnalyticsProvider};
pub async fn outgoing_webhook_events_core(
pool: &AnalyticsProvider,
req: OutgoingWebhookLogsRequest,
- merchant_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<Vec<OutgoingWebhookLogsResult>> {
let data = match pool {
AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented(
@@ -18,7 +18,7 @@ pub async fn outgoing_webhook_events_core(
AnalyticsProvider::Clickhouse(ckh_pool)
| AnalyticsProvider::CombinedSqlx(_, ckh_pool)
| AnalyticsProvider::CombinedCkh(_, ckh_pool) => {
- get_outgoing_webhook_event(&merchant_id, req, ckh_pool).await
+ get_outgoing_webhook_event(merchant_id, req, ckh_pool).await
}
}
.switch()?;
diff --git a/crates/analytics/src/outgoing_webhook_event/events.rs b/crates/analytics/src/outgoing_webhook_event/events.rs
index e742387e1eb..9aaddec2567 100644
--- a/crates/analytics/src/outgoing_webhook_event/events.rs
+++ b/crates/analytics/src/outgoing_webhook_event/events.rs
@@ -10,7 +10,7 @@ use crate::{
pub trait OutgoingWebhookLogsFilterAnalytics: LoadRow<OutgoingWebhookLogsResult> {}
pub async fn get_outgoing_webhook_event<T>(
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
query_param: OutgoingWebhookLogsRequest,
pool: &T,
) -> FiltersResult<Vec<OutgoingWebhookLogsResult>>
@@ -72,7 +72,7 @@ where
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct OutgoingWebhookLogsResult {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub event_id: String,
pub event_type: String,
pub outgoing_webhook_event_type: String,
diff --git a/crates/analytics/src/payment_intents/core.rs b/crates/analytics/src/payment_intents/core.rs
index c7546a4ab0d..96e77be19b5 100644
--- a/crates/analytics/src/payment_intents/core.rs
+++ b/crates/analytics/src/payment_intents/core.rs
@@ -43,7 +43,7 @@ pub enum TaskType {
#[instrument(skip_all)]
pub async fn get_metrics(
pool: &AnalyticsProvider,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
req: GetPaymentIntentMetricRequest,
) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<
@@ -149,7 +149,7 @@ pub async fn get_metrics(
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetPaymentIntentFiltersRequest,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<PaymentIntentFiltersResponse> {
let mut res = PaymentIntentFiltersResponse::default();
diff --git a/crates/analytics/src/payment_intents/filters.rs b/crates/analytics/src/payment_intents/filters.rs
index 1a74cfd510e..29eb8f95d75 100644
--- a/crates/analytics/src/payment_intents/filters.rs
+++ b/crates/analytics/src/payment_intents/filters.rs
@@ -16,7 +16,7 @@ pub trait PaymentIntentFilterAnalytics: LoadRow<PaymentIntentFilterRow> {}
pub async fn get_payment_intent_filter_for_dimension<T>(
dimension: PaymentIntentDimensions,
- merchant: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<PaymentIntentFilterRow>>
@@ -37,7 +37,7 @@ where
.switch()?;
query_builder
- .add_filter_clause("merchant_id", merchant)
+ .add_filter_clause("merchant_id", merchant_id)
.switch()?;
query_builder.set_distinct();
diff --git a/crates/analytics/src/payment_intents/metrics.rs b/crates/analytics/src/payment_intents/metrics.rs
index a06d76ce8fe..b314b863561 100644
--- a/crates/analytics/src/payment_intents/metrics.rs
+++ b/crates/analytics/src/payment_intents/metrics.rs
@@ -47,7 +47,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentIntentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -68,7 +68,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentIntentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs
index 5db153c8a36..c3443902f0c 100644
--- a/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs
+++ b/crates/analytics/src/payment_intents/metrics/payment_intent_count.rs
@@ -32,7 +32,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentIntentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
index 3b78a355828..d14174338c8 100644
--- a/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
+++ b/crates/analytics/src/payment_intents/metrics/smart_retried_amount.rs
@@ -38,7 +38,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentIntentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs
index ef0bb6672f1..27d54256b14 100644
--- a/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs
+++ b/crates/analytics/src/payment_intents/metrics/successful_smart_retries.rs
@@ -38,7 +38,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentIntentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs
index 3ef8c02aca2..ee63d15ee42 100644
--- a/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs
+++ b/crates/analytics/src/payment_intents/metrics/total_smart_retries.rs
@@ -35,7 +35,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentIntentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payments/core.rs b/crates/analytics/src/payments/core.rs
index e943bf0ac6b..1a27fa067a5 100644
--- a/crates/analytics/src/payments/core.rs
+++ b/crates/analytics/src/payments/core.rs
@@ -45,7 +45,7 @@ pub enum TaskType {
#[instrument(skip_all)]
pub async fn get_metrics(
pool: &AnalyticsProvider,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
req: GetPaymentMetricRequest,
) -> AnalyticsResult<MetricsResponse<MetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<
@@ -222,7 +222,7 @@ pub async fn get_metrics(
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetPaymentFiltersRequest,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<PaymentFiltersResponse> {
let mut res = PaymentFiltersResponse::default();
diff --git a/crates/analytics/src/payments/distribution.rs b/crates/analytics/src/payments/distribution.rs
index c238eb79b9b..17c29828eba 100644
--- a/crates/analytics/src/payments/distribution.rs
+++ b/crates/analytics/src/payments/distribution.rs
@@ -47,7 +47,7 @@ where
&self,
distribution: &Distribution,
dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -69,7 +69,7 @@ where
&self,
distribution: &Distribution,
dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payments/distribution/payment_error_message.rs b/crates/analytics/src/payments/distribution/payment_error_message.rs
index 7dc42994d29..90869356deb 100644
--- a/crates/analytics/src/payments/distribution/payment_error_message.rs
+++ b/crates/analytics/src/payments/distribution/payment_error_message.rs
@@ -32,7 +32,7 @@ where
&self,
distribution: &Distribution,
dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payments/filters.rs b/crates/analytics/src/payments/filters.rs
index 232a3e5b0a3..b25c3fcba2d 100644
--- a/crates/analytics/src/payments/filters.rs
+++ b/crates/analytics/src/payments/filters.rs
@@ -16,7 +16,7 @@ pub trait PaymentFilterAnalytics: LoadRow<FilterRow> {}
pub async fn get_payment_filter_for_dimension<T>(
dimension: PaymentDimensions,
- merchant: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<FilterRow>>
@@ -37,7 +37,7 @@ where
.switch()?;
query_builder
- .add_filter_clause("merchant_id", merchant)
+ .add_filter_clause("merchant_id", merchant_id)
.switch()?;
query_builder.set_distinct();
diff --git a/crates/analytics/src/payments/metrics.rs b/crates/analytics/src/payments/metrics.rs
index 1dd1481688f..b5e0a487920 100644
--- a/crates/analytics/src/payments/metrics.rs
+++ b/crates/analytics/src/payments/metrics.rs
@@ -57,7 +57,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -78,7 +78,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payments/metrics/avg_ticket_size.rs b/crates/analytics/src/payments/metrics/avg_ticket_size.rs
index 1a1fbe52987..b09e2b2365a 100644
--- a/crates/analytics/src/payments/metrics/avg_ticket_size.rs
+++ b/crates/analytics/src/payments/metrics/avg_ticket_size.rs
@@ -31,7 +31,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payments/metrics/connector_success_rate.rs b/crates/analytics/src/payments/metrics/connector_success_rate.rs
index c5da4b51a0b..eb2ff1e3aa8 100644
--- a/crates/analytics/src/payments/metrics/connector_success_rate.rs
+++ b/crates/analytics/src/payments/metrics/connector_success_rate.rs
@@ -33,7 +33,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payments/metrics/payment_count.rs b/crates/analytics/src/payments/metrics/payment_count.rs
index 6fd12edea74..9a8b3157d7a 100644
--- a/crates/analytics/src/payments/metrics/payment_count.rs
+++ b/crates/analytics/src/payments/metrics/payment_count.rs
@@ -30,7 +30,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payments/metrics/payment_processed_amount.rs b/crates/analytics/src/payments/metrics/payment_processed_amount.rs
index 772156a070d..a3be7a9662e 100644
--- a/crates/analytics/src/payments/metrics/payment_processed_amount.rs
+++ b/crates/analytics/src/payments/metrics/payment_processed_amount.rs
@@ -31,7 +31,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payments/metrics/payment_success_count.rs b/crates/analytics/src/payments/metrics/payment_success_count.rs
index ce63424d1c8..e2c3834a449 100644
--- a/crates/analytics/src/payments/metrics/payment_success_count.rs
+++ b/crates/analytics/src/payments/metrics/payment_success_count.rs
@@ -31,7 +31,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payments/metrics/retries_count.rs b/crates/analytics/src/payments/metrics/retries_count.rs
index 33aa7d3b0b6..f0e4084c65e 100644
--- a/crates/analytics/src/payments/metrics/retries_count.rs
+++ b/crates/analytics/src/payments/metrics/retries_count.rs
@@ -36,7 +36,7 @@ where
async fn load_metrics(
&self,
_dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/payments/metrics/success_rate.rs b/crates/analytics/src/payments/metrics/success_rate.rs
index 1f48deaad16..70fb1814a8e 100644
--- a/crates/analytics/src/payments/metrics/success_rate.rs
+++ b/crates/analytics/src/payments/metrics/success_rate.rs
@@ -30,7 +30,7 @@ where
async fn load_metrics(
&self,
dimensions: &[PaymentDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/query.rs b/crates/analytics/src/query.rs
index 381deb60b80..cda40e22942 100644
--- a/crates/analytics/src/query.rs
+++ b/crates/analytics/src/query.rs
@@ -354,6 +354,12 @@ pub trait ToSql<T: AnalyticsDataSource> {
fn to_sql(&self, table_engine: &TableEngine) -> error_stack::Result<String, ParsingError>;
}
+impl<T: AnalyticsDataSource> ToSql<T> for &common_utils::id_type::MerchantId {
+ fn to_sql(&self, _table_engine: &TableEngine) -> error_stack::Result<String, ParsingError> {
+ Ok(self.get_string_repr().to_owned())
+ }
+}
+
/// Implement `ToSql` on arrays of types that impl `ToString`.
macro_rules! impl_to_sql_for_to_string {
($($type:ty),+) => {
diff --git a/crates/analytics/src/refunds/core.rs b/crates/analytics/src/refunds/core.rs
index 57480c7cec7..c1fc83da76a 100644
--- a/crates/analytics/src/refunds/core.rs
+++ b/crates/analytics/src/refunds/core.rs
@@ -28,7 +28,7 @@ use crate::{
pub async fn get_metrics(
pool: &AnalyticsProvider,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
req: GetRefundMetricRequest,
) -> AnalyticsResult<MetricsResponse<RefundMetricsBucketResponse>> {
let mut metrics_accumulator: HashMap<RefundMetricsBucketIdentifier, RefundMetricsAccumulator> =
@@ -125,7 +125,7 @@ pub async fn get_metrics(
pub async fn get_filters(
pool: &AnalyticsProvider,
req: GetRefundFilterRequest,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> AnalyticsResult<RefundFiltersResponse> {
let mut res = RefundFiltersResponse::default();
for dim in req.group_by_names {
diff --git a/crates/analytics/src/refunds/filters.rs b/crates/analytics/src/refunds/filters.rs
index 29375483eb9..138c4b86ead 100644
--- a/crates/analytics/src/refunds/filters.rs
+++ b/crates/analytics/src/refunds/filters.rs
@@ -18,7 +18,7 @@ pub trait RefundFilterAnalytics: LoadRow<RefundFilterRow> {}
pub async fn get_refund_filter_for_dimension<T>(
dimension: RefundDimensions,
- merchant: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
time_range: &TimeRange,
pool: &T,
) -> FiltersResult<Vec<RefundFilterRow>>
@@ -39,7 +39,7 @@ where
.switch()?;
query_builder
- .add_filter_clause("merchant_id", merchant)
+ .add_filter_clause("merchant_id", merchant_id)
.switch()?;
query_builder.set_distinct();
diff --git a/crates/analytics/src/refunds/metrics.rs b/crates/analytics/src/refunds/metrics.rs
index d8a59e54888..e8e6d149039 100644
--- a/crates/analytics/src/refunds/metrics.rs
+++ b/crates/analytics/src/refunds/metrics.rs
@@ -51,7 +51,7 @@ where
async fn load_metrics(
&self,
dimensions: &[RefundDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &RefundFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
@@ -72,7 +72,7 @@ where
async fn load_metrics(
&self,
dimensions: &[RefundDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &RefundFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/refunds/metrics/refund_count.rs b/crates/analytics/src/refunds/metrics/refund_count.rs
index 14240ff8e13..1ce6ed46428 100644
--- a/crates/analytics/src/refunds/metrics/refund_count.rs
+++ b/crates/analytics/src/refunds/metrics/refund_count.rs
@@ -30,7 +30,7 @@ where
async fn load_metrics(
&self,
dimensions: &[RefundDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &RefundFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs
index 829b11b082c..c03e85caadb 100644
--- a/crates/analytics/src/refunds/metrics/refund_processed_amount.rs
+++ b/crates/analytics/src/refunds/metrics/refund_processed_amount.rs
@@ -30,7 +30,7 @@ where
async fn load_metrics(
&self,
dimensions: &[RefundDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &RefundFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/refunds/metrics/refund_success_count.rs b/crates/analytics/src/refunds/metrics/refund_success_count.rs
index 0219340b40b..ae7b39f1e92 100644
--- a/crates/analytics/src/refunds/metrics/refund_success_count.rs
+++ b/crates/analytics/src/refunds/metrics/refund_success_count.rs
@@ -31,7 +31,7 @@ where
async fn load_metrics(
&self,
dimensions: &[RefundDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &RefundFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/refunds/metrics/refund_success_rate.rs b/crates/analytics/src/refunds/metrics/refund_success_rate.rs
index 36d82385b3f..b42641df4d8 100644
--- a/crates/analytics/src/refunds/metrics/refund_success_rate.rs
+++ b/crates/analytics/src/refunds/metrics/refund_success_rate.rs
@@ -29,7 +29,7 @@ where
async fn load_metrics(
&self,
dimensions: &[RefundDimensions],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &RefundFilters,
granularity: &Option<Granularity>,
time_range: &TimeRange,
diff --git a/crates/analytics/src/sdk_events/core.rs b/crates/analytics/src/sdk_events/core.rs
index 51709f37e4b..3eca479818b 100644
--- a/crates/analytics/src/sdk_events/core.rs
+++ b/crates/analytics/src/sdk_events/core.rs
@@ -26,7 +26,7 @@ use crate::{
pub async fn sdk_events_core(
pool: &AnalyticsProvider,
req: SdkEventsRequest,
- publishable_key: &str,
+ publishable_key: &String,
) -> AnalyticsResult<Vec<SdkEventsResult>> {
match pool {
AnalyticsProvider::Sqlx(_) => Err(FiltersError::NotImplemented(
diff --git a/crates/analytics/src/sdk_events/events.rs b/crates/analytics/src/sdk_events/events.rs
index a4d044267e9..3120c751386 100644
--- a/crates/analytics/src/sdk_events/events.rs
+++ b/crates/analytics/src/sdk_events/events.rs
@@ -14,7 +14,7 @@ use crate::{
pub trait SdkEventsFilterAnalytics: LoadRow<SdkEventsResult> {}
pub async fn get_sdk_event<T>(
- merchant_id: &str,
+ publishable_key: &String,
request: SdkEventsRequest,
pool: &T,
) -> FiltersResult<Vec<SdkEventsResult>>
@@ -34,7 +34,7 @@ where
query_builder.add_select_column("*").switch()?;
query_builder
- .add_filter_clause("merchant_id", merchant_id)
+ .add_filter_clause("merchant_id", publishable_key)
.switch()?;
query_builder
.add_filter_clause("payment_id", request.payment_id)
@@ -57,7 +57,7 @@ where
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct SdkEventsResult {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: String,
pub event_name: Option<String>,
pub log_type: Option<String>,
diff --git a/crates/analytics/src/search.rs b/crates/analytics/src/search.rs
index a5bd117bd63..4143a6df411 100644
--- a/crates/analytics/src/search.rs
+++ b/crates/analytics/src/search.rs
@@ -13,7 +13,7 @@ use crate::opensearch::{
pub async fn msearch_results(
client: &OpenSearchClient,
req: GetGlobalSearchRequest,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
indexes: Vec<SearchIndex>,
) -> CustomResult<Vec<GetSearchResponse>, OpenSearchError> {
let mut query_builder =
@@ -22,7 +22,7 @@ pub async fn msearch_results(
query_builder
.add_filter_clause(
"merchant_id.keyword".to_string(),
- vec![merchant_id.to_string()],
+ vec![merchant_id.get_string_repr().to_owned()],
)
.switch()?;
@@ -137,7 +137,7 @@ pub async fn msearch_results(
pub async fn search_results(
client: &OpenSearchClient,
req: GetSearchRequestWithIndex,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<GetSearchResponse, OpenSearchError> {
let search_req = req.search_req;
@@ -147,7 +147,7 @@ pub async fn search_results(
query_builder
.add_filter_clause(
"merchant_id.keyword".to_string(),
- vec![merchant_id.to_string()],
+ vec![merchant_id.get_string_repr().to_owned()],
)
.switch()?;
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index fe60a2d445a..5ba200bdc97 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -72,8 +72,8 @@ pub struct MerchantAccountCreate {
pub sub_merchants_enabled: Option<bool>,
/// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant
- #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf")]
- pub parent_merchant_id: Option<String>,
+ #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)]
+ pub parent_merchant_id: Option<id_type::MerchantId>,
/// A boolean value to indicate if payment response hash needs to be enabled
#[schema(default = false, example = true)]
@@ -264,8 +264,8 @@ pub struct MerchantAccountMetadata {
#[serde(deny_unknown_fields)]
pub struct MerchantAccountUpdate {
/// The identifier for the Merchant Account
- #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
- pub merchant_id: String,
+ #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
+ pub merchant_id: id_type::MerchantId,
/// Name of the Merchant Account
#[schema(example = "NewAge Retailer")]
@@ -296,8 +296,8 @@ pub struct MerchantAccountUpdate {
pub sub_merchants_enabled: Option<bool>,
/// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant
- #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf")]
- pub parent_merchant_id: Option<String>,
+ #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)]
+ pub parent_merchant_id: Option<id_type::MerchantId>,
/// A boolean value to indicate if payment response hash needs to be enabled
#[schema(default = false, example = true)]
@@ -346,8 +346,8 @@ pub struct MerchantAccountUpdate {
#[derive(Clone, Debug, ToSchema, Serialize)]
pub struct MerchantAccountResponse {
/// The identifier for the Merchant Account
- #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
- pub merchant_id: String,
+ #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
+ pub merchant_id: id_type::MerchantId,
/// Name of the Merchant Account
#[schema(value_type = Option<String>,example = "NewAge Retailer")]
@@ -392,8 +392,8 @@ pub struct MerchantAccountResponse {
pub sub_merchants_enabled: Option<bool>,
/// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant
- #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf")]
- pub parent_merchant_id: Option<String>,
+ #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)]
+ pub parent_merchant_id: Option<id_type::MerchantId>,
/// API key that will be used for server side API access
#[schema(example = "AH3423bkjbkjdsfbkj")]
@@ -555,8 +555,8 @@ pub struct WebhookDetails {
#[derive(Debug, Serialize, ToSchema)]
pub struct MerchantAccountDeleteResponse {
/// The identifier for the Merchant Account
- #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
- pub merchant_id: String,
+ #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
+ pub merchant_id: id_type::MerchantId,
/// If the connector is deleted or not
#[schema(example = false)]
pub deleted: bool,
@@ -564,12 +564,13 @@ pub struct MerchantAccountDeleteResponse {
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct MerchantId {
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
}
#[derive(Default, Debug, Deserialize, ToSchema, Serialize)]
pub struct MerchantConnectorId {
- pub merchant_id: String,
+ #[schema(value_type = String)]
+ pub merchant_id: id_type::MerchantId,
pub merchant_connector_id: String,
}
@@ -1037,8 +1038,8 @@ pub enum AcceptedCountries {
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct MerchantConnectorDeleteResponse {
/// The identifier for the Merchant Account
- #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
- pub merchant_id: String,
+ #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
+ pub merchant_id: id_type::MerchantId,
/// Unique ID of the connector
#[schema(example = "mca_5apGeP94tMts6rg3U3kR")]
pub merchant_connector_id: String,
@@ -1050,8 +1051,8 @@ pub struct MerchantConnectorDeleteResponse {
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ToggleKVResponse {
/// The identifier for the Merchant Account
- #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
- pub merchant_id: String,
+ #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
+ pub merchant_id: id_type::MerchantId,
/// Status of KV for the specific merchant
#[schema(example = true)]
pub kv_enabled: bool,
@@ -1076,7 +1077,8 @@ pub struct TransferKeyResponse {
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ToggleKVRequest {
#[serde(skip_deserializing)]
- pub merchant_id: String,
+ #[schema(value_type = String)]
+ pub merchant_id: id_type::MerchantId,
/// Status of KV for the specific merchant
#[schema(example = true)]
pub kv_enabled: bool,
@@ -1208,7 +1210,7 @@ pub struct BusinessProfileCreate {
#[schema(value_type = Option<BusinessPayoutLinkConfig>)]
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
- /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs.
+ /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs.
#[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>,
}
@@ -1216,8 +1218,8 @@ pub struct BusinessProfileCreate {
#[derive(Clone, Debug, ToSchema, Serialize)]
pub struct BusinessProfileResponse {
/// The identifier for Merchant Account
- #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
- pub merchant_id: String,
+ #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
+ pub merchant_id: id_type::MerchantId,
/// The default business profile that must be used for creating merchant accounts and payments
#[schema(max_length = 64, example = "pro_abcdefghijklmnopqrstuvwxyz")]
diff --git a/crates/api_models/src/analytics.rs b/crates/api_models/src/analytics.rs
index ca10d7ce599..9f95eda6a7f 100644
--- a/crates/api_models/src/analytics.rs
+++ b/crates/api_models/src/analytics.rs
@@ -114,7 +114,7 @@ pub struct ReportRequest {
#[serde(rename_all = "camelCase")]
pub struct GenerateReportRequest {
pub request: ReportRequest,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub email: Secret<String, EmailStrategy>,
}
diff --git a/crates/api_models/src/api_keys.rs b/crates/api_models/src/api_keys.rs
index 801bbc63f5f..1fc7ce97be8 100644
--- a/crates/api_models/src/api_keys.rs
+++ b/crates/api_models/src/api_keys.rs
@@ -33,8 +33,8 @@ pub struct CreateApiKeyResponse {
pub key_id: String,
/// The identifier for the Merchant Account.
- #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
- pub merchant_id: String,
+ #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
+ pub merchant_id: common_utils::id_type::MerchantId,
/// The unique name for the API Key to help you identify it.
#[schema(max_length = 64, example = "Sandbox integration key")]
@@ -76,8 +76,8 @@ pub struct RetrieveApiKeyResponse {
pub key_id: String,
/// The identifier for the Merchant Account.
- #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
- pub merchant_id: String,
+ #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
+ pub merchant_id: common_utils::id_type::MerchantId,
/// The unique name for the API Key to help you identify it.
#[schema(max_length = 64, example = "Sandbox integration key")]
@@ -134,15 +134,16 @@ pub struct UpdateApiKeyRequest {
pub key_id: String,
#[serde(skip_deserializing)]
- pub merchant_id: String,
+ #[schema(value_type = String)]
+ pub merchant_id: common_utils::id_type::MerchantId,
}
/// The response body for revoking an API Key.
#[derive(Debug, Serialize, ToSchema)]
pub struct RevokeApiKeyResponse {
/// The identifier for the Merchant Account.
- #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
- pub merchant_id: String,
+ #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
+ pub merchant_id: common_utils::id_type::MerchantId,
/// The identifier for the API Key.
#[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX")]
diff --git a/crates/api_models/src/apple_pay_certificates_migration.rs b/crates/api_models/src/apple_pay_certificates_migration.rs
index 796734f53e4..512bbc6f0e2 100644
--- a/crates/api_models/src/apple_pay_certificates_migration.rs
+++ b/crates/api_models/src/apple_pay_certificates_migration.rs
@@ -1,12 +1,12 @@
#[derive(Debug, Clone, serde::Serialize)]
pub struct ApplePayCertificatesMigrationResponse {
- pub migration_successful: Vec<String>,
- pub migration_failed: Vec<String>,
+ pub migration_successful: Vec<common_utils::id_type::MerchantId>,
+ pub migration_failed: Vec<common_utils::id_type::MerchantId>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct ApplePayCertificatesMigrationRequest {
- pub merchant_ids: Vec<String>,
+ pub merchant_ids: Vec<common_utils::id_type::MerchantId>,
}
impl common_utils::events::ApiEventMetric for ApplePayCertificatesMigrationRequest {}
diff --git a/crates/api_models/src/connector_onboarding.rs b/crates/api_models/src/connector_onboarding.rs
index 7e8288d9747..1ed18392dcb 100644
--- a/crates/api_models/src/connector_onboarding.rs
+++ b/crates/api_models/src/connector_onboarding.rs
@@ -45,7 +45,7 @@ pub enum PayPalOnboardingStatus {
#[derive(serde::Serialize, Debug, Clone)]
pub struct PayPalOnboardingDone {
- pub payer_id: String,
+ pub payer_id: common_utils::id_type::MerchantId,
}
#[derive(serde::Serialize, Debug, Clone)]
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs
index ace4b54916b..e774085da28 100644
--- a/crates/api_models/src/customers.rs
+++ b/crates/api_models/src/customers.rs
@@ -21,8 +21,8 @@ pub struct CustomerRequest {
pub customer_id: Option<id_type::CustomerId>,
/// The identifier for the Merchant Account
#[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
- #[serde(default = "unknown_merchant", skip)]
- pub merchant_id: String,
+ #[serde(skip)]
+ pub merchant_id: id_type::MerchantId,
/// The customer's name
#[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")]
pub name: Option<Secret<String>>,
@@ -342,8 +342,3 @@ pub struct CustomerDeleteResponse {
#[schema(example = false)]
pub payment_methods_deleted: bool,
}
-
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
-fn unknown_merchant() -> String {
- String::from("merchant_unknown")
-}
diff --git a/crates/api_models/src/payment_methods.rs b/crates/api_models/src/payment_methods.rs
index fa7b3dc2dd0..3f1df4b8e96 100644
--- a/crates/api_models/src/payment_methods.rs
+++ b/crates/api_models/src/payment_methods.rs
@@ -100,7 +100,7 @@ pub struct PaymentMethodCreate {
/// This struct is only used by and internal api to migrate payment method
pub struct PaymentMethodMigrate {
/// Merchant id
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
/// The type of payment method use for the payment.
pub payment_method: Option<api_enums::PaymentMethod>,
@@ -352,8 +352,8 @@ impl CardDetailUpdate {
#[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct PaymentMethodResponse {
/// Unique identifier for a merchant
- #[schema(example = "merchant_1671528864")]
- pub merchant_id: String,
+ #[schema(example = "merchant_1671528864", value_type = String)]
+ pub merchant_id: id_type::MerchantId,
/// The unique identifier of the customer.
#[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")]
@@ -1176,8 +1176,8 @@ pub struct PaymentMethodCollectLinkResponse {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct PaymentMethodCollectLinkRenderRequest {
/// Unique identifier for a merchant.
- #[schema(example = "merchant_1671528864")]
- pub merchant_id: String,
+ #[schema(example = "merchant_1671528864", value_type = String)]
+ pub merchant_id: id_type::MerchantId,
/// The unique identifier for the collect link.
#[schema(value_type = String, example = "pm_collect_link_2bdacf398vwzq5n422S1")]
@@ -1346,7 +1346,7 @@ pub struct PaymentMethodRecord {
pub email: Option<pii::Email>,
pub phone: Option<masking::Secret<String>>,
pub phone_country_code: Option<String>,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub payment_method: Option<api_enums::PaymentMethod>,
pub payment_method_type: Option<api_enums::PaymentMethodType>,
pub nick_name: masking::Secret<String>,
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 04cf4cd5da3..2f505711137 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -272,9 +272,9 @@ pub struct PaymentsRequest {
/// This is an identifier for the merchant account. This is inferred from the API key
/// provided during the request
- #[schema(max_length = 255, example = "merchant_1668273825")]
+ #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)]
#[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)]
- pub merchant_id: Option<String>,
+ pub merchant_id: Option<id_type::MerchantId>,
/// Details of the routing configuration for that payment
#[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({
@@ -934,7 +934,7 @@ impl From<MinorUnit> for Amount {
#[serde(deny_unknown_fields)]
pub struct PaymentsRedirectRequest {
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub connector: String,
pub param: String,
}
@@ -2877,7 +2877,8 @@ pub struct CardResponse {
#[serde(rename_all = "snake_case")]
pub struct RewardData {
/// The merchant ID with which we have to call the connector
- pub merchant_id: String,
+ #[schema(value_type = String)]
+ pub merchant_id: id_type::MerchantId,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
@@ -3282,7 +3283,8 @@ pub struct PaymentsCaptureRequest {
#[serde(skip_deserializing)]
pub payment_id: String,
/// The unique identifier for the merchant
- pub merchant_id: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub merchant_id: Option<id_type::MerchantId>,
/// The Amount to be captured/ debited from the user's payment method.
#[schema(value_type = i64, example = 6540)]
pub amount_to_capture: Option<MinorUnit>,
@@ -3570,8 +3572,8 @@ pub struct PaymentsResponse {
/// This is an identifier for the merchant account. This is inferred from the API key
/// provided during the request
- #[schema(max_length = 255, example = "merchant_1668273825")]
- pub merchant_id: Option<String>,
+ #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)]
+ pub merchant_id: Option<id_type::MerchantId>,
#[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")]
pub status: api_enums::IntentStatus,
@@ -4110,7 +4112,7 @@ pub struct TimeRange {
#[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)]
pub struct VerifyResponse {
pub verify_id: Option<String>,
- pub merchant_id: Option<String>,
+ pub merchant_id: Option<id_type::MerchantId>,
// pub status: enums::VerifyStatus,
pub client_secret: Option<Secret<String>>,
pub customer_id: Option<id_type::CustomerId>,
@@ -4276,7 +4278,7 @@ pub struct RedirectionResponse {
pub struct PaymentsResponseForm {
pub transaction_id: String,
// pub transaction_reference_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub order_id: String,
}
@@ -4285,7 +4287,8 @@ pub struct PaymentsRetrieveRequest {
/// The type of ID (ex: payment intent id, payment attempt id or connector txn id)
pub resource_id: PaymentIdType,
/// The identifier for the Merchant Account.
- pub merchant_id: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub merchant_id: Option<id_type::MerchantId>,
/// Decider to enable or disable the connector call for retrieve request
pub force_sync: bool,
/// The parameters passed to a retrieve request
@@ -4883,7 +4886,8 @@ pub struct PaymentsSessionResponse {
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)]
pub struct PaymentRetrieveBody {
/// The identifier for the Merchant Account.
- pub merchant_id: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub merchant_id: Option<id_type::MerchantId>,
/// Decider to enable or disable the connector call for retrieve request
pub force_sync: Option<bool>,
/// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK
@@ -4899,7 +4903,8 @@ pub struct PaymentRetrieveBodyWithCredentials {
/// The identifier for payment.
pub payment_id: String,
/// The identifier for the Merchant Account.
- pub merchant_id: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub merchant_id: Option<id_type::MerchantId>,
/// Decider to enable or disable the connector call for retrieve request
pub force_sync: Option<bool>,
/// Merchant connector details used to make payments.
@@ -4967,7 +4972,8 @@ pub struct PaymentsManualUpdateRequest {
/// The identifier for the payment attempt
pub attempt_id: String,
/// Merchant ID
- pub merchant_id: String,
+ #[schema(value_type = String)]
+ pub merchant_id: id_type::MerchantId,
/// The status of the attempt
pub attempt_status: Option<enums::AttemptStatus>,
/// Error code of the connector
@@ -5059,7 +5065,8 @@ pub struct PaymentsStartRequest {
/// that have been done by a single merchant. This field is auto generated and is returned in the API response.
pub payment_id: String,
/// The identifier for the Merchant Account.
- pub merchant_id: String,
+ #[schema(value_type = String)]
+ pub merchant_id: id_type::MerchantId,
/// The identifier for the payment transaction
pub attempt_id: String,
}
@@ -5275,7 +5282,8 @@ pub struct RetrievePaymentLinkResponse {
/// Identifier for Payment Link
pub payment_link_id: String,
/// Identifier for Merchant
- pub merchant_id: String,
+ #[schema(value_type = String)]
+ pub merchant_id: id_type::MerchantId,
/// Payment Link
pub link_to_pay: String,
/// The payment amount. Amount for the payment in the lowest denomination of the currency
@@ -5297,7 +5305,8 @@ pub struct RetrievePaymentLinkResponse {
#[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)]
pub struct PaymentLinkInitiateRequest {
- pub merchant_id: String,
+ #[schema(value_type = String)]
+ pub merchant_id: id_type::MerchantId,
pub payment_id: String,
}
diff --git a/crates/api_models/src/payouts.rs b/crates/api_models/src/payouts.rs
index 49a053dd603..9509df8c591 100644
--- a/crates/api_models/src/payouts.rs
+++ b/crates/api_models/src/payouts.rs
@@ -33,8 +33,8 @@ pub struct PayoutCreateRequest {
/// This is an identifier for the merchant account. This is inferred from the API key
/// provided during the request
- #[schema(max_length = 255, value_type = String, example = "merchant_1668273825")]
- pub merchant_id: Option<String>,
+ #[schema(max_length = 255, value_type = Option<String>, example = "merchant_1668273825")]
+ pub merchant_id: Option<id_type::MerchantId>,
/// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,
#[schema(value_type = i64, example = 1000)]
@@ -362,7 +362,7 @@ pub struct PayoutCreateResponse {
/// This is an identifier for the merchant account. This is inferred from the API key
/// provided during the request
#[schema(max_length = 255, value_type = String, example = "merchant_1668273825")]
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
/// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc.,
#[schema(value_type = i64, example = 1000)]
@@ -531,7 +531,8 @@ pub struct PayoutAttemptResponse {
#[derive(Default, Debug, Clone, Deserialize, ToSchema)]
pub struct PayoutRetrieveBody {
pub force_sync: Option<bool>,
- pub merchant_id: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub merchant_id: Option<id_type::MerchantId>,
}
#[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)]
@@ -552,7 +553,8 @@ pub struct PayoutRetrieveRequest {
pub force_sync: Option<bool>,
/// The identifier for the Merchant Account.
- pub merchant_id: Option<String>,
+ #[schema(value_type = Option<String>)]
+ pub merchant_id: Option<id_type::MerchantId>,
}
#[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)]
@@ -707,7 +709,8 @@ pub struct PayoutLinkResponse {
#[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)]
pub struct PayoutLinkInitiateRequest {
- pub merchant_id: String,
+ #[schema(value_type = String)]
+ pub merchant_id: id_type::MerchantId,
pub payout_id: String,
}
diff --git a/crates/api_models/src/recon.rs b/crates/api_models/src/recon.rs
index efbe28f96ba..3aafcc413d2 100644
--- a/crates/api_models/src/recon.rs
+++ b/crates/api_models/src/recon.rs
@@ -5,7 +5,7 @@ use crate::enums;
#[derive(serde::Deserialize, Debug, serde::Serialize)]
pub struct ReconUpdateMerchantRequest {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub recon_status: enums::ReconStatus,
pub user_email: pii::Email,
}
diff --git a/crates/api_models/src/refunds.rs b/crates/api_models/src/refunds.rs
index b7fd212057c..dd6f1a22503 100644
--- a/crates/api_models/src/refunds.rs
+++ b/crates/api_models/src/refunds.rs
@@ -32,8 +32,8 @@ pub struct RefundRequest {
pub refund_id: Option<String>,
/// The identifier for the Merchant Account
- #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
- pub merchant_id: Option<String>,
+ #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)]
+ pub merchant_id: Option<common_utils::id_type::MerchantId>,
/// 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
#[schema(value_type = Option<i64> , minimum = 100, example = 6540)]
@@ -103,7 +103,8 @@ pub struct RefundManualUpdateRequest {
#[serde(skip)]
pub refund_id: String,
/// Merchant ID
- pub merchant_id: String,
+ #[schema(value_type = String)]
+ pub merchant_id: common_utils::id_type::MerchantId,
/// The status for refund
pub status: Option<RefundStatus>,
/// The code for the error
diff --git a/crates/api_models/src/routing.rs b/crates/api_models/src/routing.rs
index 4e62a5f67d2..7d1bb5bdf30 100644
--- a/crates/api_models/src/routing.rs
+++ b/crates/api_models/src/routing.rs
@@ -445,7 +445,8 @@ pub struct RoutingDictionaryRecord {
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingDictionary {
- pub merchant_id: String,
+ #[schema(value_type = String)]
+ pub merchant_id: common_utils::id_type::MerchantId,
pub active_id: Option<String>,
pub records: Vec<RoutingDictionaryRecord>,
}
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index 5bf855c4905..03e59db1e86 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -28,7 +28,7 @@ pub type SignUpResponse = DashboardEntryResponse;
#[derive(serde::Serialize, Debug, Clone)]
pub struct DashboardEntryResponse {
pub token: Secret<String>,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub name: Secret<String>,
pub email: pii::Email,
pub verification_days_left: Option<i64>,
@@ -71,7 +71,7 @@ pub struct AuthorizeResponse {
pub user_id: String,
//this field is added for audit/debug reasons
#[serde(skip_serializing)]
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
}
#[derive(serde::Deserialize, Debug, serde::Serialize)]
@@ -125,7 +125,7 @@ pub struct AcceptInviteFromEmailRequest {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct SwitchMerchantIdRequest {
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
}
#[derive(serde::Deserialize, Debug, serde::Serialize)]
@@ -156,7 +156,7 @@ pub struct UserDetails {
#[derive(serde::Serialize, Debug, Clone)]
pub struct GetUserDetailsResponse {
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub name: Secret<String>,
pub email: pii::Email,
pub verification_days_left: Option<i64>,
@@ -201,7 +201,7 @@ pub struct SendVerifyEmailRequest {
#[derive(Debug, serde::Serialize)]
pub struct UserMerchantAccount {
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub merchant_name: OptionalEncryptableName,
pub is_active: bool,
pub role_id: String,
@@ -212,14 +212,14 @@ pub struct UserMerchantAccount {
#[cfg(feature = "recon")]
#[derive(serde::Serialize, Debug)]
pub struct VerifyTokenResponse {
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub user_email: pii::Email,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct UpdateUserAccountDetailsRequest {
pub name: Option<Secret<String>>,
- pub preferred_merchant_id: Option<String>,
+ pub preferred_merchant_id: Option<id_type::MerchantId>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
diff --git a/crates/api_models/src/user_role.rs b/crates/api_models/src/user_role.rs
index 089e22a62a4..02e40e2fe1a 100644
--- a/crates/api_models/src/user_role.rs
+++ b/crates/api_models/src/user_role.rs
@@ -99,13 +99,13 @@ pub enum UserStatus {
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct MerchantSelectRequest {
- pub merchant_ids: Vec<String>,
+ pub merchant_ids: Vec<common_utils::id_type::MerchantId>,
// TODO: Remove this once the token only api is being used
pub need_dashboard_entry_response: Option<bool>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AcceptInvitationRequest {
- pub merchant_ids: Vec<String>,
+ pub merchant_ids: Vec<common_utils::id_type::MerchantId>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
diff --git a/crates/api_models/src/verifications.rs b/crates/api_models/src/verifications.rs
index 01193886e1f..5fa1b8cd4c8 100644
--- a/crates/api_models/src/verifications.rs
+++ b/crates/api_models/src/verifications.rs
@@ -27,7 +27,7 @@ pub struct ApplepayMerchantResponse {
#[derive(Debug, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub struct ApplepayGetVerifiedDomainsParam {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub merchant_connector_account_id: String,
}
/// Response to be sent for derivation of the already verified domains
diff --git a/crates/api_models/src/webhook_events.rs b/crates/api_models/src/webhook_events.rs
index 40a694a6650..2dcc6d64323 100644
--- a/crates/api_models/src/webhook_events.rs
+++ b/crates/api_models/src/webhook_events.rs
@@ -47,8 +47,8 @@ pub struct EventListItemResponse {
pub event_id: String,
/// The identifier for the Merchant Account.
- #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44")]
- pub merchant_id: String,
+ #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
+ pub merchant_id: common_utils::id_type::MerchantId,
/// The identifier for the Business Profile.
#[schema(max_length = 64, example = "SqB0zwDGR5wHppWf0bx7GKr1f2")]
@@ -97,7 +97,11 @@ pub struct EventRetrieveResponse {
impl common_utils::events::ApiEventMetric for EventRetrieveResponse {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Events {
- merchant_id_or_profile_id: self.event_information.merchant_id.clone(),
+ merchant_id_or_profile_id: self
+ .event_information
+ .merchant_id
+ .get_string_repr()
+ .to_owned(),
})
}
}
diff --git a/crates/api_models/src/webhooks.rs b/crates/api_models/src/webhooks.rs
index 2c10e3a81ee..b245e67e85a 100644
--- a/crates/api_models/src/webhooks.rs
+++ b/crates/api_models/src/webhooks.rs
@@ -207,7 +207,8 @@ pub struct IncomingWebhookDetails {
#[derive(Debug, Clone, Serialize, ToSchema)]
pub struct OutgoingWebhook {
/// The merchant id of the merchant
- pub merchant_id: String,
+ #[schema(value_type = String)]
+ pub merchant_id: common_utils::id_type::MerchantId,
/// The unique event id for each webhook
pub event_id: String,
diff --git a/crates/cards/Cargo.toml b/crates/cards/Cargo.toml
index ed2be966559..9091b1e6976 100644
--- a/crates/cards/Cargo.toml
+++ b/crates/cards/Cargo.toml
@@ -20,7 +20,7 @@ common_utils = { version = "0.1.0", path = "../common_utils" }
masking = { version = "0.1.0", path = "../masking" }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
-router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }
+router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"], default-features = false }
[dev-dependencies]
serde_json = "1.0.115"
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index a9eec76cc13..3454a6ba020 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -3003,3 +3003,10 @@ pub enum Owner {
Tenant,
Internal,
}
+
+#[derive(Clone, Debug, serde::Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum PayoutRetryType {
+ SingleConnector,
+ MultiConnector,
+}
diff --git a/crates/common_utils/Cargo.toml b/crates/common_utils/Cargo.toml
index 61d96a21737..4939c0f1609 100644
--- a/crates/common_utils/Cargo.toml
+++ b/crates/common_utils/Cargo.toml
@@ -15,6 +15,7 @@ signals = ["dep:signal-hook-tokio", "dep:signal-hook", "dep:tokio", "dep:router_
async_ext = ["dep:async-trait", "dep:futures"]
logs = ["dep:router_env"]
metrics = ["dep:router_env", "dep:futures"]
+payouts = ["common_enums/payouts"]
[dependencies]
async-trait = { version = "0.1.79", optional = true }
@@ -54,7 +55,7 @@ uuid = { version = "1.8.0", features = ["v7"] }
# First party crates
common_enums = { version = "0.1.0", path = "../common_enums" }
masking = { version = "0.1.0", path = "../masking" }
-router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"], optional = true }
+router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"], optional = true, default-features = false }
[target.'cfg(not(target_os = "windows"))'.dependencies]
signal-hook-tokio = { version = "0.3.1", features = ["futures-v0_3"], optional = true }
diff --git a/crates/common_utils/src/access_token.rs b/crates/common_utils/src/access_token.rs
index 56c2a4f784f..3407d2840d7 100644
--- a/crates/common_utils/src/access_token.rs
+++ b/crates/common_utils/src/access_token.rs
@@ -2,10 +2,12 @@
use std::fmt::Display;
+use crate::id_type;
+
/// Create a key for fetching the access token from redis
pub fn create_access_token_key(
- merchant_id: impl Display,
+ merchant_id: &id_type::MerchantId,
merchant_connector_id_or_connector_name: impl Display,
) -> String {
- format!("access_token_{merchant_id}_{merchant_connector_id_or_connector_name}")
+ merchant_id.get_access_token_key(merchant_connector_id_or_connector_name)
}
diff --git a/crates/common_utils/src/events.rs b/crates/common_utils/src/events.rs
index b2420709a77..c2294f865ae 100644
--- a/crates/common_utils/src/events.rs
+++ b/crates/common_utils/src/events.rs
@@ -105,8 +105,13 @@ impl_api_event_type!(
Miscellaneous,
(
String,
+ id_type::MerchantId,
+ (id_type::MerchantId, String),
+ (&id_type::MerchantId, String),
+ (&id_type::MerchantId, &String),
(&String, &String),
(Option<i64>, Option<i64>, String),
+ (Option<i64>, Option<i64>, id_type::MerchantId),
bool
)
);
diff --git a/crates/common_utils/src/id_type/merchant.rs b/crates/common_utils/src/id_type/merchant.rs
index 3accdc3a368..838cc52c1d0 100644
--- a/crates/common_utils/src/id_type/merchant.rs
+++ b/crates/common_utils/src/id_type/merchant.rs
@@ -3,7 +3,10 @@
//! Ids for merchant account are derived from the merchant name
//! If there are any special characters, they are removed
-use std::{borrow::Cow, fmt::Debug};
+use std::{
+ borrow::Cow,
+ fmt::{Debug, Display},
+};
use diesel::{
backend::Backend,
@@ -14,17 +17,20 @@ use diesel::{
};
use error_stack::{Result, ResultExt};
use serde::{Deserialize, Serialize};
+use utoipa::ToSchema;
use crate::{
consts::{MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH, MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH},
- errors, generate_id_with_default_len, generate_ref_id_with_default_length,
+ date_time, errors, generate_id_with_default_len, generate_ref_id_with_default_length,
id_type::{AlphaNumericId, LengthId},
new_type::MerchantName,
+ types::keymanager,
};
/// A type for merchant_id that can be used for merchant ids
-#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, AsExpression)]
+#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, AsExpression, Hash, ToSchema)]
#[diesel(sql_type = sql_types::Text)]
+#[schema(value_type = String)]
pub struct MerchantId(
LengthId<MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH, MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH>,
);
@@ -36,6 +42,22 @@ impl Debug for MerchantId {
}
}
+/// This should be temporary, we should not have direct impl of Display for merchant id
+impl Display for MerchantId {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(f, "{}", self.get_string_repr())
+ }
+}
+
+#[cfg(feature = "metrics")]
+/// This is implemented so that we can use merchant id directly as attribute in metrics
+impl From<MerchantId> for router_env::opentelemetry::Value {
+ fn from(val: MerchantId) -> Self {
+ let string_value = val.0 .0 .0;
+ Self::String(router_env::opentelemetry::StringValue::from(string_value))
+ }
+}
+
impl<DB> Queryable<sql_types::Text, DB> for MerchantId
where
DB: Backend,
@@ -83,6 +105,43 @@ impl MerchantId {
Self(length_id)
}
+
+ /// Get a merchant id with the const value of `MERCHANT_ID_NOT_FOUND`
+ pub fn get_merchant_id_not_found() -> Self {
+ let alphanumeric_id = AlphaNumericId::new_unchecked("MERCHANT_ID_NOT_FOUND".to_string());
+ let length_id = LengthId::new_unchecked(alphanumeric_id);
+ Self(length_id)
+ }
+
+ /// Get a merchant id for internal use only
+ pub fn get_internal_user_merchant_id(merchant_id: &str) -> Self {
+ let alphanumeric_id = AlphaNumericId::new_unchecked(merchant_id.to_string());
+ let length_id = LengthId::new_unchecked(alphanumeric_id);
+ Self(length_id)
+ }
+
+ /// Create a new merchant_id from unix timestamp, of the format `merchant_{timestamp}`
+ pub fn new_from_unix_timestamp() -> Self {
+ let merchant_id = format!("merchant_{}", date_time::now_unix_timestamp());
+
+ let alphanumeric_id = AlphaNumericId::new_unchecked(merchant_id);
+ let length_id = LengthId::new_unchecked(alphanumeric_id);
+
+ Self(length_id)
+ }
+
+ /// Get a merchant id with a value of `irrelevant_merchant_id`
+ pub fn get_irrelevant_merchant_id() -> Self {
+ let alphanumeric_id = AlphaNumericId::new_unchecked("irrelevant_merchant_id".to_string());
+ let length_id = LengthId::new_unchecked(alphanumeric_id);
+ Self(length_id)
+ }
+}
+
+impl From<MerchantId> for keymanager::Identifier {
+ fn from(value: MerchantId) -> Self {
+ Self::Merchant(value)
+ }
}
impl masking::SerializableSecret for MerchantId {}
@@ -112,3 +171,129 @@ where
.map(Self)
}
}
+
+/// All the keys that can be formed from merchant id
+impl MerchantId {
+ /// get step up enabled key
+ pub fn get_step_up_enabled_key(&self) -> String {
+ format!("step_up_enabled_{}", self.get_string_repr())
+ }
+
+ /// get_max_auto_retries_enabled key
+ pub fn get_max_auto_retries_enabled(&self) -> String {
+ format!("max_auto_retries_enabled_{}", self.get_string_repr())
+ }
+
+ /// get_requires_cvv_key
+ pub fn get_requires_cvv_key(&self) -> String {
+ format!("{}_requires_cvv", self.get_string_repr())
+ }
+
+ /// get_pm_filters_cgraph_key
+ pub fn get_pm_filters_cgraph_key(&self) -> String {
+ format!("pm_filters_cgraph_{}", self.get_string_repr())
+ }
+
+ /// get_blocklist_enabled_key
+ pub fn get_blocklist_guard_key(&self) -> String {
+ format!("guard_blocklist_for_{}", self.get_string_repr())
+ }
+
+ /// get_merchant_fingerprint_secret_key
+ pub fn get_merchant_fingerprint_secret_key(&self) -> String {
+ format!("fingerprint_secret_{}", self.get_string_repr())
+ }
+
+ /// get_surcharge_dsk_key
+ pub fn get_surcharge_dsk_key(&self) -> String {
+ format!("surcharge_dsl_{}", self.get_string_repr())
+ }
+
+ /// get_dsk_key
+ pub fn get_dsl_config(&self) -> String {
+ format!("dsl_{}", self.get_string_repr())
+ }
+
+ /// get_creds_identifier_key
+ pub fn get_creds_identifier_key(&self, creds_identifier: &str) -> String {
+ format!("mcd_{}_{creds_identifier}", self.get_string_repr())
+ }
+
+ /// get_poll_id
+ pub fn get_poll_id(&self, unique_id: &str) -> String {
+ format!("poll_{}_{unique_id}", self.get_string_repr())
+ }
+
+ /// get_access_token_key
+ pub fn get_access_token_key(
+ &self,
+ merchant_connector_id_or_connector_name: impl Display,
+ ) -> String {
+ format!(
+ "access_token_{}_{merchant_connector_id_or_connector_name}",
+ self.get_string_repr()
+ )
+ }
+
+ /// get_skip_saving_wallet_at_connector_key
+ pub fn get_skip_saving_wallet_at_connector_key(&self) -> String {
+ format!("skip_saving_wallet_at_connector_{}", self.get_string_repr())
+ }
+
+ /// get_payment_config_routing_id
+ pub fn get_payment_config_routing_id(&self) -> String {
+ format!("payment_config_id_{}", self.get_string_repr())
+ }
+
+ /// get_payment_method_surcharge_routing_id
+ pub fn get_payment_method_surcharge_routing_id(&self) -> String {
+ format!("payment_method_surcharge_id_{}", self.get_string_repr())
+ }
+
+ /// get_webhook_config_disabled_events_key
+ pub fn get_webhook_config_disabled_events_key(&self, connector_id: &str) -> String {
+ format!(
+ "whconf_disabled_events_{}_{connector_id}",
+ self.get_string_repr()
+ )
+ }
+
+ /// get_should_call_gsm_payout_key
+ pub fn get_should_call_gsm_payout_key(
+ &self,
+ payout_retry_type: common_enums::PayoutRetryType,
+ ) -> String {
+ match payout_retry_type {
+ common_enums::PayoutRetryType::SingleConnector => format!(
+ "should_call_gsm_single_connector_payout_{}",
+ self.get_string_repr()
+ ),
+ common_enums::PayoutRetryType::MultiConnector => format!(
+ "should_call_gsm_multiple_connector_payout_{}",
+ self.get_string_repr()
+ ),
+ }
+ }
+
+ /// Get should call gsm key for payment
+ pub fn get_should_call_gsm_key(&self) -> String {
+ format!("should_call_gsm_{}", self.get_string_repr())
+ }
+
+ /// get_max_auto_single_connector_payout_retries_enabled_
+ pub fn get_max_auto_single_connector_payout_retries_enabled(
+ &self,
+ payout_retry_type: common_enums::PayoutRetryType,
+ ) -> String {
+ match payout_retry_type {
+ common_enums::PayoutRetryType::SingleConnector => format!(
+ "max_auto_single_connector_payout_retries_enabled_{}",
+ self.get_string_repr()
+ ),
+ common_enums::PayoutRetryType::MultiConnector => format!(
+ "max_auto_multiple_connector_payout_retries_enabled_{}",
+ self.get_string_repr()
+ ),
+ }
+ }
+}
diff --git a/crates/common_utils/src/types/keymanager.rs b/crates/common_utils/src/types/keymanager.rs
index 5a7b87d0ce0..f4b671abcd7 100644
--- a/crates/common_utils/src/types/keymanager.rs
+++ b/crates/common_utils/src/types/keymanager.rs
@@ -17,6 +17,7 @@ use crate::{
crypto::Encryptable,
encryption::Encryption,
errors::{self, CustomResult},
+ id_type,
transformers::{ForeignFrom, ForeignTryFrom},
};
@@ -33,7 +34,7 @@ pub struct KeyManagerState {
#[serde(tag = "data_identifier", content = "key_identifier")]
pub enum Identifier {
User(String),
- Merchant(String),
+ Merchant(id_type::MerchantId),
UserAuth(String),
}
diff --git a/crates/diesel_models/src/address.rs b/crates/diesel_models/src/address.rs
index 57c4e36c786..8de7d8aa190 100644
--- a/crates/diesel_models/src/address.rs
+++ b/crates/diesel_models/src/address.rs
@@ -1,7 +1,6 @@
use common_utils::{
crypto::{self, Encryptable},
encryption::Encryption,
- id_type,
pii::EmailStrategy,
types::keymanager::ToEncryptable,
};
@@ -28,8 +27,8 @@ pub struct AddressNew {
pub last_name: Option<Encryption>,
pub phone_number: Option<Encryption>,
pub country_code: Option<String>,
- pub customer_id: Option<id_type::CustomerId>,
- pub merchant_id: String,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: Option<String>,
pub created_at: PrimitiveDateTime,
pub modified_at: PrimitiveDateTime,
@@ -55,8 +54,8 @@ pub struct Address {
pub country_code: Option<String>,
pub created_at: PrimitiveDateTime,
pub modified_at: PrimitiveDateTime,
- pub customer_id: Option<id_type::CustomerId>,
- pub merchant_id: String,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: Option<String>,
pub updated_by: String,
pub email: Option<Encryption>,
diff --git a/crates/diesel_models/src/api_keys.rs b/crates/diesel_models/src/api_keys.rs
index 3b6de46e085..1781e65cded 100644
--- a/crates/diesel_models/src/api_keys.rs
+++ b/crates/diesel_models/src/api_keys.rs
@@ -10,7 +10,7 @@ use crate::schema::api_keys;
#[diesel(table_name = api_keys, primary_key(key_id), check_for_backend(diesel::pg::Pg))]
pub struct ApiKey {
pub key_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub name: String,
pub description: Option<String>,
pub hashed_api_key: HashedApiKey,
@@ -24,7 +24,7 @@ pub struct ApiKey {
#[diesel(table_name = api_keys)]
pub struct ApiKeyNew {
pub key_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub name: String,
pub description: Option<String>,
pub hashed_api_key: HashedApiKey,
@@ -142,7 +142,7 @@ mod diesel_impl {
#[derive(Default, Debug, Deserialize, Serialize, Clone)]
pub struct ApiKeyExpiryTrackingData {
pub key_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub api_key_name: String,
pub prefix: String,
pub api_key_expiry: Option<PrimitiveDateTime>,
diff --git a/crates/diesel_models/src/authentication.rs b/crates/diesel_models/src/authentication.rs
index 050bc291c0b..cb518805ebf 100644
--- a/crates/diesel_models/src/authentication.rs
+++ b/crates/diesel_models/src/authentication.rs
@@ -10,7 +10,7 @@ use crate::schema::authentication;
#[diesel(table_name = authentication, primary_key(authentication_id), check_for_backend(diesel::pg::Pg))]
pub struct Authentication {
pub authentication_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub authentication_connector: String,
pub connector_authentication_id: Option<String>,
pub authentication_data: Option<serde_json::Value>,
@@ -61,7 +61,7 @@ impl Authentication {
#[diesel(table_name = authentication)]
pub struct AuthenticationNew {
pub authentication_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub authentication_connector: String,
pub connector_authentication_id: Option<String>,
// pub authentication_data: Option<serde_json::Value>,
diff --git a/crates/diesel_models/src/authorization.rs b/crates/diesel_models/src/authorization.rs
index 694577bba3f..2792bfdd55d 100644
--- a/crates/diesel_models/src/authorization.rs
+++ b/crates/diesel_models/src/authorization.rs
@@ -11,7 +11,7 @@ use crate::{enums as storage_enums, schema::incremental_authorization};
#[diesel(table_name = incremental_authorization, primary_key(authorization_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct Authorization {
pub authorization_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: String,
pub amount: MinorUnit,
#[serde(with = "common_utils::custom_serde::iso8601")]
@@ -29,7 +29,7 @@ pub struct Authorization {
#[diesel(table_name = incremental_authorization)]
pub struct AuthorizationNew {
pub authorization_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: String,
pub amount: MinorUnit,
pub status: storage_enums::AuthorizationStatus,
diff --git a/crates/diesel_models/src/blocklist.rs b/crates/diesel_models/src/blocklist.rs
index 14dbaf2fe43..0ef7daf0099 100644
--- a/crates/diesel_models/src/blocklist.rs
+++ b/crates/diesel_models/src/blocklist.rs
@@ -6,7 +6,7 @@ use crate::schema::blocklist;
#[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)]
#[diesel(table_name = blocklist)]
pub struct BlocklistNew {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint_id: String,
pub data_kind: common_enums::BlocklistDataKind,
pub metadata: Option<serde_json::Value>,
@@ -20,7 +20,7 @@ pub struct BlocklistNew {
pub struct Blocklist {
#[serde(skip)]
pub id: i32,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint_id: String,
pub data_kind: common_enums::BlocklistDataKind,
pub metadata: Option<serde_json::Value>,
diff --git a/crates/diesel_models/src/blocklist_fingerprint.rs b/crates/diesel_models/src/blocklist_fingerprint.rs
index ceea5134bb3..93b39e69a59 100644
--- a/crates/diesel_models/src/blocklist_fingerprint.rs
+++ b/crates/diesel_models/src/blocklist_fingerprint.rs
@@ -6,7 +6,7 @@ use crate::schema::blocklist_fingerprint;
#[derive(Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)]
#[diesel(table_name = blocklist_fingerprint)]
pub struct BlocklistFingerprintNew {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint_id: String,
pub data_kind: common_enums::BlocklistDataKind,
pub encrypted_fingerprint: String,
@@ -20,7 +20,7 @@ pub struct BlocklistFingerprintNew {
pub struct BlocklistFingerprint {
#[serde(skip_serializing)]
pub id: i32,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint_id: String,
pub data_kind: common_enums::BlocklistDataKind,
pub encrypted_fingerprint: String,
diff --git a/crates/diesel_models/src/blocklist_lookup.rs b/crates/diesel_models/src/blocklist_lookup.rs
index bebad02e780..dd7cd0252df 100644
--- a/crates/diesel_models/src/blocklist_lookup.rs
+++ b/crates/diesel_models/src/blocklist_lookup.rs
@@ -6,7 +6,7 @@ use crate::schema::blocklist_lookup;
#[derive(Default, Clone, Debug, Eq, Insertable, PartialEq, Serialize, Deserialize)]
#[diesel(table_name = blocklist_lookup)]
pub struct BlocklistLookupNew {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint: String,
}
@@ -26,6 +26,6 @@ pub struct BlocklistLookupNew {
pub struct BlocklistLookup {
#[serde(skip)]
pub id: i32,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub fingerprint: String,
}
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index b964b290a9e..30f6780e360 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -16,7 +16,7 @@ use crate::schema::business_profile;
#[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: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
@@ -50,7 +50,7 @@ pub struct BusinessProfile {
#[diesel(table_name = business_profile, primary_key(profile_id))]
pub struct BusinessProfileNew {
pub profile_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
diff --git a/crates/diesel_models/src/capture.rs b/crates/diesel_models/src/capture.rs
index cff09638a40..714a6a37359 100644
--- a/crates/diesel_models/src/capture.rs
+++ b/crates/diesel_models/src/capture.rs
@@ -12,7 +12,7 @@ use crate::{enums as storage_enums, schema::captures};
pub struct Capture {
pub capture_id: String,
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::CaptureStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
@@ -37,7 +37,7 @@ pub struct Capture {
pub struct CaptureNew {
pub capture_id: String,
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::CaptureStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rs
index 302772b7f9e..ea552e0d399 100644
--- a/crates/diesel_models/src/customers.rs
+++ b/crates/diesel_models/src/customers.rs
@@ -1,4 +1,4 @@
-use common_utils::{encryption::Encryption, id_type, pii};
+use common_utils::{encryption::Encryption, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
@@ -9,8 +9,8 @@ use crate::schema::customers;
)]
#[diesel(table_name = customers)]
pub struct CustomerNew {
- pub customer_id: id_type::CustomerId,
- pub merchant_id: String,
+ pub customer_id: common_utils::id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
@@ -58,8 +58,8 @@ impl From<CustomerNew> for Customer {
#[diesel(table_name = customers, check_for_backend(diesel::pg::Pg))]
pub struct Customer {
pub id: i32,
- pub customer_id: id_type::CustomerId,
- pub merchant_id: String,
+ pub customer_id: common_utils::id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub name: Option<Encryption>,
pub email: Option<Encryption>,
pub phone: Option<Encryption>,
diff --git a/crates/diesel_models/src/dispute.rs b/crates/diesel_models/src/dispute.rs
index 184dce15641..c2ef94e671f 100644
--- a/crates/diesel_models/src/dispute.rs
+++ b/crates/diesel_models/src/dispute.rs
@@ -17,7 +17,7 @@ pub struct DisputeNew {
pub dispute_status: storage_enums::DisputeStatus,
pub payment_id: String,
pub attempt_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub connector_status: String,
pub connector_dispute_id: String,
pub connector_reason: Option<String>,
@@ -44,7 +44,7 @@ pub struct Dispute {
pub dispute_status: storage_enums::DisputeStatus,
pub payment_id: String,
pub attempt_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub connector_status: String,
pub connector_dispute_id: String,
pub connector_reason: Option<String>,
diff --git a/crates/diesel_models/src/ephemeral_key.rs b/crates/diesel_models/src/ephemeral_key.rs
index 1cf15e9bfda..d398ecdf784 100644
--- a/crates/diesel_models/src/ephemeral_key.rs
+++ b/crates/diesel_models/src/ephemeral_key.rs
@@ -1,17 +1,15 @@
-use common_utils::id_type;
-
pub struct EphemeralKeyNew {
pub id: String,
- pub merchant_id: String,
- pub customer_id: id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ pub customer_id: common_utils::id_type::CustomerId,
pub secret: String,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct EphemeralKey {
pub id: String,
- pub merchant_id: String,
- pub customer_id: id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ pub customer_id: common_utils::id_type::CustomerId,
pub created_at: i64,
pub expires: i64,
pub secret: String,
diff --git a/crates/diesel_models/src/events.rs b/crates/diesel_models/src/events.rs
index 99879dafaf9..20c811654a7 100644
--- a/crates/diesel_models/src/events.rs
+++ b/crates/diesel_models/src/events.rs
@@ -21,7 +21,7 @@ pub struct EventNew {
pub primary_object_id: String,
pub primary_object_type: storage_enums::EventObjectType,
pub created_at: PrimitiveDateTime,
- pub merchant_id: Option<String>,
+ pub merchant_id: Option<common_utils::id_type::MerchantId>,
pub business_profile_id: Option<String>,
pub primary_object_created_at: Option<PrimitiveDateTime>,
pub idempotent_event_id: Option<String>,
@@ -50,7 +50,7 @@ pub struct Event {
pub primary_object_type: storage_enums::EventObjectType,
#[serde(with = "custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
- pub merchant_id: Option<String>,
+ pub merchant_id: Option<common_utils::id_type::MerchantId>,
pub business_profile_id: Option<String>,
// This column can be used to partition the database table, so that all events related to a
// single object would reside in the same partition
diff --git a/crates/diesel_models/src/file.rs b/crates/diesel_models/src/file.rs
index af584323b92..e5ad3568d70 100644
--- a/crates/diesel_models/src/file.rs
+++ b/crates/diesel_models/src/file.rs
@@ -9,7 +9,7 @@ use crate::schema::file_metadata;
#[serde(deny_unknown_fields)]
pub struct FileMetadataNew {
pub file_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub file_name: Option<String>,
pub file_size: i32,
pub file_type: String,
@@ -26,7 +26,7 @@ pub struct FileMetadataNew {
pub struct FileMetadata {
#[serde(skip_serializing)]
pub file_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub file_name: Option<String>,
pub file_size: i32,
pub file_type: String,
diff --git a/crates/diesel_models/src/fraud_check.rs b/crates/diesel_models/src/fraud_check.rs
index 2cda6bbd7f5..36fe01ea713 100644
--- a/crates/diesel_models/src/fraud_check.rs
+++ b/crates/diesel_models/src/fraud_check.rs
@@ -12,7 +12,7 @@ use crate::{
pub struct FraudCheck {
pub frm_id: String,
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub attempt_id: String,
pub created_at: PrimitiveDateTime,
pub frm_name: String,
@@ -34,7 +34,7 @@ pub struct FraudCheck {
pub struct FraudCheckNew {
pub frm_id: String,
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub attempt_id: String,
pub created_at: PrimitiveDateTime,
pub frm_name: String,
diff --git a/crates/diesel_models/src/generic_link.rs b/crates/diesel_models/src/generic_link.rs
index 1017d2d47d4..28402692480 100644
--- a/crates/diesel_models/src/generic_link.rs
+++ b/crates/diesel_models/src/generic_link.rs
@@ -1,5 +1,5 @@
use common_utils::{
- consts, id_type,
+ consts,
link_utils::{
EnabledPaymentMethod, GenericLinkStatus, GenericLinkUiConfig, PaymentMethodCollectStatus,
PayoutLinkData, PayoutLinkStatus,
@@ -19,7 +19,7 @@ use crate::{enums as storage_enums, schema::generic_link};
pub struct GenericLink {
pub link_id: String,
pub primary_reference: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
@@ -37,7 +37,7 @@ pub struct GenericLink {
pub struct GenericLinkState {
pub link_id: String,
pub primary_reference: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
@@ -65,7 +65,7 @@ pub struct GenericLinkState {
pub struct GenericLinkNew {
pub link_id: String,
pub primary_reference: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub created_at: Option<PrimitiveDateTime>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
@@ -86,7 +86,7 @@ impl Default for GenericLinkNew {
Self {
link_id: String::default(),
primary_reference: String::default(),
- merchant_id: String::default(),
+ merchant_id: common_utils::id_type::MerchantId::default(),
created_at: Some(now),
last_modified_at: Some(now),
expiry: now + Duration::seconds(consts::DEFAULT_SESSION_EXPIRY),
@@ -125,7 +125,7 @@ impl GenericLinkData {
pub struct PaymentMethodCollectLink {
pub link_id: String,
pub primary_reference: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
@@ -142,7 +142,7 @@ pub struct PaymentMethodCollectLink {
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaymentMethodCollectLinkData {
pub pm_collect_link_id: String,
- pub customer_id: id_type::CustomerId,
+ pub customer_id: common_utils::id_type::CustomerId,
pub link: Secret<String>,
pub client_secret: Secret<String>,
pub session_expiry: u32,
@@ -157,7 +157,7 @@ pub struct PaymentMethodCollectLinkData {
pub struct PayoutLink {
pub link_id: String,
pub primary_reference: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
diff --git a/crates/diesel_models/src/locker_mock_up.rs b/crates/diesel_models/src/locker_mock_up.rs
index e88ad95e236..04f3607a6ca 100644
--- a/crates/diesel_models/src/locker_mock_up.rs
+++ b/crates/diesel_models/src/locker_mock_up.rs
@@ -1,4 +1,3 @@
-use common_utils::id_type;
use diesel::{Identifiable, Insertable, Queryable, Selectable};
use crate::schema::locker_mock_up;
@@ -11,13 +10,13 @@ pub struct LockerMockUp {
pub external_id: String,
pub card_fingerprint: String,
pub card_global_fingerprint: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub card_number: String,
pub card_exp_year: String,
pub card_exp_month: String,
pub name_on_card: Option<String>,
pub nickname: Option<String>,
- pub customer_id: Option<id_type::CustomerId>,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
pub duplicate: Option<bool>,
pub card_cvc: Option<String>,
pub payment_method_id: Option<String>,
@@ -31,14 +30,14 @@ pub struct LockerMockUpNew {
pub external_id: String,
pub card_fingerprint: String,
pub card_global_fingerprint: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub card_number: String,
pub card_exp_year: String,
pub card_exp_month: String,
pub name_on_card: Option<String>,
pub card_cvc: Option<String>,
pub payment_method_id: Option<String>,
- pub customer_id: Option<id_type::CustomerId>,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
pub nickname: Option<String>,
pub enc_card_data: Option<String>,
}
diff --git a/crates/diesel_models/src/mandate.rs b/crates/diesel_models/src/mandate.rs
index 793174dea71..ec4b572e8ee 100644
--- a/crates/diesel_models/src/mandate.rs
+++ b/crates/diesel_models/src/mandate.rs
@@ -1,5 +1,5 @@
use common_enums::MerchantStorageScheme;
-use common_utils::{id_type, pii};
+use common_utils::pii;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::Secret;
use time::PrimitiveDateTime;
@@ -13,8 +13,8 @@ use crate::{enums as storage_enums, schema::mandate};
pub struct Mandate {
pub id: i32,
pub mandate_id: String,
- pub customer_id: id_type::CustomerId,
- pub merchant_id: String,
+ pub customer_id: common_utils::id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
pub mandate_status: storage_enums::MandateStatus,
pub mandate_type: storage_enums::MandateType,
@@ -51,8 +51,8 @@ pub struct Mandate {
#[diesel(table_name = mandate)]
pub struct MandateNew {
pub mandate_id: String,
- pub customer_id: id_type::CustomerId,
- pub merchant_id: String,
+ pub customer_id: common_utils::id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
pub mandate_status: storage_enums::MandateStatus,
pub mandate_type: storage_enums::MandateType,
diff --git a/crates/diesel_models/src/merchant_account.rs b/crates/diesel_models/src/merchant_account.rs
index 800e5636a97..4e99900af2f 100644
--- a/crates/diesel_models/src/merchant_account.rs
+++ b/crates/diesel_models/src/merchant_account.rs
@@ -27,7 +27,7 @@ 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: String,
+ pub merchant_id: id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
@@ -36,7 +36,7 @@ pub struct MerchantAccount {
pub merchant_details: Option<Encryption>,
pub webhook_details: Option<serde_json::Value>,
pub sub_merchants_enabled: Option<bool>,
- pub parent_merchant_id: Option<String>,
+ pub parent_merchant_id: Option<id_type::MerchantId>,
pub publishable_key: Option<String>,
pub storage_scheme: storage_enums::MerchantStorageScheme,
pub locker_id: Option<String>,
@@ -69,7 +69,7 @@ pub struct MerchantAccount {
)]
#[diesel(table_name = merchant_account, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct MerchantAccount {
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
@@ -78,7 +78,7 @@ pub struct MerchantAccount {
pub merchant_details: Option<Encryption>,
pub webhook_details: Option<serde_json::Value>,
pub sub_merchants_enabled: Option<bool>,
- pub parent_merchant_id: Option<String>,
+ pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: Option<String>,
pub storage_scheme: storage_enums::MerchantStorageScheme,
pub locker_id: Option<String>,
@@ -98,16 +98,22 @@ pub struct MerchantAccount {
pub pm_collect_link_config: Option<serde_json::Value>,
}
+impl MerchantAccount {
+ pub fn get_id(&self) -> &id_type::MerchantId {
+ &self.merchant_id
+ }
+}
+
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_account)]
pub struct MerchantAccountNew {
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub merchant_name: Option<Encryption>,
pub merchant_details: Option<Encryption>,
pub return_url: Option<String>,
pub webhook_details: Option<serde_json::Value>,
pub sub_merchants_enabled: Option<bool>,
- pub parent_merchant_id: Option<String>,
+ pub parent_merchant_id: Option<id_type::MerchantId>,
pub enable_payment_response_hash: Option<bool>,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: Option<bool>,
@@ -137,7 +143,7 @@ pub struct MerchantAccountUpdateInternal {
pub return_url: Option<String>,
pub webhook_details: Option<serde_json::Value>,
pub sub_merchants_enabled: Option<bool>,
- pub parent_merchant_id: Option<String>,
+ pub parent_merchant_id: Option<id_type::MerchantId>,
pub enable_payment_response_hash: Option<bool>,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: Option<bool>,
diff --git a/crates/diesel_models/src/merchant_connector_account.rs b/crates/diesel_models/src/merchant_connector_account.rs
index 5a549892dca..4b6ab77d8ae 100644
--- a/crates/diesel_models/src/merchant_connector_account.rs
+++ b/crates/diesel_models/src/merchant_connector_account.rs
@@ -1,6 +1,6 @@
use std::fmt::Debug;
-use common_utils::{encryption::Encryption, pii};
+use common_utils::{encryption::Encryption, id_type, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::Secret;
@@ -19,7 +19,7 @@ use crate::{enums as storage_enums, schema::merchant_connector_account};
#[diesel(table_name = merchant_connector_account, check_for_backend(diesel::pg::Pg))]
pub struct MerchantConnectorAccount {
pub id: i32,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub connector_name: String,
pub connector_account_details: Encryption,
pub test_mode: Option<bool>,
@@ -51,7 +51,7 @@ pub struct MerchantConnectorAccount {
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_connector_account)]
pub struct MerchantConnectorAccountNew {
- pub merchant_id: Option<String>,
+ pub merchant_id: Option<id_type::MerchantId>,
pub connector_type: Option<storage_enums::ConnectorType>,
pub connector_name: Option<String>,
pub connector_account_details: Option<Encryption>,
@@ -82,7 +82,6 @@ pub struct MerchantConnectorAccountNew {
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = merchant_connector_account)]
pub struct MerchantConnectorAccountUpdateInternal {
- pub merchant_id: Option<String>,
pub connector_type: Option<storage_enums::ConnectorType>,
pub connector_name: Option<String>,
pub connector_account_details: Option<Encryption>,
@@ -110,7 +109,7 @@ impl MerchantConnectorAccountUpdateInternal {
source: MerchantConnectorAccount,
) -> MerchantConnectorAccount {
MerchantConnectorAccount {
- merchant_id: self.merchant_id.unwrap_or(source.merchant_id),
+ merchant_id: source.merchant_id,
connector_type: self.connector_type.unwrap_or(source.connector_type),
connector_account_details: self
.connector_account_details
diff --git a/crates/diesel_models/src/merchant_key_store.rs b/crates/diesel_models/src/merchant_key_store.rs
index b11d9970532..5b800670349 100644
--- a/crates/diesel_models/src/merchant_key_store.rs
+++ b/crates/diesel_models/src/merchant_key_store.rs
@@ -16,7 +16,7 @@ use crate::schema::merchant_key_store;
)]
#[diesel(table_name = merchant_key_store, primary_key(merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct MerchantKeyStore {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub key: Encryption,
#[serde(with = "custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
@@ -27,7 +27,7 @@ pub struct MerchantKeyStore {
)]
#[diesel(table_name = merchant_key_store)]
pub struct MerchantKeyStoreNew {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub key: Encryption,
pub created_at: PrimitiveDateTime,
}
@@ -37,6 +37,6 @@ pub struct MerchantKeyStoreNew {
)]
#[diesel(table_name = merchant_key_store)]
pub struct MerchantKeyStoreUpdateInternal {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub key: Encryption,
}
diff --git a/crates/diesel_models/src/payment_attempt.rs b/crates/diesel_models/src/payment_attempt.rs
index 880bf99b3c4..791d4fb26e5 100644
--- a/crates/diesel_models/src/payment_attempt.rs
+++ b/crates/diesel_models/src/payment_attempt.rs
@@ -16,7 +16,7 @@ use crate::schema_v2::payment_attempt;
#[diesel(table_name = payment_attempt, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentAttempt {
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: i64,
@@ -88,7 +88,7 @@ pub struct PaymentAttempt {
pub struct PaymentAttempt {
pub id: Option<i32>,
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: i64,
@@ -172,7 +172,7 @@ pub struct PaymentListFilters {
#[diesel(table_name = payment_attempt)]
pub struct PaymentAttemptNew {
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: i64,
diff --git a/crates/diesel_models/src/payment_intent.rs b/crates/diesel_models/src/payment_intent.rs
index f7ec26e120d..012376ae3d2 100644
--- a/crates/diesel_models/src/payment_intent.rs
+++ b/crates/diesel_models/src/payment_intent.rs
@@ -1,5 +1,5 @@
use common_enums::RequestIncrementalAuthorization;
-use common_utils::{encryption::Encryption, id_type, pii, types::MinorUnit};
+use common_utils::{encryption::Encryption, pii, types::MinorUnit};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -15,12 +15,12 @@ use crate::schema_v2::payment_intent;
#[diesel(table_name = payment_intent, primary_key(payment_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct PaymentIntent {
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub amount_captured: Option<MinorUnit>,
- pub customer_id: Option<id_type::CustomerId>,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
pub description: Option<String>,
pub return_url: Option<String>,
pub metadata: Option<serde_json::Value>,
@@ -76,12 +76,12 @@ pub struct PaymentIntent {
pub struct PaymentIntent {
pub id: Option<i32>,
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub amount_captured: Option<MinorUnit>,
- pub customer_id: Option<id_type::CustomerId>,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
pub description: Option<String>,
pub return_url: Option<String>,
pub metadata: Option<serde_json::Value>,
@@ -137,12 +137,12 @@ pub struct PaymentIntent {
#[diesel(table_name = payment_intent)]
pub struct PaymentIntentNew {
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub amount_captured: Option<MinorUnit>,
- pub customer_id: Option<id_type::CustomerId>,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
pub description: Option<String>,
pub return_url: Option<String>,
pub metadata: Option<serde_json::Value>,
@@ -208,7 +208,7 @@ pub enum PaymentIntentUpdate {
PaymentCreateUpdate {
return_url: Option<String>,
status: Option<storage_enums::IntentStatus>,
- customer_id: Option<id_type::CustomerId>,
+ customer_id: Option<common_utils::id_type::CustomerId>,
shipping_address_id: Option<String>,
billing_address_id: Option<String>,
customer_details: Option<Encryption>,
@@ -271,7 +271,7 @@ pub struct PaymentIntentUpdateFields {
pub currency: storage_enums::Currency,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub status: storage_enums::IntentStatus,
- pub customer_id: Option<id_type::CustomerId>,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
pub shipping_address_id: Option<String>,
pub billing_address_id: Option<String>,
pub return_url: Option<String>,
@@ -301,7 +301,7 @@ pub struct PaymentIntentUpdateInternal {
pub currency: Option<storage_enums::Currency>,
pub status: Option<storage_enums::IntentStatus>,
pub amount_captured: Option<MinorUnit>,
- pub customer_id: Option<id_type::CustomerId>,
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
pub return_url: Option<String>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
diff --git a/crates/diesel_models/src/payment_link.rs b/crates/diesel_models/src/payment_link.rs
index 7937d2fbe30..d5887143019 100644
--- a/crates/diesel_models/src/payment_link.rs
+++ b/crates/diesel_models/src/payment_link.rs
@@ -11,7 +11,7 @@ pub struct PaymentLink {
pub payment_link_id: String,
pub payment_id: String,
pub link_to_pay: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
#[serde(with = "common_utils::custom_serde::iso8601")]
@@ -41,7 +41,7 @@ pub struct PaymentLinkNew {
pub payment_link_id: String,
pub payment_id: String,
pub link_to_pay: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
diff --git a/crates/diesel_models/src/payment_method.rs b/crates/diesel_models/src/payment_method.rs
index 6bb40e4b166..0121ec5112c 100644
--- a/crates/diesel_models/src/payment_method.rs
+++ b/crates/diesel_models/src/payment_method.rs
@@ -1,5 +1,5 @@
use common_enums::MerchantStorageScheme;
-use common_utils::{encryption::Encryption, id_type, pii};
+use common_utils::{encryption::Encryption, pii};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use masking::Secret;
use serde::{Deserialize, Serialize};
@@ -13,8 +13,8 @@ use crate::{enums as storage_enums, schema::payment_methods};
#[diesel(table_name = payment_methods, check_for_backend(diesel::pg::Pg))]
pub struct PaymentMethod {
pub id: i32,
- pub customer_id: id_type::CustomerId,
- pub merchant_id: String,
+ pub customer_id: common_utils::id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
#[diesel(deserialize_as = super::OptionalDieselArray<storage_enums::Currency>)]
pub accepted_currency: Option<Vec<storage_enums::Currency>>,
@@ -52,8 +52,8 @@ pub struct PaymentMethod {
)]
#[diesel(table_name = payment_methods)]
pub struct PaymentMethodNew {
- pub customer_id: id_type::CustomerId,
- pub merchant_id: String,
+ pub customer_id: common_utils::id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_method_id: String,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
diff --git a/crates/diesel_models/src/payout_attempt.rs b/crates/diesel_models/src/payout_attempt.rs
index 9eb2a5a59db..d8e5af55ccc 100644
--- a/crates/diesel_models/src/payout_attempt.rs
+++ b/crates/diesel_models/src/payout_attempt.rs
@@ -1,4 +1,3 @@
-use common_utils::id_type;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{self, Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -12,8 +11,8 @@ use crate::{enums as storage_enums, schema::payout_attempt};
pub struct PayoutAttempt {
pub payout_attempt_id: String,
pub payout_id: String,
- pub customer_id: id_type::CustomerId,
- pub merchant_id: String,
+ pub customer_id: common_utils::id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub address_id: String,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
@@ -48,8 +47,8 @@ pub struct PayoutAttempt {
pub struct PayoutAttemptNew {
pub payout_attempt_id: String,
pub payout_id: String,
- pub customer_id: id_type::CustomerId,
- pub merchant_id: String,
+ pub customer_id: common_utils::id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub address_id: String,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
diff --git a/crates/diesel_models/src/payouts.rs b/crates/diesel_models/src/payouts.rs
index acef00b15d2..9573d056641 100644
--- a/crates/diesel_models/src/payouts.rs
+++ b/crates/diesel_models/src/payouts.rs
@@ -1,4 +1,4 @@
-use common_utils::{id_type, pii, types::MinorUnit};
+use common_utils::{pii, types::MinorUnit};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{self, Deserialize, Serialize};
use time::PrimitiveDateTime;
@@ -12,8 +12,8 @@ use crate::{enums as storage_enums, schema::payouts};
#[diesel(table_name = payouts, primary_key(payout_id), check_for_backend(diesel::pg::Pg))]
pub struct Payouts {
pub payout_id: String,
- pub merchant_id: String,
- pub customer_id: id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ pub customer_id: common_utils::id_type::CustomerId,
pub address_id: String,
pub payout_type: Option<storage_enums::PayoutType>,
pub payout_method_id: Option<String>,
@@ -53,8 +53,8 @@ pub struct Payouts {
#[diesel(table_name = payouts)]
pub struct PayoutsNew {
pub payout_id: String,
- pub merchant_id: String,
- pub customer_id: id_type::CustomerId,
+ pub merchant_id: common_utils::id_type::MerchantId,
+ pub customer_id: common_utils::id_type::CustomerId,
pub address_id: String,
pub payout_type: Option<storage_enums::PayoutType>,
pub payout_method_id: Option<String>,
diff --git a/crates/diesel_models/src/query/address.rs b/crates/diesel_models/src/query/address.rs
index cf3cd41c405..572a5c7fe06 100644
--- a/crates/diesel_models/src/query/address.rs
+++ b/crates/diesel_models/src/query/address.rs
@@ -1,4 +1,3 @@
-use common_utils::id_type;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
@@ -91,8 +90,8 @@ impl Address {
pub async fn update_by_merchant_id_customer_id(
conn: &PgPooledConn,
- customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ customer_id: &common_utils::id_type::CustomerId,
+ merchant_id: &common_utils::id_type::MerchantId,
address: AddressUpdateInternal,
) -> StorageResult<Vec<Self>> {
generics::generic_update_with_results::<<Self as HasTable>::Table, _, _, _>(
@@ -107,7 +106,7 @@ impl Address {
pub async fn find_by_merchant_id_payment_id_address_id<'a>(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
address_id: &str,
) -> StorageResult<Self> {
diff --git a/crates/diesel_models/src/query/api_keys.rs b/crates/diesel_models/src/query/api_keys.rs
index ad7ec7c068a..5dd14501025 100644
--- a/crates/diesel_models/src/query/api_keys.rs
+++ b/crates/diesel_models/src/query/api_keys.rs
@@ -17,7 +17,7 @@ impl ApiKeyNew {
impl ApiKey {
pub async fn update_by_merchant_id_key_id(
conn: &PgPooledConn,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
key_id: String,
api_key_update: ApiKeyUpdate,
) -> StorageResult<Self> {
@@ -56,7 +56,7 @@ impl ApiKey {
pub async fn revoke_by_merchant_id_key_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key_id: &str,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
@@ -70,7 +70,7 @@ impl ApiKey {
pub async fn find_optional_by_merchant_id_key_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key_id: &str,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
@@ -95,7 +95,7 @@ impl ApiKey {
pub async fn find_by_merchant_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> StorageResult<Vec<Self>> {
diff --git a/crates/diesel_models/src/query/authentication.rs b/crates/diesel_models/src/query/authentication.rs
index 86ee4a35c16..41339fc1aac 100644
--- a/crates/diesel_models/src/query/authentication.rs
+++ b/crates/diesel_models/src/query/authentication.rs
@@ -19,7 +19,7 @@ impl AuthenticationNew {
impl Authentication {
pub async fn update_by_merchant_id_authentication_id(
conn: &PgPooledConn,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
authentication_id: String,
authorization_update: AuthenticationUpdate,
) -> StorageResult<Self> {
@@ -58,7 +58,7 @@ impl Authentication {
pub async fn find_by_merchant_id_authentication_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
authentication_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -72,7 +72,7 @@ impl Authentication {
pub async fn find_authentication_by_merchant_id_connector_authentication_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_authentication_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
diff --git a/crates/diesel_models/src/query/authorization.rs b/crates/diesel_models/src/query/authorization.rs
index 59282c78f8b..61b0fb06a01 100644
--- a/crates/diesel_models/src/query/authorization.rs
+++ b/crates/diesel_models/src/query/authorization.rs
@@ -19,7 +19,7 @@ impl AuthorizationNew {
impl Authorization {
pub async fn update_by_merchant_id_authorization_id(
conn: &PgPooledConn,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
authorization_id: String,
authorization_update: AuthorizationUpdate,
) -> StorageResult<Self> {
@@ -58,7 +58,7 @@ impl Authorization {
pub async fn find_by_merchant_id_payment_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
diff --git a/crates/diesel_models/src/query/blocklist.rs b/crates/diesel_models/src/query/blocklist.rs
index 2003a99700c..b295765981d 100644
--- a/crates/diesel_models/src/query/blocklist.rs
+++ b/crates/diesel_models/src/query/blocklist.rs
@@ -16,7 +16,7 @@ impl BlocklistNew {
impl Blocklist {
pub async fn find_by_merchant_id_fingerprint_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -30,7 +30,7 @@ impl Blocklist {
pub async fn list_by_merchant_id_data_kind(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
limit: i64,
offset: i64,
@@ -49,7 +49,7 @@ impl Blocklist {
pub async fn list_by_merchant_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
@@ -63,7 +63,7 @@ impl Blocklist {
pub async fn delete_by_merchant_id_fingerprint_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
diff --git a/crates/diesel_models/src/query/blocklist_fingerprint.rs b/crates/diesel_models/src/query/blocklist_fingerprint.rs
index 370a06801c7..ce9bba3c60f 100644
--- a/crates/diesel_models/src/query/blocklist_fingerprint.rs
+++ b/crates/diesel_models/src/query/blocklist_fingerprint.rs
@@ -16,7 +16,7 @@ impl BlocklistFingerprintNew {
impl BlocklistFingerprint {
pub async fn find_by_merchant_id_fingerprint_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
diff --git a/crates/diesel_models/src/query/blocklist_lookup.rs b/crates/diesel_models/src/query/blocklist_lookup.rs
index f5bc6eda5d7..0cd2b5a2c48 100644
--- a/crates/diesel_models/src/query/blocklist_lookup.rs
+++ b/crates/diesel_models/src/query/blocklist_lookup.rs
@@ -16,7 +16,7 @@ impl BlocklistLookupNew {
impl BlocklistLookup {
pub async fn find_by_merchant_id_fingerprint(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -30,7 +30,7 @@ impl BlocklistLookup {
pub async fn delete_by_merchant_id_fingerprint(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
diff --git a/crates/diesel_models/src/query/business_profile.rs b/crates/diesel_models/src/query/business_profile.rs
index 609a5c55f24..e716e45c650 100644
--- a/crates/diesel_models/src/query/business_profile.rs
+++ b/crates/diesel_models/src/query/business_profile.rs
@@ -48,7 +48,7 @@ impl BusinessProfile {
pub async fn find_by_profile_name_merchant_id(
conn: &PgPooledConn,
profile_name: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
@@ -61,7 +61,7 @@ impl BusinessProfile {
pub async fn list_business_profile_by_merchant_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
@@ -70,7 +70,7 @@ impl BusinessProfile {
_,
>(
conn,
- dsl::merchant_id.eq(merchant_id.to_string()),
+ dsl::merchant_id.eq(merchant_id.to_owned()),
None,
None,
None,
@@ -81,13 +81,13 @@ impl BusinessProfile {
pub async fn delete_by_profile_id_merchant_id(
conn: &PgPooledConn,
profile_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl::profile_id
.eq(profile_id.to_owned())
- .and(dsl::merchant_id.eq(merchant_id.to_string())),
+ .and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.await
}
diff --git a/crates/diesel_models/src/query/capture.rs b/crates/diesel_models/src/query/capture.rs
index c39c4ec7f57..fb2859be7af 100644
--- a/crates/diesel_models/src/query/capture.rs
+++ b/crates/diesel_models/src/query/capture.rs
@@ -49,7 +49,7 @@ impl Capture {
}
pub async fn find_all_by_merchant_id_payment_id_authorized_attempt_id(
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
authorized_attempt_id: &str,
conn: &PgPooledConn,
diff --git a/crates/diesel_models/src/query/connector_response.rs b/crates/diesel_models/src/query/connector_response.rs
index bdc24139ab6..db3ccd68cb8 100644
--- a/crates/diesel_models/src/query/connector_response.rs
+++ b/crates/diesel_models/src/query/connector_response.rs
@@ -139,7 +139,7 @@ impl ConnectorResponse {
pub async fn find_by_payment_id_merchant_id_attempt_id(
conn: &PgPooledConn,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
) -> StorageResult<Self> {
let connector_response: Self =
diff --git a/crates/diesel_models/src/query/customers.rs b/crates/diesel_models/src/query/customers.rs
index f1cc7a73481..dd9353e72d7 100644
--- a/crates/diesel_models/src/query/customers.rs
+++ b/crates/diesel_models/src/query/customers.rs
@@ -1,4 +1,3 @@
-use common_utils::id_type;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
@@ -18,8 +17,8 @@ impl CustomerNew {
impl Customer {
pub async fn update_by_customer_id_merchant_id(
conn: &PgPooledConn,
- customer_id: id_type::CustomerId,
- merchant_id: String,
+ customer_id: common_utils::id_type::CustomerId,
+ merchant_id: common_utils::id_type::MerchantId,
customer: CustomerUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
@@ -45,8 +44,8 @@ impl Customer {
pub async fn delete_by_customer_id_merchant_id(
conn: &PgPooledConn,
- customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ customer_id: &common_utils::id_type::CustomerId,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
@@ -59,8 +58,8 @@ impl Customer {
pub async fn find_by_customer_id_merchant_id(
conn: &PgPooledConn,
- customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ customer_id: &common_utils::id_type::CustomerId,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_by_id::<<Self as HasTable>::Table, _, _>(
conn,
@@ -71,7 +70,7 @@ impl Customer {
pub async fn list_by_merchant_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
@@ -85,8 +84,8 @@ impl Customer {
pub async fn find_optional_by_customer_id_merchant_id(
conn: &PgPooledConn,
- customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ customer_id: &common_utils::id_type::CustomerId,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_by_id_optional::<<Self as HasTable>::Table, _, _>(
conn,
diff --git a/crates/diesel_models/src/query/dashboard_metadata.rs b/crates/diesel_models/src/query/dashboard_metadata.rs
index e180def2c04..15b74a940ad 100644
--- a/crates/diesel_models/src/query/dashboard_metadata.rs
+++ b/crates/diesel_models/src/query/dashboard_metadata.rs
@@ -22,7 +22,7 @@ impl DashboardMetadata {
pub async fn update(
conn: &PgPooledConn,
user_id: Option<String>,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_key: enums::DashboardMetadata,
dashboard_metadata_update: DashboardMetadataUpdate,
@@ -62,7 +62,7 @@ impl DashboardMetadata {
pub async fn find_user_scoped_dashboard_metadata(
conn: &PgPooledConn,
user_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_types: Vec<enums::DashboardMetadata>,
) -> StorageResult<Vec<Self>> {
@@ -84,7 +84,7 @@ impl DashboardMetadata {
pub async fn find_merchant_scoped_dashboard_metadata(
conn: &PgPooledConn,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_types: Vec<enums::DashboardMetadata>,
) -> StorageResult<Vec<Self>> {
@@ -106,7 +106,7 @@ impl DashboardMetadata {
pub async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
conn: &PgPooledConn,
user_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
@@ -120,7 +120,7 @@ impl DashboardMetadata {
pub async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
conn: &PgPooledConn,
user_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
data_key: enums::DashboardMetadata,
) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
diff --git a/crates/diesel_models/src/query/dispute.rs b/crates/diesel_models/src/query/dispute.rs
index 974ed84e236..585bdc82573 100644
--- a/crates/diesel_models/src/query/dispute.rs
+++ b/crates/diesel_models/src/query/dispute.rs
@@ -17,7 +17,7 @@ impl DisputeNew {
impl Dispute {
pub async fn find_by_merchant_id_payment_id_connector_dispute_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
connector_dispute_id: &str,
) -> StorageResult<Option<Self>> {
@@ -33,7 +33,7 @@ impl Dispute {
pub async fn find_by_merchant_id_dispute_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
dispute_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -47,7 +47,7 @@ impl Dispute {
pub async fn find_by_merchant_id_payment_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
diff --git a/crates/diesel_models/src/query/events.rs b/crates/diesel_models/src/query/events.rs
index 1d92baaac46..8b2a1a001f8 100644
--- a/crates/diesel_models/src/query/events.rs
+++ b/crates/diesel_models/src/query/events.rs
@@ -18,7 +18,7 @@ impl EventNew {
impl Event {
pub async fn find_by_merchant_id_event_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -32,7 +32,7 @@ impl Event {
pub async fn list_initial_attempts_by_merchant_id_primary_object_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
@@ -51,7 +51,7 @@ impl Event {
pub async fn list_initial_attempts_by_merchant_id_constraints(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
created_after: Option<time::PrimitiveDateTime>,
created_before: Option<time::PrimitiveDateTime>,
limit: Option<i64>,
@@ -101,7 +101,7 @@ impl Event {
pub async fn list_by_merchant_id_initial_attempt_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
@@ -204,7 +204,7 @@ impl Event {
pub async fn update_by_merchant_id_event_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
event: EventUpdateInternal,
) -> StorageResult<Self> {
diff --git a/crates/diesel_models/src/query/file.rs b/crates/diesel_models/src/query/file.rs
index be81d1bf261..5c12ed231f4 100644
--- a/crates/diesel_models/src/query/file.rs
+++ b/crates/diesel_models/src/query/file.rs
@@ -17,7 +17,7 @@ impl FileMetadataNew {
impl FileMetadata {
pub async fn find_by_merchant_id_file_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -31,7 +31,7 @@ impl FileMetadata {
pub async fn delete_by_merchant_id_file_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
diff --git a/crates/diesel_models/src/query/fraud_check.rs b/crates/diesel_models/src/query/fraud_check.rs
index 18eee0c7281..223c2802f54 100644
--- a/crates/diesel_models/src/query/fraud_check.rs
+++ b/crates/diesel_models/src/query/fraud_check.rs
@@ -41,7 +41,7 @@ impl FraudCheck {
pub async fn get_with_payment_id(
conn: &PgPooledConn,
payment_id: String,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
@@ -55,7 +55,7 @@ impl FraudCheck {
pub async fn get_with_payment_id_if_present(
conn: &PgPooledConn,
payment_id: String,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
diff --git a/crates/diesel_models/src/query/mandate.rs b/crates/diesel_models/src/query/mandate.rs
index 584721ed8f3..26ba6765014 100644
--- a/crates/diesel_models/src/query/mandate.rs
+++ b/crates/diesel_models/src/query/mandate.rs
@@ -1,4 +1,3 @@
-use common_utils::id_type;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table};
use error_stack::report;
@@ -14,7 +13,7 @@ impl MandateNew {
impl Mandate {
pub async fn find_by_merchant_id_mandate_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
mandate_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -28,7 +27,7 @@ impl Mandate {
pub async fn find_by_merchant_id_connector_mandate_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_mandate_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -42,8 +41,8 @@ impl Mandate {
pub async fn find_by_merchant_id_customer_id(
conn: &PgPooledConn,
- merchant_id: &str,
- customer_id: &id_type::CustomerId,
+ merchant_id: &common_utils::id_type::MerchantId,
+ customer_id: &common_utils::id_type::CustomerId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
@@ -64,7 +63,7 @@ impl Mandate {
pub async fn update_by_merchant_id_mandate_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
mandate_id: &str,
mandate: MandateUpdateInternal,
) -> StorageResult<Self> {
diff --git a/crates/diesel_models/src/query/merchant_account.rs b/crates/diesel_models/src/query/merchant_account.rs
index 5c0857fc076..578a1002199 100644
--- a/crates/diesel_models/src/query/merchant_account.rs
+++ b/crates/diesel_models/src/query/merchant_account.rs
@@ -43,7 +43,7 @@ impl MerchantAccount {
pub async fn update_with_specific_fields(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_account: MerchantAccountUpdateInternal,
) -> StorageResult<Self> {
generics::generic_update_with_unique_predicate_get_result::<
@@ -61,7 +61,7 @@ impl MerchantAccount {
pub async fn delete_by_merchant_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
@@ -72,7 +72,7 @@ impl MerchantAccount {
pub async fn find_by_merchant_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
@@ -113,7 +113,7 @@ impl MerchantAccount {
pub async fn list_multiple_merchant_accounts(
conn: &PgPooledConn,
- merchant_ids: Vec<String>,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
diff --git a/crates/diesel_models/src/query/merchant_connector_account.rs b/crates/diesel_models/src/query/merchant_connector_account.rs
index d275211ebde..ee4cc843465 100644
--- a/crates/diesel_models/src/query/merchant_connector_account.rs
+++ b/crates/diesel_models/src/query/merchant_connector_account.rs
@@ -40,7 +40,7 @@ impl MerchantConnectorAccount {
pub async fn delete_by_merchant_id_merchant_connector_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &str,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
@@ -54,7 +54,7 @@ impl MerchantConnectorAccount {
pub async fn find_by_merchant_id_connector(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_label: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -82,7 +82,7 @@ impl MerchantConnectorAccount {
pub async fn find_by_merchant_id_connector_name(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -104,7 +104,7 @@ impl MerchantConnectorAccount {
pub async fn find_by_merchant_id_merchant_connector_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -118,7 +118,7 @@ impl MerchantConnectorAccount {
pub async fn find_by_merchant_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
get_disabled: bool,
) -> StorageResult<Vec<Self>> {
if get_disabled {
diff --git a/crates/diesel_models/src/query/merchant_key_store.rs b/crates/diesel_models/src/query/merchant_key_store.rs
index 4e8e4637678..4b35a43efdf 100644
--- a/crates/diesel_models/src/query/merchant_key_store.rs
+++ b/crates/diesel_models/src/query/merchant_key_store.rs
@@ -16,7 +16,7 @@ impl MerchantKeyStoreNew {
impl MerchantKeyStore {
pub async fn find_by_merchant_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
@@ -27,7 +27,7 @@ impl MerchantKeyStore {
pub async fn delete_by_merchant_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
@@ -38,7 +38,7 @@ impl MerchantKeyStore {
pub async fn list_multiple_key_stores(
conn: &PgPooledConn,
- merchant_ids: Vec<String>,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
diff --git a/crates/diesel_models/src/query/payment_attempt.rs b/crates/diesel_models/src/query/payment_attempt.rs
index 8145b5b11fe..68f16b34457 100644
--- a/crates/diesel_models/src/query/payment_attempt.rs
+++ b/crates/diesel_models/src/query/payment_attempt.rs
@@ -59,7 +59,7 @@ impl PaymentAttempt {
pub async fn find_optional_by_payment_id_merchant_id(
conn: &PgPooledConn,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
@@ -74,7 +74,7 @@ impl PaymentAttempt {
conn: &PgPooledConn,
connector_transaction_id: &str,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
@@ -89,7 +89,7 @@ impl PaymentAttempt {
pub async fn find_last_successful_attempt_by_payment_id_merchant_id(
conn: &PgPooledConn,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
// perform ordering on the application level instead of database level
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
@@ -111,7 +111,7 @@ impl PaymentAttempt {
pub async fn find_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
conn: &PgPooledConn,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
// perform ordering on the application level instead of database level
generics::generic_filter::<<Self as HasTable>::Table, _, _, Self>(
@@ -136,7 +136,7 @@ impl PaymentAttempt {
pub async fn find_by_merchant_id_connector_txn_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_txn_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -150,7 +150,7 @@ impl PaymentAttempt {
pub async fn find_by_merchant_id_attempt_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -164,7 +164,7 @@ impl PaymentAttempt {
pub async fn find_by_merchant_id_preprocessing_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
preprocessing_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -179,7 +179,7 @@ impl PaymentAttempt {
pub async fn find_by_payment_id_merchant_id_attempt_id(
conn: &PgPooledConn,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -195,7 +195,7 @@ impl PaymentAttempt {
pub async fn find_by_merchant_id_payment_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -218,7 +218,7 @@ impl PaymentAttempt {
pub async fn get_filters_for_payments(
conn: &PgPooledConn,
pi: &[PaymentIntent],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<(
Vec<String>,
Vec<enums::Currency>,
@@ -316,7 +316,7 @@ impl PaymentAttempt {
#[allow(clippy::too_many_arguments)]
pub async fn get_total_count_of_attempts(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<String>>,
payment_method: Option<Vec<enums::PaymentMethod>>,
diff --git a/crates/diesel_models/src/query/payment_intent.rs b/crates/diesel_models/src/query/payment_intent.rs
index b658f8d9c93..452e5cbc3f1 100644
--- a/crates/diesel_models/src/query/payment_intent.rs
+++ b/crates/diesel_models/src/query/payment_intent.rs
@@ -47,7 +47,7 @@ impl PaymentIntent {
pub async fn find_by_payment_id_merchant_id(
conn: &PgPooledConn,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
@@ -61,7 +61,7 @@ impl PaymentIntent {
pub async fn find_optional_by_payment_id_merchant_id(
conn: &PgPooledConn,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
diff --git a/crates/diesel_models/src/query/payment_method.rs b/crates/diesel_models/src/query/payment_method.rs
index 8008fec0206..90bf455294d 100644
--- a/crates/diesel_models/src/query/payment_method.rs
+++ b/crates/diesel_models/src/query/payment_method.rs
@@ -1,5 +1,4 @@
use async_bb8_diesel::AsyncRunQueryDsl;
-use common_utils::id_type;
use diesel::{
associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods,
QueryDsl, Table,
@@ -34,7 +33,7 @@ impl PaymentMethod {
pub async fn delete_by_merchant_id_payment_method_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_method_id: &str,
) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, Self>(
@@ -67,7 +66,7 @@ impl PaymentMethod {
pub async fn find_by_merchant_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
@@ -86,8 +85,8 @@ impl PaymentMethod {
pub async fn find_by_customer_id_merchant_id(
conn: &PgPooledConn,
- customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ customer_id: &common_utils::id_type::CustomerId,
+ merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
@@ -104,8 +103,8 @@ impl PaymentMethod {
pub async fn get_count_by_customer_id_merchant_id_status(
conn: &PgPooledConn,
- customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ customer_id: &common_utils::id_type::CustomerId,
+ merchant_id: &common_utils::id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> StorageResult<i64> {
let filter = <Self as HasTable>::table()
@@ -131,8 +130,8 @@ impl PaymentMethod {
pub async fn find_by_customer_id_merchant_id_status(
conn: &PgPooledConn,
- customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ customer_id: &common_utils::id_type::CustomerId,
+ merchant_id: &common_utils::id_type::MerchantId,
status: storage_enums::PaymentMethodStatus,
limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
diff --git a/crates/diesel_models/src/query/payout_attempt.rs b/crates/diesel_models/src/query/payout_attempt.rs
index 0f1785bed51..e415dc6735d 100644
--- a/crates/diesel_models/src/query/payout_attempt.rs
+++ b/crates/diesel_models/src/query/payout_attempt.rs
@@ -55,7 +55,7 @@ impl PayoutAttempt {
pub async fn find_by_merchant_id_payout_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -69,7 +69,7 @@ impl PayoutAttempt {
pub async fn find_by_merchant_id_payout_attempt_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_attempt_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -83,7 +83,7 @@ impl PayoutAttempt {
pub async fn find_by_merchant_id_connector_payout_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_payout_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -97,7 +97,7 @@ impl PayoutAttempt {
pub async fn update_by_merchant_id_payout_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_id: &str,
payout: PayoutAttemptUpdate,
) -> StorageResult<Self> {
@@ -118,7 +118,7 @@ impl PayoutAttempt {
pub async fn update_by_merchant_id_payout_attempt_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_attempt_id: &str,
payout: PayoutAttemptUpdate,
) -> StorageResult<Self> {
@@ -140,7 +140,7 @@ impl PayoutAttempt {
pub async fn get_filters_for_payouts(
conn: &PgPooledConn,
payouts: &[Payouts],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<(
Vec<String>,
Vec<enums::Currency>,
diff --git a/crates/diesel_models/src/query/payouts.rs b/crates/diesel_models/src/query/payouts.rs
index 13756d19e8d..e65062b3922 100644
--- a/crates/diesel_models/src/query/payouts.rs
+++ b/crates/diesel_models/src/query/payouts.rs
@@ -41,7 +41,7 @@ impl Payouts {
pub async fn find_by_merchant_id_payout_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -55,7 +55,7 @@ impl Payouts {
pub async fn update_by_merchant_id_payout_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_id: &str,
payout: PayoutsUpdate,
) -> StorageResult<Self> {
@@ -76,7 +76,7 @@ impl Payouts {
pub async fn find_optional_by_merchant_id_payout_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_id: &str,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
diff --git a/crates/diesel_models/src/query/refund.rs b/crates/diesel_models/src/query/refund.rs
index 0d5d1baf93b..53d57356d48 100644
--- a/crates/diesel_models/src/query/refund.rs
+++ b/crates/diesel_models/src/query/refund.rs
@@ -41,7 +41,7 @@ impl Refund {
// This is required to be changed for KV.
pub async fn find_by_merchant_id_refund_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -55,7 +55,7 @@ impl Refund {
pub async fn find_by_merchant_id_connector_refund_id_connector(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_refund_id: &str,
connector: &str,
) -> StorageResult<Self> {
@@ -72,7 +72,7 @@ impl Refund {
pub async fn find_by_internal_reference_id_merchant_id(
conn: &PgPooledConn,
internal_reference_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
@@ -85,7 +85,7 @@ impl Refund {
pub async fn find_by_merchant_id_connector_transaction_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_transaction_id: &str,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
@@ -108,7 +108,7 @@ impl Refund {
pub async fn find_by_payment_id_merchant_id(
conn: &PgPooledConn,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
diff --git a/crates/diesel_models/src/query/role.rs b/crates/diesel_models/src/query/role.rs
index 3b07afb7b88..7a0b1f8eb65 100644
--- a/crates/diesel_models/src/query/role.rs
+++ b/crates/diesel_models/src/query/role.rs
@@ -23,7 +23,7 @@ impl Role {
pub async fn find_by_role_id_in_merchant_scope(
conn: &PgPooledConn,
role_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
@@ -65,7 +65,7 @@ impl Role {
pub async fn list_roles(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> StorageResult<Vec<Self>> {
let predicate = dsl::merchant_id.eq(merchant_id.to_owned()).or(dsl::org_id
diff --git a/crates/diesel_models/src/query/routing_algorithm.rs b/crates/diesel_models/src/query/routing_algorithm.rs
index 75a1f37f179..6598733f0e5 100644
--- a/crates/diesel_models/src/query/routing_algorithm.rs
+++ b/crates/diesel_models/src/query/routing_algorithm.rs
@@ -20,7 +20,7 @@ impl RoutingAlgorithm {
pub async fn find_by_algorithm_id_merchant_id(
conn: &PgPooledConn,
algorithm_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
@@ -164,7 +164,7 @@ impl RoutingAlgorithm {
pub async fn list_metadata_by_merchant_id(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
limit: i64,
offset: i64,
) -> StorageResult<Vec<RoutingProfileMetadata>> {
@@ -224,7 +224,7 @@ impl RoutingAlgorithm {
pub async fn list_metadata_by_merchant_id_transaction_type(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
transaction_type: &enums::TransactionType,
limit: i64,
offset: i64,
diff --git a/crates/diesel_models/src/query/user/sample_data.rs b/crates/diesel_models/src/query/user/sample_data.rs
index 00fcdbe7ee5..ed88ccf46d7 100644
--- a/crates/diesel_models/src/query/user/sample_data.rs
+++ b/crates/diesel_models/src/query/user/sample_data.rs
@@ -63,7 +63,7 @@ pub async fn insert_refunds(
pub async fn delete_payment_intents(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<PaymentIntent>> {
let query = diesel::delete(<PaymentIntent>::table())
.filter(payment_intent_dsl::merchant_id.eq(merchant_id.to_owned()))
@@ -88,7 +88,7 @@ pub async fn delete_payment_intents(
}
pub async fn delete_payment_attempts(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<PaymentAttempt>> {
let query = diesel::delete(<PaymentAttempt>::table())
.filter(payment_attempt_dsl::merchant_id.eq(merchant_id.to_owned()))
@@ -112,7 +112,10 @@ pub async fn delete_payment_attempts(
})
}
-pub async fn delete_refunds(conn: &PgPooledConn, merchant_id: &str) -> StorageResult<Vec<Refund>> {
+pub async fn delete_refunds(
+ conn: &PgPooledConn,
+ merchant_id: &common_utils::id_type::MerchantId,
+) -> StorageResult<Vec<Refund>> {
let query = diesel::delete(<Refund>::table())
.filter(refund_dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(refund_dsl::payment_id.like("test_%"));
diff --git a/crates/diesel_models/src/query/user_role.rs b/crates/diesel_models/src/query/user_role.rs
index 5dc5309fbed..b3fa3994793 100644
--- a/crates/diesel_models/src/query/user_role.rs
+++ b/crates/diesel_models/src/query/user_role.rs
@@ -21,7 +21,7 @@ impl UserRole {
pub async fn find_by_user_id_merchant_id(
conn: &PgPooledConn,
user_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
@@ -35,7 +35,7 @@ impl UserRole {
pub async fn update_by_user_id_merchant_id(
conn: &PgPooledConn,
user_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
update: UserRoleUpdate,
) -> StorageResult<Self> {
generics::generic_update_with_unique_predicate_get_result::<
@@ -70,7 +70,7 @@ impl UserRole {
pub async fn delete_by_user_id_merchant_id(
conn: &PgPooledConn,
user_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, _>(
conn,
@@ -94,7 +94,7 @@ impl UserRole {
pub async fn list_by_merchant_id(
conn: &PgPooledConn,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
diff --git a/crates/diesel_models/src/refund.rs b/crates/diesel_models/src/refund.rs
index a3e767fdb32..b95ade2df1a 100644
--- a/crates/diesel_models/src/refund.rs
+++ b/crates/diesel_models/src/refund.rs
@@ -25,7 +25,7 @@ pub struct Refund {
pub internal_reference_id: String,
pub refund_id: String, //merchant_reference id
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub connector_transaction_id: String,
pub connector: String,
pub connector_refund_id: Option<String>,
@@ -68,7 +68,7 @@ pub struct Refund {
pub struct RefundNew {
pub refund_id: String,
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub internal_reference_id: String,
pub external_reference_id: Option<String>,
pub connector_transaction_id: String,
@@ -324,7 +324,7 @@ impl RefundUpdate {
pub struct RefundCoreWorkflow {
pub refund_internal_reference_id: String,
pub connector_transaction_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: String,
}
diff --git a/crates/diesel_models/src/role.rs b/crates/diesel_models/src/role.rs
index cf23e36d838..cf38f49aadf 100644
--- a/crates/diesel_models/src/role.rs
+++ b/crates/diesel_models/src/role.rs
@@ -10,7 +10,7 @@ pub struct Role {
pub id: i32,
pub role_name: String,
pub role_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub org_id: id_type::OrganizationId,
#[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)]
pub groups: Vec<enums::PermissionGroup>,
@@ -26,7 +26,7 @@ pub struct Role {
pub struct RoleNew {
pub role_name: String,
pub role_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub org_id: id_type::OrganizationId,
#[diesel(deserialize_as = super::DieselArray<enums::PermissionGroup>)]
pub groups: Vec<enums::PermissionGroup>,
diff --git a/crates/diesel_models/src/routing_algorithm.rs b/crates/diesel_models/src/routing_algorithm.rs
index 4634dd1af49..e2566783e9b 100644
--- a/crates/diesel_models/src/routing_algorithm.rs
+++ b/crates/diesel_models/src/routing_algorithm.rs
@@ -8,7 +8,7 @@ use crate::{enums, schema::routing_algorithm};
pub struct RoutingAlgorithm {
pub algorithm_id: String,
pub profile_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub name: String,
pub description: Option<String>,
pub kind: enums::RoutingAlgorithmKind,
diff --git a/crates/diesel_models/src/user.rs b/crates/diesel_models/src/user.rs
index 9d6514916d8..8469e4c2cab 100644
--- a/crates/diesel_models/src/user.rs
+++ b/crates/diesel_models/src/user.rs
@@ -19,7 +19,7 @@ pub struct User {
pub is_verified: bool,
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
- pub preferred_merchant_id: Option<String>,
+ pub preferred_merchant_id: Option<common_utils::id_type::MerchantId>,
pub totp_status: TotpStatus,
pub totp_secret: Option<Encryption>,
#[diesel(deserialize_as = OptionalDieselArray<Secret<String>>)]
@@ -39,7 +39,7 @@ pub struct UserNew {
pub is_verified: bool,
pub created_at: Option<PrimitiveDateTime>,
pub last_modified_at: Option<PrimitiveDateTime>,
- pub preferred_merchant_id: Option<String>,
+ pub preferred_merchant_id: Option<common_utils::id_type::MerchantId>,
pub totp_status: TotpStatus,
pub totp_secret: Option<Encryption>,
pub totp_recovery_codes: Option<Vec<Secret<String>>>,
@@ -53,7 +53,7 @@ pub struct UserUpdateInternal {
password: Option<Secret<String>>,
is_verified: Option<bool>,
last_modified_at: PrimitiveDateTime,
- preferred_merchant_id: Option<String>,
+ preferred_merchant_id: Option<common_utils::id_type::MerchantId>,
totp_status: Option<TotpStatus>,
totp_secret: Option<Encryption>,
totp_recovery_codes: Option<Vec<Secret<String>>>,
@@ -66,7 +66,7 @@ pub enum UserUpdate {
AccountUpdate {
name: Option<String>,
is_verified: Option<bool>,
- preferred_merchant_id: Option<String>,
+ preferred_merchant_id: Option<common_utils::id_type::MerchantId>,
},
TotpUpdate {
totp_status: Option<TotpStatus>,
diff --git a/crates/diesel_models/src/user/dashboard_metadata.rs b/crates/diesel_models/src/user/dashboard_metadata.rs
index 78caa20a934..291b4d2a3e6 100644
--- a/crates/diesel_models/src/user/dashboard_metadata.rs
+++ b/crates/diesel_models/src/user/dashboard_metadata.rs
@@ -9,7 +9,7 @@ use crate::{enums, schema::dashboard_metadata};
pub struct DashboardMetadata {
pub id: i32,
pub user_id: Option<String>,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub org_id: id_type::OrganizationId,
pub data_key: enums::DashboardMetadata,
pub data_value: serde_json::Value,
@@ -25,7 +25,7 @@ pub struct DashboardMetadata {
#[diesel(table_name = dashboard_metadata)]
pub struct DashboardMetadataNew {
pub user_id: Option<String>,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub org_id: id_type::OrganizationId,
pub data_key: enums::DashboardMetadata,
pub data_value: serde_json::Value,
diff --git a/crates/diesel_models/src/user/sample_data.rs b/crates/diesel_models/src/user/sample_data.rs
index c1ccdfa450f..035d99e554b 100644
--- a/crates/diesel_models/src/user/sample_data.rs
+++ b/crates/diesel_models/src/user/sample_data.rs
@@ -20,7 +20,7 @@ use crate::{
#[diesel(table_name = payment_attempt)]
pub struct PaymentAttemptBatchNew {
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub attempt_id: String,
pub status: AttemptStatus,
pub amount: i64,
diff --git a/crates/diesel_models/src/user_role.rs b/crates/diesel_models/src/user_role.rs
index 28cbac2f735..7f7c8484e8f 100644
--- a/crates/diesel_models/src/user_role.rs
+++ b/crates/diesel_models/src/user_role.rs
@@ -9,7 +9,7 @@ use crate::{enums, schema::user_roles};
pub struct UserRole {
pub id: i32,
pub user_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub role_id: String,
pub org_id: id_type::OrganizationId,
pub status: enums::UserStatus,
@@ -23,7 +23,7 @@ pub struct UserRole {
#[diesel(table_name = user_roles)]
pub struct UserRoleNew {
pub user_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub role_id: String,
pub org_id: id_type::OrganizationId,
pub status: enums::UserStatus,
diff --git a/crates/hyperswitch_domain_models/src/behaviour.rs b/crates/hyperswitch_domain_models/src/behaviour.rs
index 07911e8ea69..29f9d6bab7d 100644
--- a/crates/hyperswitch_domain_models/src/behaviour.rs
+++ b/crates/hyperswitch_domain_models/src/behaviour.rs
@@ -1,6 +1,6 @@
use common_utils::{
errors::{CustomResult, ValidationError},
- types::keymanager::KeyManagerState,
+ types::keymanager::{Identifier, KeyManagerState},
};
use masking::Secret;
@@ -15,7 +15,7 @@ pub trait Conversion {
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
- key_store_ref_id: String,
+ key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized;
@@ -29,7 +29,7 @@ pub trait ReverseConversion<SrcType: Conversion> {
self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
- key_store_ref_id: String,
+ key_manager_identifier: Identifier,
) -> CustomResult<SrcType, ValidationError>;
}
@@ -39,8 +39,8 @@ impl<T: Send, U: Conversion<DstType = T>> ReverseConversion<U> for T {
self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
- key_store_ref_id: String,
+ key_manager_identifier: Identifier,
) -> CustomResult<U, ValidationError> {
- U::convert_back(state, self, key, key_store_ref_id).await
+ U::convert_back(state, self, key, key_manager_identifier).await
}
}
diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rs
index ef7c816b0d6..558a8b4469c 100644
--- a/crates/hyperswitch_domain_models/src/customer.rs
+++ b/crates/hyperswitch_domain_models/src/customer.rs
@@ -4,7 +4,7 @@ use common_utils::{
encryption::Encryption,
errors::{CustomResult, ValidationError},
id_type, pii,
- types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
+ types::keymanager::{self, KeyManagerState, ToEncryptable},
};
use diesel_models::customers::CustomerUpdateInternal;
use error_stack::ResultExt;
@@ -24,7 +24,7 @@ pub enum SoftDeleteStatus {
pub struct Customer {
pub id: Option<i32>,
pub customer_id: id_type::CustomerId,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub name: crypto::OptionalEncryptableName,
pub email: crypto::OptionalEncryptableEmail,
pub phone: crypto::OptionalEncryptablePhone,
@@ -73,7 +73,7 @@ impl super::behaviour::Conversion for Customer {
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
- _key_store_ref_id: String,
+ _key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
@@ -85,7 +85,7 @@ impl super::behaviour::Conversion for Customer {
phone: item.phone.clone(),
email: item.email.clone(),
}),
- Identifier::Merchant(item.merchant_id.clone()),
+ keymanager::Identifier::Merchant(item.merchant_id.clone()),
key.peek(),
)
.await
diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rs
index 5ff3fec14c0..eb5905c507e 100644
--- a/crates/hyperswitch_domain_models/src/merchant_account.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_account.rs
@@ -1,10 +1,3 @@
-#[cfg(all(
- any(feature = "v1", feature = "v2"),
- not(feature = "merchant_account_v2")
-))]
-use common_utils::id_type;
-#[cfg(all(feature = "v2", feature = "merchant_account_v2"))]
-use common_utils::id_type;
use common_utils::{
crypto::{OptionalEncryptableName, OptionalEncryptableValue},
date_time,
@@ -12,7 +5,7 @@ use common_utils::{
errors::{CustomResult, ValidationError},
ext_traits::ValueExt,
pii,
- types::keymanager,
+ types::keymanager::{self},
};
use diesel_models::{
enums::MerchantStorageScheme, merchant_account::MerchantAccountUpdateInternal,
@@ -30,7 +23,7 @@ use crate::type_encryption::{decrypt_optional, AsyncLift};
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantAccount {
pub id: Option<i32>,
- pub merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
@@ -39,7 +32,7 @@ pub struct MerchantAccount {
pub merchant_details: OptionalEncryptableValue,
pub webhook_details: Option<serde_json::Value>,
pub sub_merchants_enabled: Option<bool>,
- pub parent_merchant_id: Option<String>,
+ pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub locker_id: Option<String>,
@@ -51,7 +44,7 @@ pub struct MerchantAccount {
pub modified_at: time::PrimitiveDateTime,
pub intent_fulfillment_time: Option<i64>,
pub payout_routing_algorithm: Option<serde_json::Value>,
- pub organization_id: id_type::OrganizationId,
+ pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<String>,
pub recon_status: diesel_models::enums::ReconStatus,
@@ -59,10 +52,85 @@ pub struct MerchantAccount {
pub pm_collect_link_config: Option<serde_json::Value>,
}
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "merchant_account_v2")
+))]
+#[derive(Clone)]
+/// Set the private fields of merchant account
+pub struct MerchantAccountSetter {
+ pub merchant_id: common_utils::id_type::MerchantId,
+ 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 merchant_name: OptionalEncryptableName,
+ pub merchant_details: OptionalEncryptableValue,
+ pub webhook_details: Option<serde_json::Value>,
+ pub sub_merchants_enabled: Option<bool>,
+ pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
+ pub publishable_key: String,
+ pub storage_scheme: MerchantStorageScheme,
+ pub locker_id: Option<String>,
+ pub metadata: Option<pii::SecretSerdeValue>,
+ pub routing_algorithm: Option<serde_json::Value>,
+ pub primary_business_details: serde_json::Value,
+ pub frm_routing_algorithm: Option<serde_json::Value>,
+ pub created_at: time::PrimitiveDateTime,
+ pub modified_at: time::PrimitiveDateTime,
+ pub intent_fulfillment_time: Option<i64>,
+ pub payout_routing_algorithm: Option<serde_json::Value>,
+ pub organization_id: common_utils::id_type::OrganizationId,
+ pub is_recon_enabled: bool,
+ pub default_profile: Option<String>,
+ pub recon_status: diesel_models::enums::ReconStatus,
+ pub payment_link_config: Option<serde_json::Value>,
+ pub pm_collect_link_config: Option<serde_json::Value>,
+}
+
+#[cfg(all(
+ any(feature = "v1", feature = "v2"),
+ not(feature = "merchant_account_v2")
+))]
+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,
+ payment_response_hash_key: item.payment_response_hash_key,
+ redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
+ merchant_name: item.merchant_name,
+ merchant_details: item.merchant_details,
+ webhook_details: item.webhook_details,
+ sub_merchants_enabled: item.sub_merchants_enabled,
+ parent_merchant_id: item.parent_merchant_id,
+ publishable_key: item.publishable_key,
+ storage_scheme: item.storage_scheme,
+ locker_id: item.locker_id,
+ metadata: item.metadata,
+ routing_algorithm: item.routing_algorithm,
+ primary_business_details: item.primary_business_details,
+ frm_routing_algorithm: item.frm_routing_algorithm,
+ created_at: item.created_at,
+ modified_at: item.modified_at,
+ intent_fulfillment_time: item.intent_fulfillment_time,
+ payout_routing_algorithm: item.payout_routing_algorithm,
+ organization_id: item.organization_id,
+ is_recon_enabled: item.is_recon_enabled,
+ default_profile: item.default_profile,
+ recon_status: item.recon_status,
+ payment_link_config: item.payment_link_config,
+ pm_collect_link_config: item.pm_collect_link_config,
+ }
+ }
+}
+
#[cfg(all(feature = "v2", feature = "merchant_account_v2"))]
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantAccount {
- pub merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
@@ -83,7 +151,7 @@ pub struct MerchantAccount {
pub modified_at: time::PrimitiveDateTime,
pub intent_fulfillment_time: Option<i64>,
pub payout_routing_algorithm: Option<serde_json::Value>,
- pub organization_id: id_type::OrganizationId,
+ pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<String>,
pub recon_status: diesel_models::enums::ReconStatus,
@@ -91,6 +159,13 @@ pub struct MerchantAccount {
pub pm_collect_link_config: Option<serde_json::Value>,
}
+impl MerchantAccount {
+ /// Get the unique identifier of MerchantAccount
+ pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
+ &self.merchant_id
+ }
+}
+
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum MerchantAccountUpdate {
@@ -100,7 +175,7 @@ pub enum MerchantAccountUpdate {
return_url: Option<String>,
webhook_details: Option<serde_json::Value>,
sub_merchants_enabled: Option<bool>,
- parent_merchant_id: Option<String>,
+ parent_merchant_id: Option<common_utils::id_type::MerchantId>,
enable_payment_response_hash: Option<bool>,
payment_response_hash_key: Option<String>,
redirect_to_merchant_with_http_post: Option<bool>,
@@ -240,7 +315,7 @@ impl super::behaviour::Conversion for MerchantAccount {
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
- key_store_ref_id: String,
+ key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
@@ -251,8 +326,6 @@ impl super::behaviour::Conversion for MerchantAccount {
field_name: "publishable_key".to_string(),
})?;
- let identifier = keymanager::Identifier::Merchant(key_store_ref_id.clone());
-
async {
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
merchant_id: item.merchant_id,
@@ -263,13 +336,13 @@ impl super::behaviour::Conversion for MerchantAccount {
merchant_name: item
.merchant_name
.async_lift(|inner| {
- decrypt_optional(state, inner, identifier.clone(), key.peek())
+ decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek())
})
.await?,
merchant_details: item
.merchant_details
.async_lift(|inner| {
- decrypt_optional(state, inner, identifier.clone(), key.peek())
+ decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek())
})
.await?,
webhook_details: item.webhook_details,
@@ -380,7 +453,7 @@ impl super::behaviour::Conversion for MerchantAccount {
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
- key_store_ref_id: String,
+ key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
@@ -390,7 +463,6 @@ impl super::behaviour::Conversion for MerchantAccount {
.ok_or(ValidationError::MissingRequiredField {
field_name: "publishable_key".to_string(),
})?;
- let identifier = keymanager::Identifier::Merchant(key_store_ref_id.clone());
async {
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
id: Some(item.id),
@@ -402,13 +474,13 @@ impl super::behaviour::Conversion for MerchantAccount {
merchant_name: item
.merchant_name
.async_lift(|inner| {
- decrypt_optional(state, inner, identifier.clone(), key.peek())
+ decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek())
})
.await?,
merchant_details: item
.merchant_details
.async_lift(|inner| {
- decrypt_optional(state, inner, identifier.clone(), key.peek())
+ decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek())
})
.await?,
webhook_details: item.webhook_details,
diff --git a/crates/hyperswitch_domain_models/src/merchant_key_store.rs b/crates/hyperswitch_domain_models/src/merchant_key_store.rs
index d48403b62ff..bfd75a08fa3 100644
--- a/crates/hyperswitch_domain_models/src/merchant_key_store.rs
+++ b/crates/hyperswitch_domain_models/src/merchant_key_store.rs
@@ -2,7 +2,7 @@ use common_utils::{
crypto::Encryptable,
custom_serde, date_time,
errors::{CustomResult, ValidationError},
- types::keymanager::{Identifier, KeyManagerState},
+ types::keymanager::{self, KeyManagerState},
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
@@ -12,7 +12,7 @@ use crate::type_encryption::decrypt;
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantKeyStore {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub key: Encryptable<Secret<Vec<u8>>>,
#[serde(with = "custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
@@ -34,12 +34,12 @@ impl super::behaviour::Conversion for MerchantKeyStore {
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
- _key_store_ref_id: String,
+ _key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
- let identifier = Identifier::Merchant(item.merchant_id.clone());
+ let identifier = keymanager::Identifier::Merchant(item.merchant_id.clone());
Ok(Self {
key: decrypt(state, item.key, identifier, key.peek())
.await
diff --git a/crates/hyperswitch_domain_models/src/payments.rs b/crates/hyperswitch_domain_models/src/payments.rs
index 0e12eac2f98..ac79bc1a942 100644
--- a/crates/hyperswitch_domain_models/src/payments.rs
+++ b/crates/hyperswitch_domain_models/src/payments.rs
@@ -13,7 +13,7 @@ use crate::RemoteStorageObject;
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub struct PaymentIntent {
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
index 2bf8f562604..7e4c5524727 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
@@ -1,14 +1,13 @@
use api_models::enums::Connector;
use common_enums as storage_enums;
-#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "payment_v2")))]
-use common_utils::types::keymanager::KeyManagerState;
-#[cfg(all(feature = "v2", feature = "payment_v2"))]
-use common_utils::types::keymanager::KeyManagerState;
use common_utils::{
encryption::Encryption,
errors::{CustomResult, ValidationError},
- pii,
- types::MinorUnit,
+ id_type, pii,
+ types::{
+ keymanager::{self, KeyManagerState},
+ MinorUnit,
+ },
};
use error_stack::ResultExt;
use masking::PeekInterface;
@@ -42,27 +41,27 @@ pub trait PaymentAttemptInterface {
&self,
connector_transaction_id: &str,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError>;
async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError>;
async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError>;
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
connector_txn_id: &str,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError>;
@@ -70,7 +69,7 @@ pub trait PaymentAttemptInterface {
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
attempt_id: &str,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError>;
@@ -78,20 +77,20 @@ pub trait PaymentAttemptInterface {
async fn find_payment_attempt_by_attempt_id_merchant_id(
&self,
attempt_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError>;
async fn find_payment_attempt_by_preprocessing_id_merchant_id(
&self,
preprocessing_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError>;
async fn find_attempts_by_merchant_id_payment_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_id: &str,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError>;
@@ -99,14 +98,14 @@ pub trait PaymentAttemptInterface {
async fn get_filters_for_payments(
&self,
pi: &[PaymentIntent],
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentListFilters, errors::StorageError>;
#[allow(clippy::too_many_arguments)]
async fn get_total_count_of_filtered_payment_attempts(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<Connector>>,
payment_method: Option<Vec<storage_enums::PaymentMethod>>,
@@ -120,7 +119,7 @@ pub trait PaymentAttemptInterface {
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PaymentAttempt {
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
@@ -210,7 +209,7 @@ pub struct PaymentListFilters {
#[derive(Clone, Debug, Default, Serialize, Deserialize)]
pub struct PaymentAttemptNew {
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
@@ -548,20 +547,14 @@ impl behaviour::Conversion for PaymentIntent {
state: &KeyManagerState,
storage_model: Self::DstType,
key: &masking::Secret<Vec<u8>>,
- key_store_ref_id: String,
+ key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
async {
- let inner_decrypt = |inner| {
- decrypt_optional(
- state,
- inner,
- common_utils::types::keymanager::Identifier::Merchant(key_store_ref_id.clone()),
- key.peek(),
- )
- };
+ let inner_decrypt =
+ |inner| decrypt_optional(state, inner, key_manager_identifier, key.peek());
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id,
@@ -744,20 +737,14 @@ impl behaviour::Conversion for PaymentIntent {
state: &KeyManagerState,
storage_model: Self::DstType,
key: &masking::Secret<Vec<u8>>,
- key_store_ref_id: String,
+ key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
async {
- let inner_decrypt = |inner| {
- decrypt_optional(
- state,
- inner,
- common_utils::types::keymanager::Identifier::Merchant(key_store_ref_id.clone()),
- key.peek(),
- )
- };
+ let inner_decrypt =
+ |inner| decrypt_optional(state, inner, key_manager_identifier.clone(), key.peek());
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id,
diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
index f4f6be97055..3d305656797 100644
--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs
@@ -36,7 +36,7 @@ pub trait PaymentIntentInterface {
&self,
state: &KeyManagerState,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
merchant_key_store: &MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, errors::StorageError>;
@@ -51,7 +51,7 @@ pub trait PaymentIntentInterface {
async fn filter_payment_intent_by_constraints(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
filters: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
@@ -61,7 +61,7 @@ pub trait PaymentIntentInterface {
async fn filter_payment_intents_by_time_range_constraints(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
time_range: &api_models::payments::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
@@ -71,7 +71,7 @@ pub trait PaymentIntentInterface {
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
@@ -80,7 +80,7 @@ pub trait PaymentIntentInterface {
#[cfg(feature = "olap")]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, errors::StorageError>;
@@ -97,7 +97,7 @@ pub struct CustomerData {
#[derive(Clone, Debug, PartialEq)]
pub struct PaymentIntentNew {
pub payment_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
diff --git a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
index a0786f4de7d..fe1cf4c9bdf 100644
--- a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
+++ b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
@@ -27,14 +27,14 @@ pub trait PayoutAttemptInterface {
async fn find_payout_attempt_by_merchant_id_payout_attempt_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &id_type::MerchantId,
_payout_attempt_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError>;
async fn find_payout_attempt_by_merchant_id_connector_payout_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &id_type::MerchantId,
_connector_payout_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError>;
@@ -42,7 +42,7 @@ pub trait PayoutAttemptInterface {
async fn get_filters_for_payouts(
&self,
payout: &[Payouts],
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutListFilters, errors::StorageError>;
}
@@ -60,7 +60,7 @@ pub struct PayoutAttempt {
pub payout_attempt_id: String,
pub payout_id: String,
pub customer_id: id_type::CustomerId,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub address_id: String,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
@@ -85,7 +85,7 @@ pub struct PayoutAttemptNew {
pub payout_attempt_id: String,
pub payout_id: String,
pub customer_id: id_type::CustomerId,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub address_id: String,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
@@ -111,7 +111,7 @@ impl Default for PayoutAttemptNew {
payout_attempt_id: String::default(),
payout_id: String::default(),
customer_id: generate_customer_id_of_default_length(),
- merchant_id: String::default(),
+ merchant_id: id_type::MerchantId::default(),
address_id: String::default(),
connector: None,
connector_payout_id: Some(String::default()),
diff --git a/crates/hyperswitch_domain_models/src/payouts/payouts.rs b/crates/hyperswitch_domain_models/src/payouts/payouts.rs
index 78cb572a8bb..16b4bf7f912 100644
--- a/crates/hyperswitch_domain_models/src/payouts/payouts.rs
+++ b/crates/hyperswitch_domain_models/src/payouts/payouts.rs
@@ -19,7 +19,7 @@ pub trait PayoutsInterface {
async fn find_payout_by_merchant_id_payout_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &id_type::MerchantId,
_payout_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, errors::StorageError>;
@@ -34,7 +34,7 @@ pub trait PayoutsInterface {
async fn find_optional_payout_by_merchant_id_payout_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &id_type::MerchantId,
_payout_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Option<Payouts>, errors::StorageError>;
@@ -42,7 +42,7 @@ pub trait PayoutsInterface {
#[cfg(feature = "olap")]
async fn filter_payouts_by_constraints(
&self,
- _merchant_id: &str,
+ _merchant_id: &id_type::MerchantId,
_filters: &PayoutFetchConstraints,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, errors::StorageError>;
@@ -50,7 +50,7 @@ pub trait PayoutsInterface {
#[cfg(feature = "olap")]
async fn filter_payouts_and_attempts(
&self,
- _merchant_id: &str,
+ _merchant_id: &id_type::MerchantId,
_filters: &PayoutFetchConstraints,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<
@@ -61,7 +61,7 @@ pub trait PayoutsInterface {
#[cfg(feature = "olap")]
async fn filter_payouts_by_time_range_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
time_range: &api_models::payments::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, errors::StorageError>;
@@ -70,7 +70,7 @@ pub trait PayoutsInterface {
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Payouts {
pub payout_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub customer_id: id_type::CustomerId,
pub address_id: String,
pub payout_type: Option<storage_enums::PayoutType>,
@@ -98,7 +98,7 @@ pub struct Payouts {
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PayoutsNew {
pub payout_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub customer_id: id_type::CustomerId,
pub address_id: String,
pub payout_type: Option<storage_enums::PayoutType>,
@@ -129,7 +129,7 @@ impl Default for PayoutsNew {
Self {
payout_id: String::default(),
- merchant_id: String::default(),
+ merchant_id: id_type::MerchantId::default(),
customer_id: common_utils::generate_customer_id_of_default_length(),
address_id: String::default(),
payout_type: Some(storage_enums::PayoutType::default()),
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
index 248c1f35298..c2df2686449 100644
--- a/crates/hyperswitch_domain_models/src/router_data.rs
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -8,7 +8,7 @@ use crate::{payment_address::PaymentAddress, payment_method_data};
#[derive(Debug, Clone)]
pub struct RouterData<Flow, Request, Response> {
pub flow: PhantomData<Flow>,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub customer_id: Option<id_type::CustomerId>,
pub connector_customer: Option<String>,
pub connector: String,
diff --git a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
index afba9e14d72..b2dea40082a 100644
--- a/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
@@ -11,7 +11,7 @@ use crate::{
#[derive(Debug, Clone)]
pub struct PaymentFlowData {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub connector_customer: Option<String>,
pub payment_id: String,
@@ -53,7 +53,7 @@ pub struct PaymentFlowData {
#[derive(Debug, Clone)]
pub struct RefundFlowData {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub payment_id: String,
pub attempt_id: String,
@@ -72,7 +72,7 @@ pub struct RefundFlowData {
#[cfg(feature = "payouts")]
#[derive(Debug, Clone)]
pub struct PayoutFlowData {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub connector_customer: Option<String>,
pub return_url: Option<String>,
@@ -88,7 +88,7 @@ pub struct PayoutFlowData {
#[cfg(feature = "frm")]
#[derive(Debug, Clone)]
pub struct FrmFlowData {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: String,
pub attempt_id: String,
pub payment_method: common_enums::enums::PaymentMethod,
@@ -104,14 +104,14 @@ pub struct FrmFlowData {
#[derive(Debug, Clone)]
pub struct ExternalAuthenticationFlowData {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub connector_meta_data: Option<pii::SecretSerdeValue>,
pub address: PaymentAddress,
}
#[derive(Debug, Clone)]
pub struct DisputesFlowData {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: String,
pub attempt_id: String,
pub payment_method: common_enums::enums::PaymentMethod,
@@ -127,14 +127,14 @@ pub struct DisputesFlowData {
#[derive(Debug, Clone)]
pub struct MandateRevokeFlowData {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: common_utils::id_type::CustomerId,
pub payment_id: Option<String>,
}
#[derive(Debug, Clone)]
pub struct WebhookSourceVerifyData {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Debug, Clone)]
@@ -142,7 +142,7 @@ pub struct AccessTokenFlowData {}
#[derive(Debug, Clone)]
pub struct FilesFlowData {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: String,
pub attempt_id: String,
pub return_url: Option<String>,
diff --git a/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs b/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
index 79b172e9ea7..5edd8d68c32 100644
--- a/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
+++ b/crates/hyperswitch_interfaces/src/events/connector_api_logs.rs
@@ -17,7 +17,7 @@ pub struct ConnectorEvent {
url: String,
method: String,
payment_id: String,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
created_at: i128,
/// Connector Event Request ID
pub request_id: String,
@@ -37,7 +37,7 @@ impl ConnectorEvent {
url: String,
method: Method,
payment_id: String,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
request_id: Option<&RequestId>,
latency: u128,
refund_id: Option<String>,
diff --git a/crates/hyperswitch_interfaces/src/webhooks.rs b/crates/hyperswitch_interfaces/src/webhooks.rs
index b9148d67015..e863af40a39 100644
--- a/crates/hyperswitch_interfaces/src/webhooks.rs
+++ b/crates/hyperswitch_interfaces/src/webhooks.rs
@@ -45,7 +45,7 @@ pub trait IncomingWebhook: ConnectorCommon + Sync {
async fn decode_webhook_body(
&self,
request: &IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_name: &str,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -79,12 +79,12 @@ pub trait IncomingWebhook: ConnectorCommon + Sync {
/// fn get_webhook_source_verification_merchant_secret
async fn get_webhook_source_verification_merchant_secret(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> {
let debug_suffix = format!(
- "For merchant_id: {}, and connector_name: {}",
+ "For merchant_id: {:?}, and connector_name: {}",
merchant_id, connector_name
);
let default_secret = "default_secret".to_string();
@@ -136,7 +136,7 @@ pub trait IncomingWebhook: ConnectorCommon + Sync {
fn get_webhook_source_verification_message(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(Vec::new())
@@ -146,7 +146,7 @@ pub trait IncomingWebhook: ConnectorCommon + Sync {
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_name: &str,
diff --git a/crates/pm_auth/src/types.rs b/crates/pm_auth/src/types.rs
index e5fb8fb6441..4c20e879d8b 100644
--- a/crates/pm_auth/src/types.rs
+++ b/crates/pm_auth/src/types.rs
@@ -10,7 +10,7 @@ use masking::Secret;
#[derive(Debug, Clone)]
pub struct PaymentAuthRouterData<F, Request, Response> {
pub flow: PhantomData<F>,
- pub merchant_id: Option<String>,
+ pub merchant_id: Option<id_type::MerchantId>,
pub connector: Option<String>,
pub request: Request,
pub response: Result<Response, ErrorResponse>,
diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rs
index 3cde172d231..b7e89929a8a 100644
--- a/crates/router/src/analytics.rs
+++ b/crates/router/src/analytics.rs
@@ -191,13 +191,9 @@ pub mod routes {
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
- analytics::payments::get_metrics(
- &state.pool,
- &auth.merchant_account.merchant_id,
- req,
- )
- .await
- .map(ApplicationResponse::Json)
+ analytics::payments::get_metrics(&state.pool, auth.merchant_account.get_id(), req)
+ .await
+ .map(ApplicationResponse::Json)
},
&auth::JWTAuth(Permission::Analytics),
api_locking::LockAction::NotApplicable,
@@ -229,7 +225,7 @@ pub mod routes {
|state, auth: AuthenticationData, req, _| async move {
analytics::payment_intents::get_metrics(
&state.pool,
- &auth.merchant_account.merchant_id,
+ auth.merchant_account.get_id(),
req,
)
.await
@@ -263,13 +259,9 @@ pub mod routes {
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
- analytics::refunds::get_metrics(
- &state.pool,
- &auth.merchant_account.merchant_id,
- req,
- )
- .await
- .map(ApplicationResponse::Json)
+ analytics::refunds::get_metrics(&state.pool, auth.merchant_account.get_id(), req)
+ .await
+ .map(ApplicationResponse::Json)
},
&auth::JWTAuth(Permission::Analytics),
api_locking::LockAction::NotApplicable,
@@ -299,7 +291,7 @@ pub mod routes {
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
- analytics::frm::get_metrics(&state.pool, &auth.merchant_account.merchant_id, req)
+ analytics::frm::get_metrics(&state.pool, auth.merchant_account.get_id(), req)
.await
.map(ApplicationResponse::Json)
},
@@ -370,7 +362,7 @@ pub mod routes {
analytics::active_payments::get_metrics(
&state.pool,
&auth.merchant_account.publishable_key,
- &auth.merchant_account.merchant_id,
+ auth.merchant_account.get_id(),
req,
)
.await
@@ -406,7 +398,7 @@ pub mod routes {
|state, auth: AuthenticationData, req, _| async move {
analytics::auth_events::get_metrics(
&state.pool,
- &auth.merchant_account.merchant_id,
+ auth.merchant_account.get_id(),
&auth.merchant_account.publishable_key,
req,
)
@@ -431,13 +423,9 @@ pub mod routes {
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
- analytics::payments::get_filters(
- &state.pool,
- req,
- &auth.merchant_account.merchant_id,
- )
- .await
- .map(ApplicationResponse::Json)
+ analytics::payments::get_filters(&state.pool, req, auth.merchant_account.get_id())
+ .await
+ .map(ApplicationResponse::Json)
},
&auth::JWTAuth(Permission::Analytics),
api_locking::LockAction::NotApplicable,
@@ -460,7 +448,7 @@ pub mod routes {
analytics::payment_intents::get_filters(
&state.pool,
req,
- &auth.merchant_account.merchant_id,
+ auth.merchant_account.get_id(),
)
.await
.map(ApplicationResponse::Json)
@@ -483,13 +471,9 @@ pub mod routes {
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req: GetRefundFilterRequest, _| async move {
- analytics::refunds::get_filters(
- &state.pool,
- req,
- &auth.merchant_account.merchant_id,
- )
- .await
- .map(ApplicationResponse::Json)
+ analytics::refunds::get_filters(&state.pool, req, auth.merchant_account.get_id())
+ .await
+ .map(ApplicationResponse::Json)
},
&auth::JWTAuth(Permission::Analytics),
api_locking::LockAction::NotApplicable,
@@ -509,7 +493,7 @@ pub mod routes {
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req: GetFrmFilterRequest, _| async move {
- analytics::frm::get_filters(&state.pool, req, &auth.merchant_account.merchant_id)
+ analytics::frm::get_filters(&state.pool, req, auth.merchant_account.get_id())
.await
.map(ApplicationResponse::Json)
},
@@ -557,7 +541,7 @@ pub mod routes {
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
- api_events_core(&state.pool, req, auth.merchant_account.merchant_id)
+ api_events_core(&state.pool, req, auth.merchant_account.get_id())
.await
.map(ApplicationResponse::Json)
},
@@ -581,7 +565,7 @@ pub mod routes {
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
- outgoing_webhook_events_core(&state.pool, req, auth.merchant_account.merchant_id)
+ outgoing_webhook_events_core(&state.pool, req, auth.merchant_account.get_id())
.await
.map(ApplicationResponse::Json)
},
@@ -635,7 +619,7 @@ pub mod routes {
let lambda_req = GenerateReportRequest {
request: payload,
- merchant_id: auth.merchant_account.merchant_id.to_string(),
+ merchant_id: auth.merchant_account.get_id().to_owned(),
email: user_email,
};
@@ -677,7 +661,7 @@ pub mod routes {
let lambda_req = GenerateReportRequest {
request: payload,
- merchant_id: auth.merchant_account.merchant_id.to_string(),
+ merchant_id: auth.merchant_account.get_id().to_owned(),
email: user_email,
};
@@ -719,7 +703,7 @@ pub mod routes {
let lambda_req = GenerateReportRequest {
request: payload,
- merchant_id: auth.merchant_account.merchant_id.to_string(),
+ merchant_id: auth.merchant_account.get_id().to_owned(),
email: user_email,
};
@@ -763,7 +747,7 @@ pub mod routes {
|state, auth: AuthenticationData, req, _| async move {
analytics::api_event::get_api_event_metrics(
&state.pool,
- &auth.merchant_account.merchant_id,
+ auth.merchant_account.get_id(),
req,
)
.await
@@ -787,13 +771,9 @@ pub mod routes {
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
- analytics::api_event::get_filters(
- &state.pool,
- req,
- auth.merchant_account.merchant_id,
- )
- .await
- .map(ApplicationResponse::Json)
+ analytics::api_event::get_filters(&state.pool, req, auth.merchant_account.get_id())
+ .await
+ .map(ApplicationResponse::Json)
},
&auth::JWTAuth(Permission::Analytics),
api_locking::LockAction::NotApplicable,
@@ -813,7 +793,7 @@ pub mod routes {
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
- connector_events_core(&state.pool, req, auth.merchant_account.merchant_id)
+ connector_events_core(&state.pool, req, auth.merchant_account.get_id())
.await
.map(ApplicationResponse::Json)
},
@@ -915,13 +895,9 @@ pub mod routes {
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
- analytics::disputes::get_filters(
- &state.pool,
- req,
- &auth.merchant_account.merchant_id,
- )
- .await
- .map(ApplicationResponse::Json)
+ analytics::disputes::get_filters(&state.pool, req, auth.merchant_account.get_id())
+ .await
+ .map(ApplicationResponse::Json)
},
&auth::JWTAuth(Permission::Analytics),
api_locking::LockAction::NotApplicable,
@@ -950,13 +926,9 @@ pub mod routes {
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
- analytics::disputes::get_metrics(
- &state.pool,
- &auth.merchant_account.merchant_id,
- req,
- )
- .await
- .map(ApplicationResponse::Json)
+ analytics::disputes::get_metrics(&state.pool, auth.merchant_account.get_id(), req)
+ .await
+ .map(ApplicationResponse::Json)
},
&auth::JWTAuth(Permission::Analytics),
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index adab685ea09..64969b7d51a 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -702,7 +702,8 @@ pub struct LockerBasedRecipientConnectorList {
#[derive(Debug, Deserialize, Clone, Default)]
pub struct ConnectorRequestReferenceIdConfig {
- pub merchant_ids_send_payment_id_as_connector_request_id: HashSet<String>,
+ pub merchant_ids_send_payment_id_as_connector_request_id:
+ HashSet<common_utils::id_type::MerchantId>,
}
#[derive(Debug, Deserialize, Clone, Default)]
diff --git a/crates/router/src/connector/adyen.rs b/crates/router/src/connector/adyen.rs
index 96d17edc0e1..9d747c2b576 100644
--- a/crates/router/src/connector/adyen.rs
+++ b/crates/router/src/connector/adyen.rs
@@ -1749,7 +1749,7 @@ impl api::IncomingWebhook for Adyen {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
@@ -1773,7 +1773,7 @@ impl api::IncomingWebhook for Adyen {
async fn verify_webhook_source(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 681b994191a..27189aab996 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -1631,8 +1631,11 @@ fn get_recurring_processing_model(
match (item.request.setup_future_usage, item.request.off_session) {
(Some(storage_enums::FutureUsage::OffSession), _) => {
let customer_id = item.get_customer_id()?;
- let shopper_reference =
- format!("{}_{}", item.merchant_id, customer_id.get_string_repr());
+ let shopper_reference = format!(
+ "{}_{}",
+ item.merchant_id.get_string_repr(),
+ customer_id.get_string_repr()
+ );
let store_payment_method = item.request.is_mandate_payment();
Ok((
Some(AdyenRecurringModel::UnscheduledCardOnFile),
@@ -1645,7 +1648,7 @@ fn get_recurring_processing_model(
None,
Some(format!(
"{}_{}",
- item.merchant_id,
+ item.merchant_id.get_string_repr(),
item.get_customer_id()?.get_string_repr()
)),
)),
@@ -1814,11 +1817,15 @@ fn get_social_security_number(voucher_data: &domain::VoucherData) -> Option<Secr
fn build_shopper_reference(
customer_id: &Option<id_type::CustomerId>,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> Option<String> {
- customer_id
- .clone()
- .map(|c_id| format!("{}_{}", merchant_id, c_id.get_string_repr()))
+ customer_id.clone().map(|c_id| {
+ format!(
+ "{}_{}",
+ merchant_id.get_string_repr(),
+ c_id.get_string_repr()
+ )
+ })
}
impl<'a> TryFrom<(&domain::BankDebitData, &types::PaymentsAuthorizeRouterData)>
@@ -4603,7 +4610,7 @@ impl<F> TryFrom<&AdyenRouterData<&types::PayoutsRouterData<F>>> for AdyenPayoutE
merchant_account: auth_type.merchant_account,
payment_method: payout_method_data,
reference: item.router_data.connector_request_reference_id.clone(),
- shopper_reference: item.router_data.merchant_id.clone(),
+ shopper_reference: item.router_data.merchant_id.get_string_repr().to_owned(),
})
}
}
@@ -4690,7 +4697,7 @@ impl<F> TryFrom<&AdyenRouterData<&types::PayoutsRouterData<F>>> for AdyenPayoutC
merchant_account,
payment_data: PayoutPaymentMethodData::PayoutBankData(bank_data),
reference: item.router_data.connector_request_reference_id.to_owned(),
- shopper_reference: item.router_data.merchant_id.to_owned(),
+ shopper_reference: item.router_data.merchant_id.get_string_repr().to_owned(),
shopper_email: customer_email,
shopper_name: ShopperName {
first_name: Some(address.get_first_name()?.to_owned()), // it is a required field for payouts
@@ -4736,7 +4743,7 @@ impl<F> TryFrom<&AdyenRouterData<&types::PayoutsRouterData<F>>> for AdyenPayoutC
merchant_account,
payment_data: PayoutPaymentMethodData::PayoutWalletData(payout_wallet),
reference: item.router_data.request.payout_id.to_owned(),
- shopper_reference: item.router_data.merchant_id.to_owned(),
+ shopper_reference: item.router_data.merchant_id.get_string_repr().to_owned(),
shopper_email: customer_email,
shopper_name: ShopperName {
first_name: Some(address.get_first_name()?.to_owned()), // it is a required field for payouts
diff --git a/crates/router/src/connector/airwallex.rs b/crates/router/src/connector/airwallex.rs
index fbc25909489..e6b0113e98c 100644
--- a/crates/router/src/connector/airwallex.rs
+++ b/crates/router/src/connector/airwallex.rs
@@ -988,7 +988,7 @@ impl api::IncomingWebhook for Airwallex {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let timestamp = request
diff --git a/crates/router/src/connector/authorizedotnet.rs b/crates/router/src/connector/authorizedotnet.rs
index 8d0c1db37a2..b48643e76e8 100644
--- a/crates/router/src/connector/authorizedotnet.rs
+++ b/crates/router/src/connector/authorizedotnet.rs
@@ -918,7 +918,7 @@ impl api::IncomingWebhook for Authorizedotnet {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(request.body.to_vec())
diff --git a/crates/router/src/connector/bluesnap.rs b/crates/router/src/connector/bluesnap.rs
index 7fb4869dc83..ed54b1e052c 100644
--- a/crates/router/src/connector/bluesnap.rs
+++ b/crates/router/src/connector/bluesnap.rs
@@ -1075,7 +1075,7 @@ impl api::IncomingWebhook for Bluesnap {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let timestamp =
@@ -1343,12 +1343,15 @@ impl ConnectorErrorTypeMapping for Bluesnap {
fn get_url_with_merchant_transaction_id(
base_url: String,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
merchant_transaction_id: String,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{},{}",
- base_url, "services/2/transactions/", merchant_transaction_id, merchant_id
+ base_url,
+ "services/2/transactions/",
+ merchant_transaction_id,
+ merchant_id.get_string_repr()
))
}
diff --git a/crates/router/src/connector/bluesnap/transformers.rs b/crates/router/src/connector/bluesnap/transformers.rs
index f354bf1c2db..2f4670ccdcf 100644
--- a/crates/router/src/connector/bluesnap/transformers.rs
+++ b/crates/router/src/connector/bluesnap/transformers.rs
@@ -198,7 +198,7 @@ pub struct ApplepayHeader {
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BluesnapConnectorMetaData {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Debug, Serialize)]
diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs
index 5115280b931..fe15422a128 100644
--- a/crates/router/src/connector/braintree.rs
+++ b/crates/router/src/connector/braintree.rs
@@ -1362,7 +1362,7 @@ impl api::IncomingWebhook for Braintree {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notify = get_webhook_object_from_body(request.body)
@@ -1376,7 +1376,7 @@ impl api::IncomingWebhook for Braintree {
async fn verify_webhook_source(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
diff --git a/crates/router/src/connector/cashtocode.rs b/crates/router/src/connector/cashtocode.rs
index 2b06e0de69c..2155b80dd81 100644
--- a/crates/router/src/connector/cashtocode.rs
+++ b/crates/router/src/connector/cashtocode.rs
@@ -383,7 +383,7 @@ impl api::IncomingWebhook for Cashtocode {
async fn verify_webhook_source(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs
index d4170d3c3b6..3fca0b86aeb 100644
--- a/crates/router/src/connector/checkout.rs
+++ b/crates/router/src/connector/checkout.rs
@@ -1236,7 +1236,7 @@ impl api::IncomingWebhook for Checkout {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(format!("{}", String::from_utf8_lossy(request.body)).into_bytes())
diff --git a/crates/router/src/connector/coinbase.rs b/crates/router/src/connector/coinbase.rs
index 497cf81918e..0c3c0be41db 100644
--- a/crates/router/src/connector/coinbase.rs
+++ b/crates/router/src/connector/coinbase.rs
@@ -399,7 +399,7 @@ impl api::IncomingWebhook for Coinbase {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let message = std::str::from_utf8(request.body)
diff --git a/crates/router/src/connector/cryptopay.rs b/crates/router/src/connector/cryptopay.rs
index 40f85843755..2bef8d46d7d 100644
--- a/crates/router/src/connector/cryptopay.rs
+++ b/crates/router/src/connector/cryptopay.rs
@@ -462,7 +462,7 @@ impl api::IncomingWebhook for Cryptopay {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let message = std::str::from_utf8(request.body)
diff --git a/crates/router/src/connector/globalpay.rs b/crates/router/src/connector/globalpay.rs
index 5c1a8246f07..7d5553bb25c 100644
--- a/crates/router/src/connector/globalpay.rs
+++ b/crates/router/src/connector/globalpay.rs
@@ -967,7 +967,7 @@ impl api::IncomingWebhook for Globalpay {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let payload: Value = request.body.parse_struct("GlobalpayWebhookBody").switch()?;
diff --git a/crates/router/src/connector/gocardless.rs b/crates/router/src/connector/gocardless.rs
index fc3a4f1d0be..281a1ea5c9b 100644
--- a/crates/router/src/connector/gocardless.rs
+++ b/crates/router/src/connector/gocardless.rs
@@ -760,7 +760,7 @@ impl api::IncomingWebhook for Gocardless {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(format!("{}", String::from_utf8_lossy(request.body))
diff --git a/crates/router/src/connector/gpayments/gpayments_types.rs b/crates/router/src/connector/gpayments/gpayments_types.rs
index cb436fe8830..787740523aa 100644
--- a/crates/router/src/connector/gpayments/gpayments_types.rs
+++ b/crates/router/src/connector/gpayments/gpayments_types.rs
@@ -12,7 +12,7 @@ pub struct GpaymentsConnectorMetaData {
#[serde(rename_all = "camelCase")]
pub struct GpaymentsPreAuthVersionCallRequest {
pub acct_number: CardNumber,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
@@ -68,7 +68,7 @@ pub struct GpaymentsPreAuthenticationRequest {
///
/// Example: "1234567890123456789012345678901234"
/// Length: Maximum 35 characters
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
/// Optional boolean. If set to true, ActiveServer will not collect the browser information automatically.
/// The requestor must have a backend implementation to collect browser information.
@@ -135,7 +135,7 @@ pub struct GpaymentsAuthenticationRequest {
pub card_expiry_date: String,
#[serde(rename = "notificationURL")]
pub notification_url: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
#[serde(rename = "threeDSCompInd")]
pub three_ds_comp_ind: ThreeDsCompletionIndicator,
pub message_category: String,
diff --git a/crates/router/src/connector/gpayments/transformers.rs b/crates/router/src/connector/gpayments/transformers.rs
index c6bce775e8f..50c8c0f28c6 100644
--- a/crates/router/src/connector/gpayments/transformers.rs
+++ b/crates/router/src/connector/gpayments/transformers.rs
@@ -79,7 +79,7 @@ impl TryFrom<&GpaymentsRouterData<&types::authentication::PreAuthNVersionCallRou
#[derive(Deserialize, PartialEq)]
pub struct GpaymentsMetaData {
pub endpoint_prefix: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
}
impl TryFrom<&Option<common_utils::pii::SecretSerdeValue>> for GpaymentsMetaData {
diff --git a/crates/router/src/connector/iatapay.rs b/crates/router/src/connector/iatapay.rs
index c3e8344198c..8dc74798895 100644
--- a/crates/router/src/connector/iatapay.rs
+++ b/crates/router/src/connector/iatapay.rs
@@ -675,7 +675,7 @@ impl api::IncomingWebhook for Iatapay {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let message = std::str::from_utf8(request.body)
diff --git a/crates/router/src/connector/mifinity.rs b/crates/router/src/connector/mifinity.rs
index 9c20c26875b..b4a22e38a01 100644
--- a/crates/router/src/connector/mifinity.rs
+++ b/crates/router/src/connector/mifinity.rs
@@ -316,7 +316,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
Ok(format!(
"{}api/gateway/payment-status/payment_validation_key_{}_{}",
self.base_url(connectors),
- merchant_id,
+ merchant_id.get_string_repr(),
payment_id
))
}
diff --git a/crates/router/src/connector/mifinity/transformers.rs b/crates/router/src/connector/mifinity/transformers.rs
index 0e52f7d3b50..20885d08955 100644
--- a/crates/router/src/connector/mifinity/transformers.rs
+++ b/crates/router/src/connector/mifinity/transformers.rs
@@ -127,7 +127,7 @@ impl TryFrom<&MifinityRouterData<&types::PaymentsAuthorizeRouterData>> for Mifin
};
let validation_key = format!(
"payment_validation_key_{}_{}",
- item.router_data.merchant_id,
+ item.router_data.merchant_id.get_string_repr(),
item.router_data.connector_request_reference_id.clone()
);
let client_reference = item.router_data.customer_id.clone().ok_or(
diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs
index 2c0712c5408..e43bc0808e5 100644
--- a/crates/router/src/connector/nmi.rs
+++ b/crates/router/src/connector/nmi.rs
@@ -888,7 +888,7 @@ impl api::IncomingWebhook for Nmi {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let sig_header =
diff --git a/crates/router/src/connector/noon.rs b/crates/router/src/connector/noon.rs
index d9e476ac1f9..4cc049a5581 100644
--- a/crates/router/src/connector/noon.rs
+++ b/crates/router/src/connector/noon.rs
@@ -869,7 +869,7 @@ impl api::IncomingWebhook for Noon {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let webhook_body: noon::NoonWebhookBody = request
diff --git a/crates/router/src/connector/nuvei.rs b/crates/router/src/connector/nuvei.rs
index 316a5e7ab4b..8108413b4ee 100644
--- a/crates/router/src/connector/nuvei.rs
+++ b/crates/router/src/connector/nuvei.rs
@@ -875,7 +875,7 @@ impl api::IncomingWebhook for Nuvei {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let body = serde_urlencoded::from_str::<nuvei::NuveiWebhookDetails>(&request.query_params)
diff --git a/crates/router/src/connector/opennode.rs b/crates/router/src/connector/opennode.rs
index 5346fc086d7..0a1de1fdde2 100644
--- a/crates/router/src/connector/opennode.rs
+++ b/crates/router/src/connector/opennode.rs
@@ -398,7 +398,7 @@ impl api::IncomingWebhook for Opennode {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let message = std::str::from_utf8(request.body)
diff --git a/crates/router/src/connector/payme.rs b/crates/router/src/connector/payme.rs
index 588ba7e712e..6bf26b4f60b 100644
--- a/crates/router/src/connector/payme.rs
+++ b/crates/router/src/connector/payme.rs
@@ -1141,7 +1141,7 @@ impl api::IncomingWebhook for Payme {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let resource =
@@ -1160,7 +1160,7 @@ impl api::IncomingWebhook for Payme {
async fn verify_webhook_source(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
diff --git a/crates/router/src/connector/rapyd.rs b/crates/router/src/connector/rapyd.rs
index 714f8d54626..da10513b3d3 100644
--- a/crates/router/src/connector/rapyd.rs
+++ b/crates/router/src/connector/rapyd.rs
@@ -788,12 +788,15 @@ impl api::IncomingWebhook for Rapyd {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let host = connector_utils::get_header_key_value("host", request.headers)?;
let connector = self.id();
- let url_path = format!("https://{host}/webhooks/{merchant_id}/{connector}");
+ let url_path = format!(
+ "https://{host}/webhooks/{}/{connector}",
+ merchant_id.get_string_repr()
+ );
let salt = connector_utils::get_header_key_value("salt", request.headers)?;
let timestamp = connector_utils::get_header_key_value("timestamp", request.headers)?;
let stringify_auth = String::from_utf8(connector_webhook_secrets.secret.to_vec())
@@ -819,7 +822,7 @@ impl api::IncomingWebhook for Rapyd {
async fn verify_webhook_source(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
diff --git a/crates/router/src/connector/razorpay.rs b/crates/router/src/connector/razorpay.rs
index 737ead477c3..3dcb636b42a 100644
--- a/crates/router/src/connector/razorpay.rs
+++ b/crates/router/src/connector/razorpay.rs
@@ -643,7 +643,7 @@ impl api::IncomingWebhook for Razorpay {
async fn verify_webhook_source(
&self,
_request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<
masking::Secret<serde_json::Value>,
diff --git a/crates/router/src/connector/riskified.rs b/crates/router/src/connector/riskified.rs
index b37e794ec88..0f8ebb46134 100644
--- a/crates/router/src/connector/riskified.rs
+++ b/crates/router/src/connector/riskified.rs
@@ -570,7 +570,7 @@ impl api::IncomingWebhook for Riskified {
async fn verify_webhook_source(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
@@ -605,7 +605,7 @@ impl api::IncomingWebhook for Riskified {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(request.body.to_vec())
diff --git a/crates/router/src/connector/signifyd.rs b/crates/router/src/connector/signifyd.rs
index c6b3e01ab5b..6ba2dce9861 100644
--- a/crates/router/src/connector/signifyd.rs
+++ b/crates/router/src/connector/signifyd.rs
@@ -678,7 +678,7 @@ impl api::IncomingWebhook for Signifyd {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(request.body.to_vec())
@@ -687,7 +687,7 @@ impl api::IncomingWebhook for Signifyd {
async fn verify_webhook_source(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
diff --git a/crates/router/src/connector/square.rs b/crates/router/src/connector/square.rs
index 27f4dd2c25d..9b9c68a5f2b 100644
--- a/crates/router/src/connector/square.rs
+++ b/crates/router/src/connector/square.rs
@@ -863,7 +863,7 @@ impl api::IncomingWebhook for Square {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let header_value = request
diff --git a/crates/router/src/connector/stax.rs b/crates/router/src/connector/stax.rs
index d49a9f2b4fc..8524a19309d 100644
--- a/crates/router/src/connector/stax.rs
+++ b/crates/router/src/connector/stax.rs
@@ -852,7 +852,7 @@ impl api::IncomingWebhook for Stax {
async fn verify_webhook_source(
&self,
_request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
_connector_label: &str,
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index 7e4b644203d..82ed9577a83 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -2175,7 +2175,7 @@ impl api::IncomingWebhook for Stripe {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let mut security_header_kvs = get_signature_elements_from_header(request.headers)?;
diff --git a/crates/router/src/connector/trustpay.rs b/crates/router/src/connector/trustpay.rs
index 6ec8b37982a..deb7ec79618 100644
--- a/crates/router/src/connector/trustpay.rs
+++ b/crates/router/src/connector/trustpay.rs
@@ -960,7 +960,7 @@ impl api::IncomingWebhook for Trustpay {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let trustpay_response: trustpay::TrustpayWebhookResponse = request
diff --git a/crates/router/src/connector/volt.rs b/crates/router/src/connector/volt.rs
index b7da8676961..202dcba7ed1 100644
--- a/crates/router/src/connector/volt.rs
+++ b/crates/router/src/connector/volt.rs
@@ -664,7 +664,7 @@ impl api::IncomingWebhook for Volt {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let x_volt_timed =
diff --git a/crates/router/src/connector/worldline.rs b/crates/router/src/connector/worldline.rs
index ae5e6c1b4a3..901f9ab8e4d 100644
--- a/crates/router/src/connector/worldline.rs
+++ b/crates/router/src/connector/worldline.rs
@@ -787,7 +787,7 @@ impl api::IncomingWebhook for Worldline {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(request.body.to_vec())
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index 365ddda4d53..11d9da7785a 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -757,7 +757,7 @@ pub struct WebhookBody {
pub api_version: Option<String>,
pub id: String,
pub created: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
#[serde(rename = "type")]
pub event_type: WebhookEvent,
pub payment: Option<serde_json::Value>,
diff --git a/crates/router/src/connector/worldpay.rs b/crates/router/src/connector/worldpay.rs
index c44ae7afddf..33c9393cede 100644
--- a/crates/router/src/connector/worldpay.rs
+++ b/crates/router/src/connector/worldpay.rs
@@ -730,7 +730,7 @@ impl api::IncomingWebhook for Worldpay {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let secret_str = std::str::from_utf8(&connector_webhook_secrets.secret)
diff --git a/crates/router/src/connector/worldpay/transformers.rs b/crates/router/src/connector/worldpay/transformers.rs
index 892b6644722..cab949789b9 100644
--- a/crates/router/src/connector/worldpay/transformers.rs
+++ b/crates/router/src/connector/worldpay/transformers.rs
@@ -145,7 +145,11 @@ impl
currency: item.router_data.request.currency.to_string(),
},
narrative: InstructionNarrative {
- line1: item.router_data.merchant_id.clone().replace('_', "-"),
+ line1: item
+ .router_data
+ .merchant_id
+ .get_string_repr()
+ .replace('_', "-"),
..Default::default()
},
payment_instrument: fetch_payment_instrument(
diff --git a/crates/router/src/connector/zen.rs b/crates/router/src/connector/zen.rs
index e76216f4dcd..9490ff138de 100644
--- a/crates/router/src/connector/zen.rs
+++ b/crates/router/src/connector/zen.rs
@@ -588,7 +588,7 @@ impl api::IncomingWebhook for Zen {
fn get_webhook_source_verification_message(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let webhook_body: zen::ZenWebhookBody = request
@@ -608,7 +608,7 @@ impl api::IncomingWebhook for Zen {
async fn verify_webhook_source(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
diff --git a/crates/router/src/connector/zsl.rs b/crates/router/src/connector/zsl.rs
index f71a5e86b5d..d2341a510e1 100644
--- a/crates/router/src/connector/zsl.rs
+++ b/crates/router/src/connector/zsl.rs
@@ -418,7 +418,7 @@ impl api::IncomingWebhook for Zsl {
async fn verify_webhook_source(
&self,
request: &api::IncomingWebhookRequestDetails<'_>,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
_connector_label: &str,
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index 4a816a95ab7..33d24eeccea 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -61,10 +61,10 @@ pub fn create_merchant_publishable_key() -> String {
pub async fn insert_merchant_configs(
db: &dyn StorageInterface,
- merchant_id: &String,
+ merchant_id: &id_type::MerchantId,
) -> RouterResult<()> {
db.insert_config(configs::ConfigNew {
- key: format!("{}_requires_cvv", merchant_id),
+ key: merchant_id.get_requires_cvv_key(),
config: "true".to_string(),
})
.await
@@ -72,7 +72,7 @@ pub async fn insert_merchant_configs(
.attach_printable("Error while setting requires_cvv config")?;
db.insert_config(configs::ConfigNew {
- key: utils::get_merchant_fingerprint_secret_key(merchant_id),
+ key: merchant_id.get_merchant_fingerprint_secret_key(),
config: utils::generate_id(consts::FINGERPRINT_SECRET_LENGTH, "fs"),
})
.await
@@ -89,7 +89,7 @@ fn add_publishable_key_to_decision_service(
) {
let state = state.clone();
let publishable_key = merchant_account.publishable_key.clone();
- let merchant_id = merchant_account.merchant_id.clone();
+ let merchant_id = merchant_account.get_id().clone();
authentication::decision::spawn_tracked_job(
async move {
@@ -192,7 +192,7 @@ pub async fn create_merchant_account(
let master_key = db.get_master_key();
let key_manager_state = &(&state).into();
- let merchant_id = req.get_merchant_reference_id().get_string_repr().to_owned();
+ let merchant_id = req.get_merchant_reference_id();
let identifier = km_types::Identifier::Merchant(merchant_id.clone());
#[cfg(feature = "keymanager_create")]
{
@@ -319,7 +319,7 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {
let parent_merchant_id = get_parent_merchant(
state,
self.sub_merchants_enabled,
- self.parent_merchant_id,
+ self.parent_merchant_id.as_ref(),
&key_store,
)
.await?;
@@ -331,11 +331,10 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {
let key = key_store.key.clone().into_inner();
let key_manager_state = state.into();
- let mut merchant_account = async {
+ let merchant_account = async {
Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>(
- domain::MerchantAccount {
- id: None,
- merchant_id: self.merchant_id.get_string_repr().to_owned(),
+ domain::MerchantAccountSetter {
+ merchant_id: self.merchant_id,
merchant_name: self
.merchant_name
.async_lift(|inner| {
@@ -395,11 +394,13 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
+ let mut domain_merchant_account = domain::MerchantAccount::from(merchant_account);
+
CreateBusinessProfile::new(self.primary_business_details.clone())
- .create_business_profiles(state, &mut merchant_account, &key_store)
+ .create_business_profiles(state, &mut domain_merchant_account, &key_store)
.await?;
- Ok(merchant_account)
+ Ok(domain_merchant_account)
}
}
@@ -757,7 +758,7 @@ pub async fn create_business_profile_from_business_labels(
state: &SessionState,
db: &dyn StorageInterface,
key_store: &domain::MerchantKeyStore,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
new_business_details: Vec<admin_types::PrimaryBusinessDetails>,
) -> RouterResult<()> {
let key_manager_state = &state.into();
@@ -825,7 +826,7 @@ pub async fn create_business_profile_from_business_labels(
pub async fn update_business_profile_cascade(
state: SessionState,
merchant_account_update: api::MerchantAccountUpdate,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> RouterResult<()> {
if merchant_account_update.return_url.is_some()
|| merchant_account_update.webhook_details.is_some()
@@ -842,7 +843,7 @@ pub async fn update_business_profile_cascade(
.list_business_profile_by_merchant_id(&merchant_id)
.await
.to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
- id: merchant_id.to_string(),
+ id: merchant_id.get_string_repr().to_owned(),
})?;
let business_profile_update = admin_types::BusinessProfileUpdate {
@@ -892,7 +893,7 @@ pub async fn update_business_profile_cascade(
pub async fn merchant_account_update(
state: SessionState,
- merchant_id: &String,
+ merchant_id: &id_type::MerchantId,
req: api::MerchantAccountUpdate,
) -> RouterResponse<api::MerchantAccountResponse> {
let db = state.store.as_ref();
@@ -985,7 +986,7 @@ pub async fn merchant_account_update(
};
// Update the business profile, This is for backwards compatibility
- update_business_profile_cascade(state.clone(), req.clone(), merchant_id.to_string()).await?;
+ update_business_profile_cascade(state.clone(), req.clone(), merchant_id.to_owned()).await?;
let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone());
let updated_merchant_account = storage::MerchantAccountUpdate::Update {
@@ -1029,7 +1030,7 @@ pub async fn merchant_account_update(
parent_merchant_id: get_parent_merchant(
&state,
req.sub_merchants_enabled,
- req.parent_merchant_id,
+ req.parent_merchant_id.as_ref(),
&key_store,
)
.await?,
@@ -1072,7 +1073,7 @@ pub async fn merchant_account_update(
pub async fn merchant_account_delete(
state: SessionState,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> RouterResponse<api::MerchantAccountDeleteResponse> {
let mut is_deleted = false;
let db = state.store.as_ref();
@@ -1116,7 +1117,7 @@ pub async fn merchant_account_delete(
);
match db
- .delete_config_by_key(format!("{}_requires_cvv", merchant_id).as_str())
+ .delete_config_by_key(merchant_id.get_requires_cvv_key().as_str())
.await
{
Ok(_) => Ok::<_, errors::ApiErrorResponse>(()),
@@ -1143,9 +1144,9 @@ pub async fn merchant_account_delete(
async fn get_parent_merchant(
state: &SessionState,
sub_merchants_enabled: Option<bool>,
- parent_merchant: Option<String>,
+ parent_merchant: Option<&id_type::MerchantId>,
key_store: &domain::MerchantKeyStore,
-) -> RouterResult<Option<String>> {
+) -> RouterResult<Option<id_type::MerchantId>> {
Ok(match sub_merchants_enabled {
Some(true) => {
Some(
@@ -1161,20 +1162,20 @@ async fn get_parent_merchant(
errors::ApiErrorResponse::InvalidDataValue { field_name: "parent_merchant_id" }
))?
.await?
- .merchant_id
+ .get_id().to_owned()
)
}
_ => None,
})
}
-async fn validate_merchant_id<S: Into<String>>(
+async fn validate_merchant_id(
state: &SessionState,
- merchant_id: S,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<domain::MerchantAccount> {
let db = &*state.store;
- db.find_merchant_account_by_merchant_id(&state.into(), &merchant_id.into(), key_store)
+ db.find_merchant_account_by_merchant_id(&state.into(), merchant_id, key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
}
@@ -1217,7 +1218,7 @@ fn validate_certificate_in_mca_metadata(
pub async fn create_payment_connector(
state: SessionState,
req: api::MerchantConnectorCreate,
- merchant_id: &String,
+ merchant_id: &id_type::MerchantId,
) -> RouterResponse<api_models::admin::MerchantConnectorResponse> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
@@ -1350,7 +1351,7 @@ pub async fn create_payment_connector(
Some(
process_open_banking_connectors(
&state,
- merchant_id.as_str(),
+ merchant_id,
&auth,
&req.connector_type,
&req.connector_name,
@@ -1400,7 +1401,7 @@ pub async fn create_payment_connector(
validate_pm_auth(
val,
&state,
- merchant_id.clone().as_str(),
+ merchant_id,
&key_store,
merchant_account,
&Some(profile_id.clone()),
@@ -1415,7 +1416,7 @@ pub async fn create_payment_connector(
let conn_auth = Secret::new(connector_auth);
let identifier = km_types::Identifier::Merchant(key_store.merchant_id.clone());
let merchant_connector_account = domain::MerchantConnectorAccount {
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
connector_type: req.connector_type,
connector_name: req.connector_name.to_string(),
merchant_connector_id: utils::generate_id(consts::ID_LENGTH, "mca"),
@@ -1444,7 +1445,7 @@ pub async fn create_payment_connector(
connector_webhook_details.encode_to_value(
)
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {}", merchant_id))
+ .attach_printable(format!("Failed to serialize api_models::admin::MerchantConnectorWebhookDetails for Merchant: {:?}", merchant_id))
.map(Some)?
.map(Secret::new)
}
@@ -1475,9 +1476,12 @@ pub async fn create_payment_connector(
_ => api_enums::TransactionType::Payment,
};
- let mut default_routing_config =
- routing_helpers::get_merchant_default_config(&*state.store, merchant_id, &transaction_type)
- .await?;
+ let mut default_routing_config = routing_helpers::get_merchant_default_config(
+ &*state.store,
+ merchant_id.get_string_repr(),
+ &transaction_type,
+ )
+ .await?;
let mut default_routing_config_for_profile = routing_helpers::get_merchant_default_config(
&*state.clone().store,
@@ -1512,7 +1516,7 @@ pub async fn create_payment_connector(
default_routing_config.push(choice.clone());
routing_helpers::update_merchant_default_config(
&*state.store,
- merchant_id,
+ merchant_id.get_string_repr(),
default_routing_config.clone(),
&transaction_type,
)
@@ -1535,7 +1539,7 @@ pub async fn create_payment_connector(
1,
&add_attributes([
("connector", req.connector_name.to_string()),
- ("merchant", merchant_id.to_string()),
+ ("merchant", merchant_id.get_string_repr().to_owned()),
]),
);
@@ -1546,7 +1550,7 @@ pub async fn create_payment_connector(
async fn validate_pm_auth(
val: serde_json::Value,
state: &SessionState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
merchant_account: domain::MerchantAccount,
profile_id: &Option<String>,
@@ -1567,7 +1571,7 @@ async fn validate_pm_auth(
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
- id: merchant_account.merchant_id.clone(),
+ id: merchant_account.get_id().get_string_repr().to_owned(),
})?;
for conn_choice in config.enabled_payment_methods {
@@ -1592,7 +1596,7 @@ async fn validate_pm_auth(
pub async fn retrieve_payment_connector(
state: SessionState,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
merchant_connector_id: String,
) -> RouterResponse<api_models::admin::MerchantConnectorResponse> {
let store = state.store.as_ref();
@@ -1628,7 +1632,7 @@ pub async fn retrieve_payment_connector(
pub async fn list_payment_connectors(
state: SessionState,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> RouterResponse<Vec<api_models::admin::MerchantConnectorResponse>> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
@@ -1668,7 +1672,7 @@ pub async fn list_payment_connectors(
pub async fn update_payment_connector(
state: SessionState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
merchant_connector_id: &str,
req: api_models::admin::MerchantConnectorUpdate,
) -> RouterResponse<api_models::admin::MerchantConnectorResponse> {
@@ -1745,7 +1749,6 @@ pub async fn update_payment_connector(
}
}
let payment_connector = storage::MerchantConnectorAccountUpdate::Update {
- merchant_id: None,
connector_type: Some(req.connector_type),
connector_name: None,
merchant_connector_id: None,
@@ -1819,7 +1822,7 @@ pub async fn update_payment_connector(
pub async fn delete_payment_connector(
state: SessionState,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
merchant_connector_id: String,
) -> RouterResponse<api::MerchantConnectorDeleteResponse> {
let db = state.store.as_ref();
@@ -1870,7 +1873,7 @@ pub async fn delete_payment_connector(
pub async fn kv_for_merchant(
state: SessionState,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
enable: bool,
) -> RouterResponse<api_models::admin::ToggleKVResponse> {
let db = state.store.as_ref();
@@ -1936,7 +1939,7 @@ pub async fn kv_for_merchant(
Ok(service_api::ApplicationResponse::Json(
api_models::admin::ToggleKVResponse {
- merchant_id: updated_merchant_account.merchant_id,
+ merchant_id: updated_merchant_account.get_id().to_owned(),
kv_enabled: kv_status,
},
))
@@ -1974,7 +1977,7 @@ pub async fn toggle_kv_for_all_merchants(
pub async fn check_merchant_account_kv_status(
state: SessionState,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> RouterResponse<api_models::admin::ToggleKVResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
@@ -2000,7 +2003,7 @@ pub async fn check_merchant_account_kv_status(
Ok(service_api::ApplicationResponse::Json(
api_models::admin::ToggleKVResponse {
- merchant_id: merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
kv_enabled: kv_status,
},
))
@@ -2054,7 +2057,7 @@ pub async fn create_and_insert_business_profile(
pub async fn create_business_profile(
state: SessionState,
request: api::BusinessProfileCreate,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> RouterResponse<api_models::admin::BusinessProfileResponse> {
if let Some(session_expiry) = &request.session_expiry {
helpers::validate_session_expiry(session_expiry.to_owned())?;
@@ -2118,7 +2121,7 @@ pub async fn create_business_profile(
pub async fn list_business_profile(
state: SessionState,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> RouterResponse<Vec<api_models::admin::BusinessProfileResponse>> {
let db = state.store.as_ref();
let key_store = db
@@ -2149,7 +2152,7 @@ pub async fn list_business_profile(
pub async fn retrieve_business_profile(
state: SessionState,
profile_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> RouterResponse<api_models::admin::BusinessProfileResponse> {
let db = state.store.as_ref();
let key_store = db
@@ -2178,7 +2181,7 @@ pub async fn retrieve_business_profile(
pub async fn delete_business_profile(
state: SessionState,
profile_id: String,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> RouterResponse<bool> {
let db = state.store.as_ref();
let delete_result = db
@@ -2194,7 +2197,7 @@ pub async fn delete_business_profile(
pub async fn update_business_profile(
state: SessionState,
profile_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
request: api::BusinessProfileUpdate,
) -> RouterResponse<api::BusinessProfileResponse> {
let db = state.store.as_ref();
@@ -2214,7 +2217,7 @@ pub async fn update_business_profile(
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.attach_printable("Error while fetching the key store by merchant_id")?;
- if business_profile.merchant_id != merchant_id {
+ if business_profile.merchant_id != *merchant_id {
Err(errors::ApiErrorResponse::AccessForbidden {
resource: profile_id.to_string(),
})?
@@ -2386,7 +2389,7 @@ pub async fn extended_card_info_toggle(
pub async fn connector_agnostic_mit_toggle(
state: SessionState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
profile_id: &str,
connector_agnostic_mit_choice: admin_types::ConnectorAgnosticMitChoice,
) -> RouterResponse<admin_types::ConnectorAgnosticMitChoice> {
@@ -2399,7 +2402,7 @@ pub async fn connector_agnostic_mit_toggle(
id: profile_id.to_string(),
})?;
- if business_profile.merchant_id != merchant_id {
+ if business_profile.merchant_id != *merchant_id {
Err(errors::ApiErrorResponse::AccessForbidden {
resource: profile_id.to_string(),
})?
@@ -2902,7 +2905,7 @@ pub fn validate_status_and_disabled(
async fn process_open_banking_connectors(
state: &SessionState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
auth: &types::ConnectorAuthType,
connector_type: &api_enums::ConnectorType,
connector: &api_enums::Connector,
@@ -3066,7 +3069,7 @@ fn validate_bank_account_data(data: &types::MerchantAccountData) -> RouterResult
async fn connector_recipient_create_call(
state: &SessionState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
connector_name: String,
auth: &types::ConnectorAuthType,
data: &types::MerchantAccountData,
@@ -3151,19 +3154,21 @@ async fn connector_recipient_create_call(
async fn locker_recipient_create_call(
state: &SessionState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
data: &types::MerchantAccountData,
) -> RouterResult<String> {
let enc_data = serde_json::to_string(data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert to MerchantAccountData json to String")?;
- let cust_id = id_type::CustomerId::from(merchant_id.to_string().into())
+ let merchant_id_string = merchant_id.get_string_repr().to_owned();
+
+ let cust_id = id_type::CustomerId::from(merchant_id_string.into())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert to CustomerId")?;
let payload = transformers::StoreLockerReq::LockerGeneric(transformers::StoreGenericReq {
- merchant_id,
+ merchant_id: merchant_id.to_owned(),
merchant_customer_id: cust_id.clone(),
enc_data,
ttl: state.conf.locker.ttl_for_storage_in_secs,
diff --git a/crates/router/src/core/api_keys.rs b/crates/router/src/core/api_keys.rs
index 6af82a6b7a8..f06050c5303 100644
--- a/crates/router/src/core/api_keys.rs
+++ b/crates/router/src/core/api_keys.rs
@@ -112,7 +112,7 @@ impl PlaintextApiKey {
pub async fn create_api_key(
state: SessionState,
api_key: api::CreateApiKeyRequest,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
) -> RouterResponse<api::CreateApiKeyResponse> {
let api_key_config = state.conf.api_keys.get_inner();
let store = state.store.as_ref();
@@ -123,7 +123,7 @@ pub async fn create_api_key(
store
.get_merchant_key_store_by_merchant_id(
&(&state).into(),
- merchant_id.as_str(),
+ &merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
@@ -172,7 +172,7 @@ pub async fn create_api_key(
metrics::API_KEY_CREATED.add(
&metrics::CONTEXT,
1,
- &add_attributes([("merchant", merchant_id)]),
+ &add_attributes([("merchant", merchant_id.get_string_repr().to_owned())]),
);
// Add process to process_tracker for email reminder, only if expiry is set to future date
@@ -266,7 +266,7 @@ pub async fn add_api_key_expiry_task(
#[instrument(skip_all)]
pub async fn retrieve_api_key(
state: SessionState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key_id: &str,
) -> RouterResponse<api::RetrieveApiKeyResponse> {
let store = state.store.as_ref();
@@ -438,7 +438,7 @@ pub async fn update_api_key_expiry_task(
#[instrument(skip_all)]
pub async fn revoke_api_key(
state: SessionState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key_id: &str,
) -> RouterResponse<api::RevokeApiKeyResponse> {
let store = state.store.as_ref();
@@ -525,7 +525,7 @@ pub async fn revoke_api_key_expiry_task(
#[instrument(skip_all)]
pub async fn list_api_keys(
state: SessionState,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> RouterResponse<Vec<api::RetrieveApiKeyResponse>> {
diff --git a/crates/router/src/core/api_locking.rs b/crates/router/src/core/api_locking.rs
index 8723c5fc141..9b45fecee4e 100644
--- a/crates/router/src/core/api_locking.rs
+++ b/crates/router/src/core/api_locking.rs
@@ -38,17 +38,24 @@ pub struct LockingInput {
}
impl LockingInput {
- fn get_redis_locking_key(&self, merchant_id: String) -> String {
+ fn get_redis_locking_key(&self, merchant_id: common_utils::id_type::MerchantId) -> String {
format!(
"{}_{}_{}_{}",
- API_LOCK_PREFIX, merchant_id, self.api_identifier, self.unique_locking_key
+ API_LOCK_PREFIX,
+ merchant_id.get_string_repr(),
+ self.api_identifier,
+ self.unique_locking_key
)
}
}
impl LockAction {
#[instrument(skip_all)]
- pub async fn perform_locking_action<A>(self, state: &A, merchant_id: String) -> RouterResult<()>
+ pub async fn perform_locking_action<A>(
+ self,
+ state: &A,
+ merchant_id: common_utils::id_type::MerchantId,
+ ) -> RouterResult<()>
where
A: SessionStateInfo,
{
@@ -109,7 +116,11 @@ impl LockAction {
}
#[instrument(skip_all)]
- pub async fn free_lock_action<A>(self, state: &A, merchant_id: String) -> RouterResult<()>
+ pub async fn free_lock_action<A>(
+ self,
+ state: &A,
+ merchant_id: common_utils::id_type::MerchantId,
+ ) -> RouterResult<()>
where
A: SessionStateInfo,
{
diff --git a/crates/router/src/core/apple_pay_certificates_migration.rs b/crates/router/src/core/apple_pay_certificates_migration.rs
index 87c15935715..8fe61f75ca2 100644
--- a/crates/router/src/core/apple_pay_certificates_migration.rs
+++ b/crates/router/src/core/apple_pay_certificates_migration.rs
@@ -93,13 +93,15 @@ pub async fn apple_pay_certificates_migration(
match merchant_connector_accounts_update {
Ok(_) => {
- logger::debug!("Merchant connector accounts updated for merchant id {merchant_id}");
- migration_successful_merchant_ids.push(merchant_id.to_string());
+ logger::debug!(
+ "Merchant connector accounts updated for merchant id {merchant_id:?}"
+ );
+ migration_successful_merchant_ids.push(merchant_id.clone());
}
Err(error) => {
logger::debug!(
- "Merchant connector accounts update failed with error {error} for merchant id {merchant_id}");
- migration_failed_merchant_ids.push(merchant_id.to_string());
+ "Merchant connector accounts update failed with error {error} for merchant id {merchant_id:?}");
+ migration_failed_merchant_ids.push(merchant_id.clone());
}
};
}
diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rs
index ec799365f7a..7cc03ab9ea4 100644
--- a/crates/router/src/core/authentication.rs
+++ b/crates/router/src/core/authentication.rs
@@ -20,7 +20,7 @@ use crate::{
#[allow(clippy::too_many_arguments)]
pub async fn perform_authentication(
state: &SessionState,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
authentication_connector: String,
payment_method_data: payments::PaymentMethodData,
payment_method: common_enums::PaymentMethod,
@@ -94,7 +94,7 @@ pub async fn perform_post_authentication(
let authentication = state
.store
.find_authentication_by_merchant_id_authentication_id(
- business_profile.merchant_id.clone(),
+ &business_profile.merchant_id,
authentication_id.clone(),
)
.await
diff --git a/crates/router/src/core/authentication/transformers.rs b/crates/router/src/core/authentication/transformers.rs
index 1be40a0ab6e..569f2beea5e 100644
--- a/crates/router/src/core/authentication/transformers.rs
+++ b/crates/router/src/core/authentication/transformers.rs
@@ -26,7 +26,7 @@ const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_AUTHENTICATION_FLOW: &str =
#[allow(clippy::too_many_arguments)]
pub fn construct_authentication_router_data(
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
authentication_connector: String,
payment_method_data: payments::PaymentMethodData,
payment_method: PaymentMethod,
@@ -103,7 +103,7 @@ pub fn construct_pre_authentication_router_data<F: Clone>(
authentication_connector: String,
card_holder_account_number: cards::CardNumber,
merchant_connector_account: &payments_helpers::MerchantConnectorAccountType,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
) -> RouterResult<
types::RouterData<
F,
@@ -127,7 +127,7 @@ pub fn construct_pre_authentication_router_data<F: Clone>(
pub fn construct_router_data<F: Clone, Req, Res>(
authentication_connector_name: String,
payment_method: PaymentMethod,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
address: types::PaymentAddress,
request_data: Req,
merchant_connector_account: &payments_helpers::MerchantConnectorAccountType,
diff --git a/crates/router/src/core/authentication/utils.rs b/crates/router/src/core/authentication/utils.rs
index b7638e7a413..0ed55999831 100644
--- a/crates/router/src/core/authentication/utils.rs
+++ b/crates/router/src/core/authentication/utils.rs
@@ -176,7 +176,7 @@ impl ForeignFrom<common_enums::AuthenticationStatus> for common_enums::AttemptSt
pub async fn create_new_authentication(
state: &SessionState,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
authentication_connector: String,
token: String,
profile_id: String,
diff --git a/crates/router/src/core/blocklist.rs b/crates/router/src/core/blocklist.rs
index 947acc506df..16833773a50 100644
--- a/crates/router/src/core/blocklist.rs
+++ b/crates/router/src/core/blocklist.rs
@@ -15,7 +15,7 @@ pub async fn add_entry_to_blocklist(
merchant_account: domain::MerchantAccount,
body: api_blocklist::AddToBlocklistRequest,
) -> RouterResponse<api_blocklist::AddToBlocklistResponse> {
- utils::insert_entry_into_blocklist(&state, merchant_account.merchant_id, body)
+ utils::insert_entry_into_blocklist(&state, merchant_account.get_id(), body)
.await
.map(services::ApplicationResponse::Json)
}
@@ -25,7 +25,7 @@ pub async fn remove_entry_from_blocklist(
merchant_account: domain::MerchantAccount,
body: api_blocklist::DeleteFromBlocklistRequest,
) -> RouterResponse<api_blocklist::DeleteFromBlocklistResponse> {
- utils::delete_entry_from_blocklist(&state, merchant_account.merchant_id, body)
+ utils::delete_entry_from_blocklist(&state, merchant_account.get_id(), body)
.await
.map(services::ApplicationResponse::Json)
}
@@ -35,7 +35,7 @@ pub async fn list_blocklist_entries(
merchant_account: domain::MerchantAccount,
query: api_blocklist::ListBlocklistQuery,
) -> RouterResponse<Vec<api_blocklist::BlocklistResponse>> {
- utils::list_blocklist_entries_for_merchant(&state, merchant_account.merchant_id, query)
+ utils::list_blocklist_entries_for_merchant(&state, merchant_account.get_id(), query)
.await
.map(services::ApplicationResponse::Json)
}
@@ -45,7 +45,7 @@ pub async fn toggle_blocklist_guard(
merchant_account: domain::MerchantAccount,
query: api_blocklist::ToggleBlocklistQuery,
) -> RouterResponse<api_blocklist::ToggleBlocklistResponse> {
- utils::toggle_blocklist_guard_for_merchant(&state, merchant_account.merchant_id, query)
+ utils::toggle_blocklist_guard_for_merchant(&state, merchant_account.get_id(), query)
.await
.map(services::ApplicationResponse::Json)
}
diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs
index c739a86ee51..8edd75d3df7 100644
--- a/crates/router/src/core/blocklist/utils.rs
+++ b/crates/router/src/core/blocklist/utils.rs
@@ -19,21 +19,21 @@ use crate::{
pub async fn delete_entry_from_blocklist(
state: &SessionState,
- merchant_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
request: api_blocklist::DeleteFromBlocklistRequest,
) -> RouterResult<api_blocklist::DeleteFromBlocklistResponse> {
let blocklist_entry = match request {
api_blocklist::DeleteFromBlocklistRequest::CardBin(bin) => {
- delete_card_bin_blocklist_entry(state, &bin, &merchant_id).await?
+ delete_card_bin_blocklist_entry(state, &bin, merchant_id).await?
}
api_blocklist::DeleteFromBlocklistRequest::ExtendedCardBin(xbin) => {
- delete_card_bin_blocklist_entry(state, &xbin, &merchant_id).await?
+ delete_card_bin_blocklist_entry(state, &xbin, merchant_id).await?
}
api_blocklist::DeleteFromBlocklistRequest::Fingerprint(fingerprint_id) => state
.store
- .delete_blocklist_entry_by_merchant_id_fingerprint_id(&merchant_id, &fingerprint_id)
+ .delete_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, &fingerprint_id)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "no blocklist record for the given fingerprint id was found".to_string(),
@@ -45,10 +45,10 @@ pub async fn delete_entry_from_blocklist(
pub async fn toggle_blocklist_guard_for_merchant(
state: &SessionState,
- merchant_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
query: api_blocklist::ToggleBlocklistQuery,
) -> CustomResult<api_blocklist::ToggleBlocklistResponse, errors::ApiErrorResponse> {
- let key = get_blocklist_guard_key(merchant_id.as_str());
+ let key = merchant_id.get_blocklist_guard_key();
let maybe_guard = state.store.find_config_by_key(&key).await;
let new_config = configs::ConfigNew {
key: key.clone(),
@@ -87,21 +87,15 @@ pub async fn toggle_blocklist_guard_for_merchant(
})
}
-/// Provides the identifier for the specific merchant's blocklist guard config
-#[inline(always)]
-pub fn get_blocklist_guard_key(merchant_id: &str) -> String {
- format!("guard_blocklist_for_{merchant_id}")
-}
-
pub async fn list_blocklist_entries_for_merchant(
state: &SessionState,
- merchant_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
query: api_blocklist::ListBlocklistQuery,
) -> RouterResult<Vec<api_blocklist::BlocklistResponse>> {
state
.store
.list_blocklist_entries_by_merchant_id_data_kind(
- &merchant_id,
+ merchant_id,
query.data_kind,
query.limit.into(),
query.offset.into(),
@@ -139,7 +133,7 @@ fn validate_extended_card_bin(bin: &str) -> RouterResult<()> {
pub async fn insert_entry_into_blocklist(
state: &SessionState,
- merchant_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
to_block: api_blocklist::AddToBlocklistRequest,
) -> RouterResult<api_blocklist::AddToBlocklistResponse> {
let blocklist_entry = match &to_block {
@@ -148,7 +142,7 @@ pub async fn insert_entry_into_blocklist(
duplicate_check_insert_bin(
bin,
state,
- &merchant_id,
+ merchant_id,
common_enums::BlocklistDataKind::CardBin,
)
.await?
@@ -159,7 +153,7 @@ pub async fn insert_entry_into_blocklist(
duplicate_check_insert_bin(
bin,
state,
- &merchant_id,
+ merchant_id,
common_enums::BlocklistDataKind::ExtendedCardBin,
)
.await?
@@ -168,7 +162,7 @@ pub async fn insert_entry_into_blocklist(
api_blocklist::AddToBlocklistRequest::Fingerprint(fingerprint_id) => {
let blocklist_entry_result = state
.store
- .find_blocklist_entry_by_merchant_id_fingerprint_id(&merchant_id, fingerprint_id)
+ .find_blocklist_entry_by_merchant_id_fingerprint_id(merchant_id, fingerprint_id)
.await;
match blocklist_entry_result {
@@ -192,7 +186,7 @@ pub async fn insert_entry_into_blocklist(
state
.store
.insert_blocklist_entry(storage::BlocklistNew {
- merchant_id: merchant_id.clone(),
+ merchant_id: merchant_id.to_owned(),
fingerprint_id: fingerprint_id.clone(),
data_kind: api_models::enums::enums::BlocklistDataKind::PaymentMethod,
metadata: None,
@@ -208,9 +202,9 @@ pub async fn insert_entry_into_blocklist(
pub async fn get_merchant_fingerprint_secret(
state: &SessionState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<String> {
- let key = utils::get_merchant_fingerprint_secret_key(merchant_id);
+ let key = merchant_id.get_merchant_fingerprint_secret_key();
let config_fetch_result = state.store.find_config_by_key(&key).await;
match config_fetch_result {
@@ -243,7 +237,7 @@ pub async fn get_merchant_fingerprint_secret(
async fn duplicate_check_insert_bin(
bin: &str,
state: &SessionState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
) -> RouterResult<storage::Blocklist> {
let blocklist_entry_result = state
@@ -271,7 +265,7 @@ async fn duplicate_check_insert_bin(
state
.store
.insert_blocklist_entry(storage::BlocklistNew {
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
fingerprint_id: bin.to_string(),
data_kind,
metadata: None,
@@ -285,7 +279,7 @@ async fn duplicate_check_insert_bin(
async fn delete_card_bin_blocklist_entry(
state: &SessionState,
bin: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<storage::Blocklist> {
state
.store
@@ -306,9 +300,8 @@ where
F: Send + Clone,
{
let db = &state.store;
- let merchant_id = &merchant_account.merchant_id;
- let merchant_fingerprint_secret =
- get_merchant_fingerprint_secret(state, merchant_id.as_str()).await?;
+ let merchant_id = merchant_account.get_id();
+ let merchant_fingerprint_secret = get_merchant_fingerprint_secret(state, merchant_id).await?;
// Hashed Fingerprint to check whether or not this payment should be blocked.
let card_number_fingerprint = if let Some(api_models::payments::PaymentMethodData::Card(card)) =
@@ -452,7 +445,7 @@ where
pub async fn generate_payment_fingerprint(
state: &SessionState,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
payment_method_data: Option<crate::types::api::PaymentMethodData>,
) -> CustomResult<Option<String>, errors::ApiErrorResponse> {
let merchant_fingerprint_secret = get_merchant_fingerprint_secret(state, &merchant_id).await?;
diff --git a/crates/router/src/core/conditional_config.rs b/crates/router/src/core/conditional_config.rs
index c34f8e7116d..e845d54ee7a 100644
--- a/crates/router/src/core/conditional_config.rs
+++ b/crates/router/src/core/conditional_config.rs
@@ -8,9 +8,7 @@ use error_stack::ResultExt;
use euclid::frontend::ast;
use storage_impl::redis::cache;
-use super::routing::helpers::{
- get_payment_config_routing_id, update_merchant_active_algorithm_ref,
-};
+use super::routing::helpers::update_merchant_active_algorithm_ref;
use crate::{
core::errors::{self, RouterResponse},
routes::SessionState,
@@ -62,7 +60,7 @@ pub async fn upsert_conditional_config(
.attach_printable("Could not decode the routing algorithm")?
.unwrap_or_default();
- let key = get_payment_config_routing_id(merchant_account.merchant_id.as_str());
+ let key = merchant_account.get_id().get_payment_config_routing_id();
let read_config_key = db.find_config_by_key(&key).await;
ast::lowering::lower_program(prog.clone())
@@ -157,7 +155,7 @@ pub async fn delete_conditional_config(
merchant_account: domain::MerchantAccount,
) -> RouterResponse<()> {
let db = state.store.as_ref();
- let key = get_payment_config_routing_id(&merchant_account.merchant_id);
+ let key = merchant_account.get_id().get_payment_config_routing_id();
let mut algo_id: routing::RoutingAlgorithmRef = merchant_account
.routing_algorithm
.clone()
@@ -185,7 +183,7 @@ pub async fn retrieve_conditional_config(
merchant_account: domain::MerchantAccount,
) -> RouterResponse<DecisionManagerResponse> {
let db = state.store.as_ref();
- let algorithm_id = get_payment_config_routing_id(merchant_account.merchant_id.as_str());
+ let algorithm_id = merchant_account.get_id().get_payment_config_routing_id();
let algo_config = db
.find_config_by_key(&algorithm_id)
.await
diff --git a/crates/router/src/core/connector_onboarding.rs b/crates/router/src/core/connector_onboarding.rs
index d6c20cc2810..c3de228d9a7 100644
--- a/crates/router/src/core/connector_onboarding.rs
+++ b/crates/router/src/core/connector_onboarding.rs
@@ -82,7 +82,9 @@ pub async fn sync_onboarding_status(
let auth_details = oss_types::ConnectorAuthType::SignatureKey {
api_key: connector_onboarding_conf.paypal.client_secret.clone(),
key1: connector_onboarding_conf.paypal.client_id.clone(),
- api_secret: Secret::new(paypal_onboarding_data.payer_id.clone()),
+ api_secret: Secret::new(
+ paypal_onboarding_data.payer_id.get_string_repr().to_owned(),
+ ),
};
let update_mca_data = paypal::update_mca(
&state,
diff --git a/crates/router/src/core/connector_onboarding/paypal.rs b/crates/router/src/core/connector_onboarding/paypal.rs
index 6f28cfcbf8e..5dda818b0f5 100644
--- a/crates/router/src/core/connector_onboarding/paypal.rs
+++ b/crates/router/src/core/connector_onboarding/paypal.rs
@@ -140,7 +140,7 @@ async fn find_paypal_merchant_by_tracking_id(
pub async fn update_mca(
state: &SessionState,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
connector_id: String,
auth_details: oss_types::ConnectorAuthType,
) -> RouterResult<oss_api_types::MerchantConnectorResponse> {
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index d34e2f081e1..16f79e375b8 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -48,7 +48,7 @@ pub async fn create_customer(
let merchant_reference_id = customer_data.get_merchant_reference_id();
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let merchant_reference_id_customer = MerchantReferenceIdForCustomer {
customer_id: merchant_reference_id.as_ref(),
@@ -124,7 +124,7 @@ impl CustomerCreateBridge for customers::CustomerRequest {
) -> errors::CustomResult<domain::Customer, errors::CustomersErrorResponse> {
// Setting default billing address to Db
let address = self.get_address();
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let key = key_store.key.get_inner().peek();
let customer_billing_address_struct = AddressStructForDbEntry {
@@ -163,7 +163,7 @@ impl CustomerCreateBridge for customers::CustomerRequest {
customer_id: merchant_reference_id
.to_owned()
.ok_or(errors::CustomersErrorResponse::InternalServerError)?,
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
name: encryptable_customer.name,
email: encryptable_customer.email,
phone: encryptable_customer.phone,
@@ -266,7 +266,7 @@ impl CustomerCreateBridge for customers::CustomerRequest {
struct AddressStructForDbEntry<'a> {
address: Option<&'a api_models::payments::AddressDetails>,
customer_data: &'a customers::CustomerRequest,
- merchant_id: &'a str,
+ merchant_id: &'a id_type::MerchantId,
customer_id: Option<&'a id_type::CustomerId>,
storage_scheme: common_enums::MerchantStorageScheme,
key_store: &'a domain::MerchantKeyStore,
@@ -314,7 +314,7 @@ impl<'a> AddressStructForDbEntry<'a> {
struct MerchantReferenceIdForCustomer<'a> {
customer_id: Option<&'a id_type::CustomerId>,
- merchant_id: &'a str,
+ merchant_id: &'a id_type::MerchantId,
merchant_account: &'a domain::MerchantAccount,
key_store: &'a domain::MerchantKeyStore,
key_manager_state: &'a KeyManagerState,
@@ -377,7 +377,7 @@ pub async fn retrieve_customer(
.find_customer_by_customer_id_merchant_id(
key_manager_state,
&req.customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
@@ -400,7 +400,7 @@ pub async fn retrieve_customer(
#[instrument(skip(state))]
pub async fn list_customers(
state: SessionState,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
key_store: domain::MerchantKeyStore,
) -> errors::CustomerResponse<Vec<customers::CustomerResponse>> {
let db = state.store.as_ref();
@@ -432,7 +432,7 @@ pub async fn delete_customer(
.find_customer_by_customer_id_merchant_id(
key_manager_state,
&req.customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
@@ -440,7 +440,7 @@ pub async fn delete_customer(
.switch()?;
let customer_mandates = db
- .find_mandate_by_merchant_id_customer_id(&merchant_account.merchant_id, &req.customer_id)
+ .find_mandate_by_merchant_id_customer_id(merchant_account.get_id(), &req.customer_id)
.await
.switch()?;
@@ -453,7 +453,7 @@ pub async fn delete_customer(
match db
.find_payment_method_by_customer_id_merchant_id_list(
&req.customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
None,
)
.await
@@ -465,14 +465,14 @@ pub async fn delete_customer(
cards::delete_card_from_locker(
&state,
&req.customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
pm.locker_id.as_ref().unwrap_or(&pm.payment_method_id),
)
.await
.switch()?;
}
db.delete_payment_method_by_merchant_id_payment_method_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&pm.payment_method_id,
)
.await
@@ -529,7 +529,7 @@ pub async fn delete_customer(
.update_address_by_merchant_id_customer_id(
key_manager_state,
&req.customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
update_address,
&key_store,
)
@@ -569,7 +569,7 @@ pub async fn delete_customer(
db.update_customer_by_customer_id_merchant_id(
key_manager_state,
req.customer_id.clone(),
- merchant_account.merchant_id,
+ merchant_account.get_id().to_owned(),
customer_orig,
updated_customer,
&key_store,
@@ -613,7 +613,7 @@ pub async fn update_customer(
.find_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
@@ -632,7 +632,7 @@ pub async fn update_customer(
customer_address,
key,
merchant_account.storage_scheme,
- merchant_account.merchant_id.clone(),
+ merchant_account.get_id().clone(),
)
.await
.switch()
@@ -642,8 +642,9 @@ pub async fn update_customer(
.await
.switch()
.attach_printable(format!(
- "Failed while updating address: merchant_id: {}, customer_id: {:?}",
- merchant_account.merchant_id, customer_id
+ "Failed while updating address: merchant_id: {:?}, customer_id: {:?}",
+ merchant_account.get_id(),
+ customer_id
))?,
)
}
@@ -654,7 +655,7 @@ pub async fn update_customer(
.get_domain_address(
&state,
customer_address,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&customer.customer_id,
key,
merchant_account.storage_scheme,
@@ -699,7 +700,7 @@ pub async fn update_customer(
.update_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id.to_owned(),
- merchant_account.merchant_id.to_owned(),
+ merchant_account.get_id().to_owned(),
customer,
storage::CustomerUpdate::Update {
name: encryptable_customer.name,
diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rs
index 6a7f531f5a0..0584851e607 100644
--- a/crates/router/src/core/disputes.rs
+++ b/crates/router/src/core/disputes.rs
@@ -30,7 +30,7 @@ pub async fn retrieve_dispute(
) -> RouterResponse<api_models::disputes::DisputeResponse> {
let dispute = state
.store
- .find_dispute_by_merchant_id_dispute_id(&merchant_account.merchant_id, &req.dispute_id)
+ .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), &req.dispute_id)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: req.dispute_id,
@@ -47,7 +47,7 @@ pub async fn retrieve_disputes_list(
) -> RouterResponse<Vec<api_models::disputes::DisputeResponse>> {
let disputes = state
.store
- .find_disputes_by_merchant_id(&merchant_account.merchant_id, constraints)
+ .find_disputes_by_merchant_id(merchant_account.get_id(), constraints)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to retrieve disputes")?;
@@ -68,7 +68,7 @@ pub async fn accept_dispute(
let db = &state.store;
let dispute = state
.store
- .find_dispute_by_merchant_id_dispute_id(&merchant_account.merchant_id, &req.dispute_id)
+ .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), &req.dispute_id)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: req.dispute_id,
@@ -91,7 +91,7 @@ pub async fn accept_dispute(
.find_payment_intent_by_payment_id_merchant_id(
&(&state).into(),
&dispute.payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
@@ -100,7 +100,7 @@ pub async fn accept_dispute(
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&dispute.attempt_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
@@ -170,7 +170,7 @@ pub async fn submit_evidence(
let db = &state.store;
let dispute = state
.store
- .find_dispute_by_merchant_id_dispute_id(&merchant_account.merchant_id, &req.dispute_id)
+ .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), &req.dispute_id)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: req.dispute_id.clone(),
@@ -205,7 +205,7 @@ pub async fn submit_evidence(
.find_payment_intent_by_payment_id_merchant_id(
&(&state).into(),
&dispute.payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
@@ -214,7 +214,7 @@ pub async fn submit_evidence(
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&dispute.attempt_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
@@ -339,7 +339,7 @@ pub async fn attach_evidence(
.clone()
.ok_or(errors::ApiErrorResponse::MissingDisputeId)?;
let dispute = db
- .find_dispute_by_merchant_id_dispute_id(&merchant_account.merchant_id, &dispute_id)
+ .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), &dispute_id)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: dispute_id.clone(),
@@ -410,7 +410,7 @@ pub async fn retrieve_dispute_evidence(
) -> RouterResponse<Vec<api_models::disputes::DisputeEvidenceBlock>> {
let dispute = state
.store
- .find_dispute_by_merchant_id_dispute_id(&merchant_account.merchant_id, &req.dispute_id)
+ .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), &req.dispute_id)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: req.dispute_id,
@@ -434,7 +434,7 @@ pub async fn delete_evidence(
let dispute_id = delete_evidence_request.dispute_id.clone();
let dispute = state
.store
- .find_dispute_by_merchant_id_dispute_id(&merchant_account.merchant_id, &dispute_id)
+ .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), &dispute_id)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: dispute_id.clone(),
diff --git a/crates/router/src/core/disputes/transformers.rs b/crates/router/src/core/disputes/transformers.rs
index d37410d5ef8..7cd87815775 100644
--- a/crates/router/src/core/disputes/transformers.rs
+++ b/crates/router/src/core/disputes/transformers.rs
@@ -210,7 +210,7 @@ pub async fn get_dispute_evidence_block(
) -> CustomResult<api_models::disputes::DisputeEvidenceBlock, errors::ApiErrorResponse> {
let file_metadata = state
.store
- .find_file_metadata_by_merchant_id_file_id(&merchant_account.merchant_id, &file_id)
+ .find_file_metadata_by_merchant_id_file_id(merchant_account.get_id(), &file_id)
.await
.change_context(errors::ApiErrorResponse::FileNotFound)
.attach_printable("Unable to retrieve file_metadata")?;
diff --git a/crates/router/src/core/files.rs b/crates/router/src/core/files.rs
index 9ba5c29ce76..243b93a4483 100644
--- a/crates/router/src/core/files.rs
+++ b/crates/router/src/core/files.rs
@@ -24,10 +24,14 @@ pub async fn files_create_core(
)
.await?;
let file_id = common_utils::generate_id(consts::ID_LENGTH, "file");
- let file_key = format!("{}/{}", merchant_account.merchant_id, file_id);
+ let file_key = format!(
+ "{}/{}",
+ merchant_account.get_id().get_string_repr(),
+ file_id
+ );
let file_new = diesel_models::file::FileMetadataNew {
file_id: file_id.clone(),
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
file_name: create_file_request.file_name.clone(),
file_size: create_file_request.file_size,
file_type: create_file_request.file_type.to_string(),
@@ -86,7 +90,7 @@ pub async fn files_delete_core(
state
.store
.as_ref()
- .delete_file_metadata_by_merchant_id_file_id(&merchant_account.merchant_id, &req.file_id)
+ .delete_file_metadata_by_merchant_id_file_id(merchant_account.get_id(), &req.file_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to delete file_metadata")?;
@@ -102,7 +106,7 @@ pub async fn files_retrieve_core(
let file_metadata_object = state
.store
.as_ref()
- .find_file_metadata_by_merchant_id_file_id(&merchant_account.merchant_id, &req.file_id)
+ .find_file_metadata_by_merchant_id_file_id(merchant_account.get_id(), &req.file_id)
.await
.change_context(errors::ApiErrorResponse::FileNotFound)
.attach_printable("Unable to retrieve file_metadata")?;
diff --git a/crates/router/src/core/files/helpers.rs b/crates/router/src/core/files/helpers.rs
index ed95e7790e7..36c71f9a4f7 100644
--- a/crates/router/src/core/files/helpers.rs
+++ b/crates/router/src/core/files/helpers.rs
@@ -43,7 +43,7 @@ pub async fn validate_file_upload(
.ok_or(errors::ApiErrorResponse::MissingDisputeId)?;
let dispute = state
.store
- .find_dispute_by_merchant_id_dispute_id(&merchant_account.merchant_id, dispute_id)
+ .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), dispute_id)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound {
dispute_id: dispute_id.to_string(),
@@ -87,7 +87,7 @@ pub async fn delete_file_using_file_id(
) -> CustomResult<(), errors::ApiErrorResponse> {
let file_metadata_object = state
.store
- .find_file_metadata_by_merchant_id_file_id(&merchant_account.merchant_id, &file_key)
+ .find_file_metadata_by_merchant_id_file_id(merchant_account.get_id(), &file_key)
.await
.change_context(errors::ApiErrorResponse::FileNotFound)?;
let (provider, provider_file_id) = match (
@@ -181,7 +181,7 @@ pub async fn retrieve_file_and_provider_file_id_from_file_id(
Some(file_key) => {
let file_metadata_object = state
.store
- .find_file_metadata_by_merchant_id_file_id(&merchant_account.merchant_id, &file_key)
+ .find_file_metadata_by_merchant_id_file_id(merchant_account.get_id(), &file_key)
.await
.change_context(errors::ApiErrorResponse::FileNotFound)?;
let (provider, provider_file_id) = match (
@@ -248,7 +248,7 @@ pub async fn upload_and_get_provider_provider_file_id_profile_id(
.ok_or(errors::ApiErrorResponse::MissingDisputeId)?;
let dispute = state
.store
- .find_dispute_by_merchant_id_dispute_id(&merchant_account.merchant_id, &dispute_id)
+ .find_dispute_by_merchant_id_dispute_id(merchant_account.get_id(), &dispute_id)
.await
.to_not_found_response(errors::ApiErrorResponse::DisputeNotFound { dispute_id })?;
let connector_data = api::ConnectorData::get_connector_by_name(
@@ -263,7 +263,7 @@ pub async fn upload_and_get_provider_provider_file_id_profile_id(
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&dispute.payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
@@ -273,7 +273,7 @@ pub async fn upload_and_get_provider_provider_file_id_profile_id(
.store
.find_payment_attempt_by_attempt_id_merchant_id(
&dispute.attempt_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rs
index 8ddd0b7aa24..dfd8e085f67 100644
--- a/crates/router/src/core/fraud_check.rs
+++ b/crates/router/src/core/fraud_check.rs
@@ -165,7 +165,7 @@ where
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
- id: merchant_account.merchant_id.clone(),
+ id: merchant_account.get_id().get_string_repr().to_owned(),
})
.ok();
@@ -658,7 +658,7 @@ pub async fn frm_fulfillment_core(
.find_payment_intent_by_payment_id_merchant_id(
&(&state).into(),
&req.payment_id.clone(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
@@ -672,7 +672,7 @@ pub async fn frm_fulfillment_core(
let existing_fraud_check = db
.find_fraud_check_by_payment_id_if_present(
req.payment_id.clone(),
- merchant_account.merchant_id.clone(),
+ merchant_account.get_id().clone(),
)
.await
.change_context(invalid_request_error.to_owned())?;
@@ -720,7 +720,7 @@ pub async fn make_fulfillment_api_call(
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&payment_intent.active_attempt.get_id(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
diff --git a/crates/router/src/core/fraud_check/flows/checkout_flow.rs b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
index 47ab1810f75..4aae07382f8 100644
--- a/crates/router/src/core/fraud_check/flows/checkout_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/checkout_flow.rs
@@ -54,7 +54,7 @@ impl ConstructFlowSpecificData<frm_api::Checkout, FraudCheckCheckoutData, FraudC
let router_data = RouterData {
flow: std::marker::PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
customer_id,
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.clone(),
diff --git a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
index 05aafb92f98..a16dc2b16e1 100644
--- a/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/fulfillment_flow.rs
@@ -40,7 +40,7 @@ pub async fn construct_fulfillment_router_data<'a>(
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
None,
key_store,
&profile_id,
@@ -60,7 +60,7 @@ pub async fn construct_fulfillment_router_data<'a>(
)?;
let router_data = RouterData {
flow: std::marker::PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
connector,
payment_id: payment_attempt.payment_id.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
@@ -95,7 +95,7 @@ pub async fn construct_fulfillment_router_data<'a>(
payment_method_balance: None,
connector_request_reference_id: core_utils::get_connector_request_reference_id(
&state.conf,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
payment_attempt,
),
#[cfg(feature = "payouts")]
diff --git a/crates/router/src/core/fraud_check/flows/record_return.rs b/crates/router/src/core/fraud_check/flows/record_return.rs
index 2f263124083..3933a37676b 100644
--- a/crates/router/src/core/fraud_check/flows/record_return.rs
+++ b/crates/router/src/core/fraud_check/flows/record_return.rs
@@ -50,7 +50,7 @@ impl ConstructFlowSpecificData<RecordReturn, FraudCheckRecordReturnData, FraudCh
let currency = self.payment_attempt.clone().currency;
let router_data = RouterData {
flow: std::marker::PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
customer_id,
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.clone(),
diff --git a/crates/router/src/core/fraud_check/flows/sale_flow.rs b/crates/router/src/core/fraud_check/flows/sale_flow.rs
index fee1964a42a..58764edd635 100644
--- a/crates/router/src/core/fraud_check/flows/sale_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/sale_flow.rs
@@ -47,7 +47,7 @@ impl ConstructFlowSpecificData<frm_api::Sale, FraudCheckSaleData, FraudCheckResp
let router_data = RouterData {
flow: std::marker::PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
customer_id,
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.clone(),
diff --git a/crates/router/src/core/fraud_check/flows/transaction_flow.rs b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
index c5d00c4a8e9..1be03b846bf 100644
--- a/crates/router/src/core/fraud_check/flows/transaction_flow.rs
+++ b/crates/router/src/core/fraud_check/flows/transaction_flow.rs
@@ -57,7 +57,7 @@ impl
let router_data = RouterData {
flow: std::marker::PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
customer_id,
connector: connector_id.to_string(),
payment_id: self.payment_intent.payment_id.clone(),
diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
index 698eb43385e..ca7f110e899 100644
--- a/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
+++ b/crates/router/src/core/fraud_check/operation/fraud_check_post.rs
@@ -84,7 +84,7 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPost {
let existing_fraud_check = db
.find_fraud_check_by_payment_id_if_present(
payment_data.payment_intent.payment_id.clone(),
- payment_data.merchant_account.merchant_id.clone(),
+ payment_data.merchant_account.get_id().clone(),
)
.await
.ok();
@@ -94,7 +94,7 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPost {
db.insert_fraud_check_response(FraudCheckNew {
frm_id: utils::generate_id(consts::ID_LENGTH, "frm"),
payment_id: payment_data.payment_intent.payment_id.clone(),
- merchant_id: payment_data.merchant_account.merchant_id.clone(),
+ merchant_id: payment_data.merchant_account.get_id().clone(),
attempt_id: payment_data.payment_attempt.attempt_id.clone(),
created_at: common_utils::date_time::now(),
frm_name: frm_connector_details.connector_name,
diff --git a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
index 6a0bd78130d..05b803074d6 100644
--- a/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
+++ b/crates/router/src/core/fraud_check/operation/fraud_check_pre.rs
@@ -79,7 +79,7 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPre {
let existing_fraud_check = db
.find_fraud_check_by_payment_id_if_present(
payment_data.payment_intent.payment_id.clone(),
- payment_data.merchant_account.merchant_id.clone(),
+ payment_data.merchant_account.get_id().clone(),
)
.await
.ok();
@@ -90,7 +90,7 @@ impl GetTracker<PaymentToFrmData> for FraudCheckPre {
db.insert_fraud_check_response(FraudCheckNew {
frm_id: Uuid::new_v4().simple().to_string(),
payment_id: payment_data.payment_intent.payment_id.clone(),
- merchant_id: payment_data.merchant_account.merchant_id.clone(),
+ merchant_id: payment_data.merchant_account.get_id().clone(),
attempt_id: payment_data.payment_attempt.attempt_id.clone(),
created_at: common_utils::date_time::now(),
frm_name: frm_connector_details.connector_name,
diff --git a/crates/router/src/core/fraud_check/types.rs b/crates/router/src/core/fraud_check/types.rs
index bc30ad83b14..d35e3227e6d 100644
--- a/crates/router/src/core/fraud_check/types.rs
+++ b/crates/router/src/core/fraud_check/types.rs
@@ -43,7 +43,7 @@ pub struct PaymentDetails {
}
#[derive(Clone, Default, Debug)]
pub struct FrmMerchantAccount {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Clone, Debug)]
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index 22b3b29e03b..9eecbc17e49 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -14,7 +14,7 @@ use crate::{
pub async fn rust_locker_migration(
state: SessionState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<services::ApplicationResponse<MigrateCardResponse>, errors::ApiErrorResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
@@ -79,7 +79,7 @@ pub async fn call_to_locker(
state: &SessionState,
payment_methods: Vec<PaymentMethod>,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
merchant_account: &domain::MerchantAccount,
) -> CustomResult<usize, errors::ApiErrorResponse> {
let mut cards_moved = 0;
@@ -149,7 +149,7 @@ pub async fn call_to_locker(
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(format!(
- "Card migration failed for merchant_id: {merchant_id}, customer_id: {customer_id:?}, payment_method_id: {} ",
+ "Card migration failed for merchant_id: {merchant_id:?}, customer_id: {customer_id:?}, payment_method_id: {} ",
pm.payment_method_id
));
@@ -164,7 +164,7 @@ pub async fn call_to_locker(
cards_moved += 1;
logger::info!(
- "Card migrated for merchant_id: {merchant_id}, customer_id: {customer_id:?}, payment_method_id: {} ",
+ "Card migrated for merchant_id: {merchant_id:?}, customer_id: {customer_id:?}, payment_method_id: {} ",
pm.payment_method_id
);
}
diff --git a/crates/router/src/core/mandate.rs b/crates/router/src/core/mandate.rs
index e9cddebe09c..e74f7f11a73 100644
--- a/crates/router/src/core/mandate.rs
+++ b/crates/router/src/core/mandate.rs
@@ -41,7 +41,7 @@ pub async fn get_mandate(
.store
.as_ref()
.find_mandate_by_merchant_id_mandate_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&req.mandate_id,
merchant_account.storage_scheme,
)
@@ -68,7 +68,7 @@ pub async fn revoke_mandate(
let db = state.store.as_ref();
let mandate = db
.find_mandate_by_merchant_id_mandate_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&req.mandate_id,
merchant_account.storage_scheme,
)
@@ -88,7 +88,7 @@ pub async fn revoke_mandate(
let merchant_connector_account = payment_helper::get_merchant_connector_account(
&state,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
None,
&key_store,
&profile_id,
@@ -130,7 +130,7 @@ pub async fn revoke_mandate(
Ok(_) => {
let update_mandate = db
.update_mandate_by_merchant_id_mandate_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&req.mandate_id,
storage::MandateUpdate::StatusUpdate {
mandate_status: storage::enums::MandateStatus::Revoked,
@@ -172,7 +172,7 @@ pub async fn revoke_mandate(
#[instrument(skip(db))]
pub async fn update_connector_mandate_id(
db: &dyn StorageInterface,
- merchant_account: String,
+ merchant_id: &id_type::MerchantId,
mandate_ids_opt: Option<String>,
payment_method_id: Option<String>,
resp: Result<types::PaymentsResponseData, types::ErrorResponse>,
@@ -191,7 +191,7 @@ pub async fn update_connector_mandate_id(
//Ignore updation if the payment_attempt mandate_id or connector_mandate_id is not present
if let Some((mandate_id, connector_id)) = mandate_ids_opt.zip(connector_mandate_id) {
let mandate = db
- .find_mandate_by_merchant_id_mandate_id(&merchant_account, &mandate_id, storage_scheme)
+ .find_mandate_by_merchant_id_mandate_id(merchant_id, &mandate_id, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::MandateNotFound)?;
@@ -211,7 +211,7 @@ pub async fn update_connector_mandate_id(
// only update the connector_mandate_id if existing is none
if mandate.connector_mandate_id.is_none() {
db.update_mandate_by_merchant_id_mandate_id(
- &merchant_account,
+ merchant_id,
&mandate_id,
update_mandate_details,
mandate,
@@ -234,15 +234,15 @@ pub async fn get_customer_mandates(
let mandates = state
.store
.find_mandate_by_merchant_id_customer_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&req.get_merchant_reference_id(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
- "Failed while finding mandate: merchant_id: {}, customer_id: {:?}",
- merchant_account.merchant_id,
+ "Failed while finding mandate: merchant_id: {:?}, customer_id: {:?}",
+ merchant_account.get_id(),
req.get_merchant_reference_id()
)
})?;
@@ -281,7 +281,7 @@ pub async fn update_mandate_procedure<F, FData>(
state: &SessionState,
resp: types::RouterData<F, FData, types::PaymentsResponseData>,
mandate: Mandate,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
pm_id: Option<String>,
storage_scheme: MerchantStorageScheme,
) -> errors::RouterResult<types::RouterData<F, FData, types::PaymentsResponseData>>
@@ -371,7 +371,7 @@ where
let orig_mandate = state
.store
.find_mandate_by_merchant_id_mandate_id(
- resp.merchant_id.as_ref(),
+ &resp.merchant_id,
mandate_id,
storage_scheme,
)
@@ -484,7 +484,7 @@ pub async fn retrieve_mandates_list(
let mandates = state
.store
.as_ref()
- .find_mandates_by_merchant_id(&merchant_account.merchant_id, constraints)
+ .find_mandates_by_merchant_id(merchant_account.get_id(), constraints)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to retrieve mandates")?;
diff --git a/crates/router/src/core/mandate/helpers.rs b/crates/router/src/core/mandate/helpers.rs
index a4eb18371f0..9899d85fc73 100644
--- a/crates/router/src/core/mandate/helpers.rs
+++ b/crates/router/src/core/mandate/helpers.rs
@@ -23,7 +23,7 @@ pub async fn get_profile_id_for_mandate(
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
diff --git a/crates/router/src/core/mandate/utils.rs b/crates/router/src/core/mandate/utils.rs
index d158f173173..81dbfd1d41d 100644
--- a/crates/router/src/core/mandate/utils.rs
+++ b/crates/router/src/core/mandate/utils.rs
@@ -28,7 +28,7 @@ pub async fn construct_mandate_revoke_router_data(
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let router_data = types::RouterData {
flow: PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
customer_id: Some(mandate.customer_id),
connector_customer: None,
connector: mandate.connector,
diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rs
index bf50405ba81..a6d50fe6156 100644
--- a/crates/router/src/core/payment_link.rs
+++ b/crates/router/src/core/payment_link.rs
@@ -53,7 +53,7 @@ pub async fn initiate_payment_link_flow(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
payment_id: String,
) -> RouterResponse<services::PaymentLinkFormData> {
let db = &*state.store;
@@ -314,7 +314,7 @@ pub async fn list_payment_link(
) -> RouterResponse<Vec<api_models::payments::RetrievePaymentLinkResponse>> {
let db = state.store.as_ref();
let payment_link = db
- .list_payment_link_by_merchant_id(&merchant.merchant_id, constraints)
+ .list_payment_link_by_merchant_id(merchant.get_id(), constraints)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to retrieve payment link")?;
@@ -492,7 +492,7 @@ pub async fn get_payment_link_status(
state: SessionState,
merchant_account: domain::MerchantAccount,
key_store: domain::MerchantKeyStore,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
payment_id: String,
) -> RouterResponse<services::PaymentLinkFormData> {
let db = &*state.store;
diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rs
index 86cb1fc1b1e..6566d30e128 100644
--- a/crates/router/src/core/payment_methods.rs
+++ b/crates/router/src/core/payment_methods.rs
@@ -189,7 +189,7 @@ pub async fn create_pm_collect_db_entry(
.customer_id
.get_string_repr()
.to_string(),
- merchant_id: merchant_account.merchant_id.to_string(),
+ merchant_id: merchant_account.get_id().to_owned(),
link_type: common_enums::GenericLinkType::PaymentMethodCollect,
link_data,
url: pm_collect_link_data.link.clone(),
@@ -380,7 +380,7 @@ pub async fn add_payment_method_status_update_task(
payment_method: &diesel_models::PaymentMethod,
prev_status: enums::PaymentMethodStatus,
curr_status: enums::PaymentMethodStatus,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> Result<(), errors::ProcessTrackerError> {
let created_at = payment_method.created_at;
let schedule_time =
@@ -390,7 +390,7 @@ pub async fn add_payment_method_status_update_task(
payment_method_id: payment_method.payment_method_id.clone(),
prev_status,
curr_status,
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
};
let runner = storage::ProcessTrackerRunner::PaymentMethodStatusUpdateWorkflow;
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index fd8da0e24f3..47f3ba0ab42 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -86,7 +86,7 @@ pub async fn create_payment_method(
customer_id: &id_type::CustomerId,
payment_method_id: &str,
locker_id: Option<String>,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
payment_method_data: Option<Encryption>,
@@ -121,7 +121,7 @@ pub async fn create_payment_method(
.insert_payment_method(
storage::PaymentMethodNew {
customer_id: customer_id.to_owned(),
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
payment_method_id: payment_method_id.to_string(),
locker_id,
payment_method: req.payment_method,
@@ -160,7 +160,7 @@ pub async fn create_payment_method(
if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {
let _ = set_default_payment_method(
state,
- merchant_id.to_string(),
+ merchant_id,
key_store.clone(),
customer_id,
payment_method_id.to_owned(),
@@ -175,14 +175,14 @@ pub async fn create_payment_method(
pub fn store_default_payment_method(
req: &api::PaymentMethodCreate,
customer_id: &id_type::CustomerId,
- merchant_id: &String,
+ merchant_id: &id_type::MerchantId,
) -> (
api::PaymentMethodResponse,
Option<payment_methods::DataDuplicationCheck>,
) {
let pm_id = generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
customer_id: Some(customer_id.to_owned()),
payment_method_id: pm_id,
payment_method: req.payment_method,
@@ -251,7 +251,7 @@ pub async fn get_or_insert_payment_method(
resp,
&req,
key_store,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
customer_id,
resp.metadata.clone().map(|val| val.expose()),
None,
@@ -274,7 +274,7 @@ pub async fn get_or_insert_payment_method(
pub async fn migrate_payment_method(
state: routes::SessionState,
req: api::PaymentMethodMigrate,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
@@ -326,7 +326,7 @@ pub async fn migrate_payment_method(
skip_locker_call_and_migrate_payment_method(
state,
&req,
- merchant_id.into(),
+ merchant_id.to_owned(),
key_store,
merchant_account,
card_bin_details.clone(),
@@ -449,7 +449,7 @@ impl
pub async fn skip_locker_call_and_migrate_payment_method(
state: routes::SessionState,
req: &api::PaymentMethodMigrate,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
merchant_account: &domain::MerchantAccount,
card: api_models::payment_methods::CardDetailFromLocker,
@@ -508,7 +508,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(
.insert_payment_method(
storage::PaymentMethodNew {
customer_id: customer_id.to_owned(),
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
payment_method_id: payment_method_id.to_string(),
locker_id: None,
payment_method: req.payment_method,
@@ -549,7 +549,7 @@ pub async fn skip_locker_call_and_migrate_payment_method(
if customer.default_payment_method_id.is_none() && req.payment_method.is_some() {
let _ = set_default_payment_method(
&state,
- merchant_id.to_string(),
+ &merchant_id,
key_store.clone(),
&customer_id,
payment_method_id.to_owned(),
@@ -590,7 +590,7 @@ pub async fn get_client_secret_or_add_payment_method(
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResponse<api::PaymentMethodResponse> {
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
#[cfg(not(feature = "payouts"))]
@@ -625,7 +625,7 @@ pub async fn get_client_secret_or_add_payment_method(
&customer_id,
payment_method_id.as_str(),
None,
- merchant_id.as_str(),
+ merchant_id,
None,
None,
None,
@@ -722,7 +722,7 @@ pub async fn add_payment_method_data(
.find_customer_by_customer_id_merchant_id(
&(&state).into(),
&customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
@@ -837,7 +837,7 @@ pub async fn add_payment_method_data(
if customer.default_payment_method_id.is_none() {
let _ = set_default_payment_method(
&state,
- merchant_account.merchant_id.clone(),
+ merchant_account.get_id(),
key_store.clone(),
&customer_id,
pm_id,
@@ -885,7 +885,7 @@ pub async fn add_payment_method(
) -> errors::RouterResponse<api::PaymentMethodResponse> {
req.validate()?;
let db = &*state.store;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let customer_id = req.customer_id.clone().get_required_value("customer_id")?;
let payment_method = req.payment_method.get_required_value("payment_method")?;
let payment_method_billing_address: Option<Encryptable<Secret<serde_json::Value>>> = req
@@ -1129,7 +1129,7 @@ pub async fn insert_payment_method(
resp: &api::PaymentMethodResponse,
req: &api::PaymentMethodCreate,
key_store: &domain::MerchantKeyStore,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
pm_metadata: Option<serde_json::Value>,
customer_acceptance: Option<serde_json::Value>,
@@ -1495,7 +1495,7 @@ pub async fn add_bank_to_locker(
let payload =
payment_methods::StoreLockerReq::LockerGeneric(payment_methods::StoreGenericReq {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
merchant_customer_id: customer_id.to_owned(),
enc_data,
ttl: state.conf.locker.ttl_for_storage_in_secs,
@@ -1511,7 +1511,7 @@ pub async fn add_bank_to_locker(
bank.clone(),
store_resp.card_reference,
req,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
);
Ok((payment_method_resp, store_resp.duplication_check))
}
@@ -1569,7 +1569,7 @@ pub async fn add_card_to_locker(
pub async fn get_card_from_locker(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
card_reference: &str,
) -> errors::RouterResult<Card> {
metrics::GET_FROM_LOCKER.add(&metrics::CONTEXT, 1, &[]);
@@ -1611,7 +1611,7 @@ pub async fn get_card_from_locker(
pub async fn delete_card_from_locker(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
card_reference: &str,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
metrics::DELETE_FROM_LOCKER.add(&metrics::CONTEXT, 1, &[]);
@@ -1649,7 +1649,7 @@ pub async fn add_card_hs(
errors::VaultError,
> {
let payload = payment_methods::StoreLockerReq::LockerCard(payment_methods::StoreCardReq {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
merchant_customer_id: customer_id.to_owned(),
requestor_card_reference: card_reference.map(str::to_string),
card: Card {
@@ -1670,7 +1670,7 @@ pub async fn add_card_hs(
card.clone(),
store_card_payload.card_reference,
req,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
);
Ok((payment_method_resp, store_card_payload.duplication_check))
}
@@ -1707,7 +1707,7 @@ pub async fn get_payment_method_from_hs_locker<'a>(
state: &'a routes::SessionState,
key_store: &domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_method_reference: &'a str,
locker_choice: Option<api_enums::LockerChoice>,
) -> errors::CustomResult<Secret<String>, errors::VaultError> {
@@ -1769,9 +1769,9 @@ pub async fn get_payment_method_from_hs_locker<'a>(
}
#[instrument(skip_all)]
-pub async fn call_to_locker_hs<'a>(
+pub async fn call_to_locker_hs(
state: &routes::SessionState,
- payload: &payment_methods::StoreLockerReq<'a>,
+ payload: &payment_methods::StoreLockerReq,
customer_id: &id_type::CustomerId,
locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<payment_methods::StoreCardRespPayload, errors::VaultError> {
@@ -1866,7 +1866,7 @@ pub async fn update_payment_method_connector_mandate_details(
pub async fn get_card_from_hs_locker<'a>(
state: &'a routes::SessionState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
card_reference: &'a str,
locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<Card, errors::VaultError> {
@@ -1923,7 +1923,7 @@ pub async fn get_card_from_hs_locker<'a>(
pub async fn delete_card_from_hs_locker<'a>(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
card_reference: &'a str,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
let locker = &state.conf.locker;
@@ -1968,10 +1968,10 @@ pub async fn delete_card_from_hs_locker<'a>(
}
///Mock api for local testing
-pub async fn mock_call_to_locker_hs<'a>(
+pub async fn mock_call_to_locker_hs(
db: &dyn db::StorageInterface,
card_id: &str,
- payload: &payment_methods::StoreLockerReq<'a>,
+ payload: &payment_methods::StoreLockerReq,
card_cvc: Option<String>,
payment_method_id: Option<String>,
customer_id: Option<&id_type::CustomerId>,
@@ -1981,7 +1981,7 @@ pub async fn mock_call_to_locker_hs<'a>(
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: "".to_string(),
+ merchant_id: id_type::MerchantId::default(),
card_number: "4111111111111111".to_string(),
card_exp_year: "2099".to_string(),
card_exp_month: "12".to_string(),
@@ -1994,7 +1994,7 @@ pub async fn mock_call_to_locker_hs<'a>(
};
locker_mock_up = match payload {
payment_methods::StoreLockerReq::LockerCard(store_card_req) => storage::LockerMockUpNew {
- merchant_id: store_card_req.merchant_id.to_string(),
+ merchant_id: store_card_req.merchant_id.to_owned(),
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(),
@@ -2004,7 +2004,7 @@ pub async fn mock_call_to_locker_hs<'a>(
},
payment_methods::StoreLockerReq::LockerGeneric(store_generic_req) => {
storage::LockerMockUpNew {
- merchant_id: store_generic_req.merchant_id.to_string(),
+ merchant_id: store_generic_req.merchant_id.to_owned(),
enc_card_data: Some(store_generic_req.enc_data.to_owned()),
..locker_mock_up
}
@@ -2084,7 +2084,7 @@ pub async fn mock_get_payment_method<'a>(
.payment_method_id
.unwrap_or(locker_mock_up.card_id),
external_id: locker_mock_up.external_id,
- merchant_id: Some(locker_mock_up.merchant_id),
+ merchant_id: Some(locker_mock_up.merchant_id.to_owned()),
nickname: locker_mock_up.nickname,
customer_id: locker_mock_up.customer_id,
duplicate: locker_mock_up.duplicate,
@@ -2243,7 +2243,7 @@ pub async fn list_payment_methods(
pi.shipping_address_id.clone(),
&key_store,
&pi.payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
@@ -2260,7 +2260,7 @@ pub async fn list_payment_methods(
pi.billing_address_id.clone(),
&key_store,
&pi.payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
@@ -2325,7 +2325,7 @@ pub async fn list_payment_methods(
let all_mcas = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
key_manager_state,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
false,
&key_store,
)
@@ -2351,7 +2351,7 @@ pub async fn list_payment_methods(
let business_profile = core_utils::validate_and_get_business_profile(
db,
profile_id.as_ref(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
)
.await?;
@@ -2371,7 +2371,8 @@ pub async fn list_payment_methods(
})?;
format!(
"pm_filters_cgraph_{}_{}",
- &merchant_account.merchant_id, profile_id
+ merchant_account.get_id(),
+ profile_id
)
};
@@ -2468,7 +2469,7 @@ pub async fn list_payment_methods(
match db
.find_payment_method_by_customer_id_merchant_id_list(
&customer.customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
None,
)
.await
@@ -3704,7 +3705,7 @@ pub async fn list_customer_payment_method(
.find_customer_by_customer_id_merchant_id(
&state.into(),
customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
@@ -3713,7 +3714,7 @@ pub async fn list_customer_payment_method(
let is_requires_cvv = db
.find_config_by_key_unwrap_or(
- format!("{}_requires_cvv", merchant_account.merchant_id).as_str(),
+ &merchant_account.get_id().get_requires_cvv_key(),
Some("true".to_string()),
)
.await
@@ -3725,14 +3726,13 @@ pub async fn list_customer_payment_method(
let resp = db
.find_payment_method_by_customer_id_merchant_id_status(
customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
common_enums::PaymentMethodStatus::Active,
limit,
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
- //let mca = query::find_mca_by_merchant_id(conn, &merchant_account.merchant_id)?;
let mut customer_pms = Vec::new();
let profile_id = payment_intent
@@ -3755,7 +3755,7 @@ pub async fn list_customer_payment_method(
let business_profile = core_utils::validate_and_get_business_profile(
db,
profile_id.as_ref(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
)
.await?;
@@ -3883,7 +3883,7 @@ pub async fn list_customer_payment_method(
let mca_enabled = get_mca_status(
state,
&key_store,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
is_connector_agnostic_mit_enabled,
connector_mandate_details,
pm.network_transaction_id.as_ref(),
@@ -3982,7 +3982,7 @@ pub async fn list_customer_payment_method(
.store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_intent.payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&payment_intent.active_attempt.get_id(),
merchant_account.storage_scheme,
)
@@ -4014,7 +4014,7 @@ pub async fn list_customer_payment_method(
pub async fn get_mca_status(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
is_connector_agnostic_mit_enabled: bool,
connector_mandate_details: Option<storage::PaymentsMandateReference>,
network_transaction_id: Option<&String>,
@@ -4033,7 +4033,7 @@ pub async fn get_mca_status(
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
- id: merchant_id.to_string(),
+ id: merchant_id.get_string_repr().to_owned(),
})?;
let mut mca_ids = HashSet::new();
@@ -4298,7 +4298,7 @@ async fn get_bank_account_connector_details(
}
pub async fn set_default_payment_method(
state: &routes::SessionState,
- merchant_id: String,
+ merchant_id: &id_type::MerchantId,
key_store: domain::MerchantKeyStore,
customer_id: &id_type::CustomerId,
payment_method_id: String,
@@ -4312,7 +4312,7 @@ pub async fn set_default_payment_method(
.find_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id,
- &merchant_id,
+ merchant_id,
&key_store,
storage_scheme,
)
@@ -4328,7 +4328,7 @@ pub async fn set_default_payment_method(
.get_required_value("payment_method")?;
utils::when(
- &payment_method.customer_id != customer_id || payment_method.merchant_id != merchant_id,
+ &payment_method.customer_id != customer_id || payment_method.merchant_id != *merchant_id,
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "The payment_method_id is not valid".to_string(),
@@ -4400,7 +4400,7 @@ pub async fn get_bank_from_hs_locker(
key_store: &domain::MerchantKeyStore,
temp_token: &str,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
token_ref: &str,
) -> errors::RouterResult<api::BankPayout> {
let payment_method = get_payment_method_from_hs_locker(
@@ -4605,7 +4605,7 @@ pub async fn delete_payment_method(
.find_customer_by_customer_id_merchant_id(
key_manager_state,
&key.customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
@@ -4631,7 +4631,7 @@ pub async fn delete_payment_method(
}
db.delete_payment_method_by_merchant_id_payment_method_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
pm_id.payment_method_id.as_str(),
)
.await
diff --git a/crates/router/src/core/payment_methods/migration.rs b/crates/router/src/core/payment_methods/migration.rs
index 83e9993478b..d548d03ab47 100644
--- a/crates/router/src/core/payment_methods/migration.rs
+++ b/crates/router/src/core/payment_methods/migration.rs
@@ -12,7 +12,7 @@ use crate::{
pub async fn migrate_payment_methods(
state: routes::SessionState,
payment_methods: Vec<PaymentMethodRecord>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_account: &domain::MerchantAccount,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResponse<Vec<PaymentMethodMigrationResponse>> {
@@ -58,7 +58,8 @@ fn parse_csv(data: &[u8]) -> csv::Result<Vec<PaymentMethodRecord>> {
}
pub fn get_payment_method_records(
form: PaymentMethodsMigrateForm,
-) -> Result<(String, Vec<PaymentMethodRecord>), errors::ApiErrorResponse> {
+) -> Result<(common_utils::id_type::MerchantId, Vec<PaymentMethodRecord>), errors::ApiErrorResponse>
+{
match parse_csv(form.file.data.to_bytes()) {
Ok(records) => {
if let Some(first_record) = records.first() {
diff --git a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
index fd209e78da2..6a3ceeada1c 100644
--- a/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
+++ b/crates/router/src/core/payment_methods/surcharge_decision_configs.rs
@@ -378,10 +378,10 @@ fn get_surcharge_details_from_surcharge_output(
#[instrument(skip_all)]
pub async fn ensure_algorithm_cached(
store: &dyn StorageInterface,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &str,
) -> ConditionalConfigResult<VirInterpreterBackendCacheWrapper> {
- let key = format!("surcharge_dsl_{merchant_id}");
+ let key = merchant_id.get_surcharge_dsk_key();
let value_to_cache = || async {
let config: diesel_models::Config = store.find_config_by_key(algorithm_id).await?;
diff --git a/crates/router/src/core/payment_methods/transformers.rs b/crates/router/src/core/payment_methods/transformers.rs
index 6bfadabdb35..9ca2bffc88c 100644
--- a/crates/router/src/core/payment_methods/transformers.rs
+++ b/crates/router/src/core/payment_methods/transformers.rs
@@ -21,12 +21,12 @@ use crate::{
#[derive(Debug, Serialize)]
#[serde(untagged)]
-pub enum StoreLockerReq<'a> {
- LockerCard(StoreCardReq<'a>),
- LockerGeneric(StoreGenericReq<'a>),
+pub enum StoreLockerReq {
+ LockerCard(StoreCardReq),
+ LockerGeneric(StoreGenericReq),
}
-impl StoreLockerReq<'_> {
+impl StoreLockerReq {
pub fn update_requestor_card_reference(&mut self, card_reference: Option<String>) {
match self {
Self::LockerCard(c) => c.requestor_card_reference = card_reference,
@@ -36,8 +36,8 @@ impl StoreLockerReq<'_> {
}
#[derive(Debug, Deserialize, Serialize)]
-pub struct StoreCardReq<'a> {
- pub merchant_id: &'a str,
+pub struct StoreCardReq {
+ pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: id_type::CustomerId,
#[serde(skip_serializing_if = "Option::is_none")]
pub requestor_card_reference: Option<String>,
@@ -46,8 +46,8 @@ pub struct StoreCardReq<'a> {
}
#[derive(Debug, Deserialize, Serialize)]
-pub struct StoreGenericReq<'a> {
- pub merchant_id: &'a str,
+pub struct StoreGenericReq {
+ pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: id_type::CustomerId,
#[serde(rename = "enc_card_data")]
pub enc_data: String,
@@ -76,8 +76,8 @@ pub enum DataDuplicationCheck {
}
#[derive(Debug, Deserialize, Serialize)]
-pub struct CardReqBody<'a> {
- pub merchant_id: &'a str,
+pub struct CardReqBody {
+ pub merchant_id: id_type::MerchantId,
pub merchant_customer_id: id_type::CustomerId,
pub card_reference: String,
}
@@ -105,12 +105,12 @@ pub struct DeleteCardResp {
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct AddCardRequest<'a> {
+pub struct AddCardRequest {
pub card_number: cards::CardNumber,
pub customer_id: id_type::CustomerId,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
- pub merchant_id: &'a str,
+ pub merchant_id: id_type::MerchantId,
pub email_address: Option<Email>,
pub name_on_card: Option<Secret<String>>,
pub nickname: Option<String>,
@@ -124,7 +124,7 @@ pub struct AddCardResponse {
pub card_fingerprint: Secret<String>,
pub card_global_fingerprint: Secret<String>,
#[serde(rename = "merchant_id")]
- pub merchant_id: Option<String>,
+ pub merchant_id: Option<id_type::MerchantId>,
pub card_number: Option<cards::CardNumber>,
pub card_exp_year: Option<Secret<String>>,
pub card_exp_month: Option<Secret<String>>,
@@ -140,7 +140,7 @@ pub struct AddPaymentMethodResponse {
pub payment_method_id: String,
pub external_id: String,
#[serde(rename = "merchant_id")]
- pub merchant_id: Option<String>,
+ pub merchant_id: Option<id_type::MerchantId>,
pub nickname: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub duplicate: Option<bool>,
@@ -285,10 +285,10 @@ pub async fn mk_basilisk_req(
Ok(jwe_body)
}
-pub async fn mk_add_locker_request_hs<'a>(
+pub async fn mk_add_locker_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
- payload: &StoreLockerReq<'a>,
+ payload: &StoreLockerReq,
locker_choice: api_enums::LockerChoice,
) -> CustomResult<services::Request, errors::VaultError> {
let payload = payload
@@ -317,7 +317,7 @@ pub fn mk_add_bank_response_hs(
bank: api::BankPayout,
bank_reference: String,
req: api::PaymentMethodCreate,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
api::PaymentMethodResponse {
merchant_id: merchant_id.to_owned(),
@@ -341,7 +341,7 @@ pub fn mk_add_card_response_hs(
card: api::CardDetail,
card_reference: String,
req: api::PaymentMethodCreate,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> api::PaymentMethodResponse {
let card_number = card.card_number.clone();
let last4_digits = card_number.get_last4();
@@ -390,13 +390,13 @@ pub async fn mk_get_card_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
card_reference: &str,
locker_choice: Option<api_enums::LockerChoice>,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = customer_id.to_owned();
let card_req_body = CardReqBody {
- merchant_id,
+ merchant_id: merchant_id.to_owned(),
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
@@ -462,12 +462,12 @@ pub async fn mk_delete_card_request_hs(
jwekey: &settings::Jwekey,
locker: &settings::Locker,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
card_reference: &str,
) -> CustomResult<services::Request, errors::VaultError> {
let merchant_customer_id = customer_id.to_owned();
let card_req_body = CardReqBody {
- merchant_id,
+ merchant_id: merchant_id.to_owned(),
merchant_customer_id,
card_reference: card_reference.to_owned(),
};
@@ -492,24 +492,6 @@ pub async fn mk_delete_card_request_hs(
Ok(request)
}
-pub fn mk_delete_card_request(
- locker: &settings::Locker,
- merchant_id: &'static str,
- card_id: &'static str,
-) -> CustomResult<services::Request, errors::VaultError> {
- let delete_card_req = GetCard {
- merchant_id,
- card_id,
- };
- let mut url = locker.host.to_owned();
- url.push_str("/card/deleteCard");
- let mut request = services::Request::new(services::Method::Post, &url);
- request.add_default_headers();
-
- request.set_body(RequestContent::FormUrlEncoded(Box::new(delete_card_req)));
- Ok(request)
-}
-
pub fn mk_delete_card_response(
response: DeleteCardResponse,
) -> errors::RouterResult<DeleteCardResp> {
diff --git a/crates/router/src/core/payment_methods/validator.rs b/crates/router/src/core/payment_methods/validator.rs
index 23470fb3ef1..c45f6df837d 100644
--- a/crates/router/src/core/payment_methods/validator.rs
+++ b/crates/router/src/core/payment_methods/validator.rs
@@ -24,7 +24,7 @@ pub async fn validate_request_and_initiate_payment_method_collect_link(
// Validate customer_id
let db: &dyn StorageInterface = &*state.store;
let customer_id = req.customer_id.clone();
- let merchant_id = merchant_account.merchant_id.clone();
+ let merchant_id = merchant_account.get_id().clone();
match db
.find_customer_by_customer_id_merchant_id(
&state.into(),
@@ -40,7 +40,7 @@ pub async fn validate_request_and_initiate_payment_method_collect_link(
if err.current_context().is_db_not_found() {
Err(err).change_context(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
- "customer [{}] not found for merchant [{}]",
+ "customer [{}] not found for merchant [{:?}]",
customer_id.get_string_repr(),
merchant_id
),
@@ -102,7 +102,8 @@ pub async fn validate_request_and_initiate_payment_method_collect_link(
None => default_config.expiry,
};
let link = Secret::new(format!(
- "{domain}/payment_methods/collect/{merchant_id}/{pm_collect_link_id}"
+ "{domain}/payment_methods/collect/{}/{pm_collect_link_id}",
+ merchant_id.get_string_repr()
));
let enabled_payment_methods = match (&req.enabled_payment_methods, &merchant_config) {
(Some(enabled_payment_methods), _) => enabled_payment_methods.clone(),
diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rs
index 8d83cfb803f..e1d98c5056d 100644
--- a/crates/router/src/core/payments.rs
+++ b/crates/router/src/core/payments.rs
@@ -135,7 +135,7 @@ where
{
let operation: BoxedOperation<'_, F, Req> = Box::new(operation);
- tracing::Span::current().record("merchant_id", merchant_account.merchant_id.as_str());
+ tracing::Span::current().record("merchant_id", merchant_account.get_id().get_string_repr());
let (operation, validate_result) = operation
.to_validate_request()?
.validate_request(&req, &merchant_account)?;
@@ -274,7 +274,7 @@ where
payment_sync::get_sync_process_schedule_time(
&*state.store,
connector.connector.id(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
0,
)
.await
@@ -365,7 +365,7 @@ where
payment_sync::get_sync_process_schedule_time(
&*state.store,
connector_data.connector.id(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
0,
)
.await
@@ -401,11 +401,9 @@ where
#[cfg(feature = "retry")]
{
use crate::core::payments::retry::{self, GsmValidation};
- let config_bool = retry::config_should_call_gsm(
- &*state.store,
- &merchant_account.merchant_id,
- )
- .await;
+ let config_bool =
+ retry::config_should_call_gsm(&*state.store, merchant_account.get_id())
+ .await;
if config_bool && router_data.should_call_gsm() {
router_data = retry::do_gsm_actions(
@@ -633,7 +631,7 @@ where
let output = perform_decision_management(
state,
algorithm_ref,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
payment_data,
)
.await
@@ -856,7 +854,7 @@ fn is_start_pay<Op: Debug>(operation: &Op) -> bool {
pub struct PaymentsRedirectResponseData {
pub connector: Option<String>,
pub param: Option<String>,
- pub merchant_id: Option<String>,
+ pub merchant_id: Option<id_type::MerchantId>,
pub json_payload: Option<serde_json::Value>,
pub resource_id: api::PaymentIdType,
pub force_sync: bool,
@@ -907,7 +905,10 @@ pub trait PaymentRedirectFlow: Sync {
"connector",
req.connector.to_owned().unwrap_or("null".to_string()),
),
- ("merchant_id", merchant_account.merchant_id.to_owned()),
+ (
+ "merchant_id",
+ merchant_account.get_id().get_string_repr().to_owned(),
+ ),
]),
);
let connector = req.connector.clone().get_required_value("connector")?;
@@ -1198,7 +1199,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {
connector: String,
payment_id: String,
) -> RouterResult<Self::PaymentFlowResponse> {
- let merchant_id = merchant_account.merchant_id.clone();
+ let merchant_id = merchant_account.get_id().clone();
let payment_intent = state
.store
.find_payment_intent_by_payment_id_merchant_id(
@@ -1226,7 +1227,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {
let authentication = state
.store
.find_authentication_by_merchant_id_authentication_id(
- merchant_id.clone(),
+ &merchant_id,
authentication_id.clone(),
)
.await
@@ -1333,7 +1334,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {
// When intent status is RequiresCustomerAction, Set poll_id in redis to allow the fetch status of poll through retrieve_poll_status api from client
if payments_response.status == common_enums::IntentStatus::RequiresCustomerAction {
let req_poll_id = utils::get_external_authentication_request_poll_id(&payment_id);
- let poll_id = utils::get_poll_id(merchant_id.clone(), req_poll_id.clone());
+ let poll_id = utils::get_poll_id(&merchant_id, req_poll_id.clone());
let redis_conn = state
.store
.get_redis_conn()
@@ -1433,7 +1434,7 @@ pub async fn call_connector_service<F, RouterDReq, ApiRequest>(
payment_data: &mut PaymentData<F>,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
- validate_result: &operations::ValidateResult<'_>,
+ validate_result: &operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
@@ -1720,14 +1721,15 @@ pub async fn get_merchant_bank_data_for_open_banking_connectors(
let final_recipient_data = if let Some(id) = recipient_id {
if contains {
// Customer Id for OpenBanking connectors will be merchant_id as the account data stored at locker belongs to the merchant
- let cust_id = id_type::CustomerId::from(merchant_account.merchant_id.clone().into())
+ let merchant_id_str = merchant_account.get_id().get_string_repr().to_owned();
+ let cust_id = id_type::CustomerId::from(merchant_id_str.into())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert to CustomerId")?;
let locker_resp = cards::get_payment_method_from_hs_locker(
state,
key_store,
&cust_id,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
id.as_str(),
Some(enums::LockerChoice::HyperswitchCardVault),
)
@@ -1764,7 +1766,7 @@ where
F: Send + Clone + Sync,
{
let merchant_id = &payment_data.payment_attempt.merchant_id;
- let blocklist_enabled_key = format!("guard_blocklist_for_{merchant_id}");
+ let blocklist_enabled_key = merchant_id.get_blocklist_guard_key();
let blocklist_guard_enabled = state
.store
.find_config_by_key_unwrap_or(&blocklist_enabled_key, Some("false".to_string()))
@@ -2254,7 +2256,7 @@ where
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
payment_data.creds_identifier.to_owned(),
key_store,
&profile_id,
@@ -2494,7 +2496,7 @@ pub async fn get_connector_tokenization_action_when_confirm_true<F, Req>(
state: &SessionState,
operation: &BoxedOperation<'_, F, Req>,
payment_data: &mut PaymentData<F>,
- validate_result: &operations::ValidateResult<'_>,
+ validate_result: &operations::ValidateResult,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
@@ -2623,7 +2625,7 @@ pub async fn tokenize_in_router_when_confirm_false_or_external_authentication<F,
state: &SessionState,
operation: &BoxedOperation<'_, F, Req>,
payment_data: &mut PaymentData<F>,
- validate_result: &operations::ValidateResult<'_>,
+ validate_result: &operations::ValidateResult,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
business_profile: Option<&diesel_models::business_profile::BusinessProfile>,
@@ -2880,7 +2882,7 @@ pub async fn list_payments(
) -> RouterResponse<api::PaymentListResponse> {
use hyperswitch_domain_models::errors::StorageError;
helpers::validate_payment_list_request(&constraints)?;
- let merchant_id = &merchant.merchant_id;
+ let merchant_id = merchant.get_id();
let db = state.store.as_ref();
let payment_intents = helpers::filter_by_constraints(
&state,
@@ -2956,7 +2958,7 @@ pub async fn apply_filters_on_payments(
let list: Vec<(storage::PaymentIntent, storage::PaymentAttempt)> = db
.get_filtered_payment_intents_attempt(
&(&state).into(),
- &merchant.merchant_id,
+ merchant.get_id(),
&constraints.clone().into(),
&merchant_key_store,
merchant.storage_scheme,
@@ -2969,7 +2971,7 @@ pub async fn apply_filters_on_payments(
let active_attempt_ids = db
.get_filtered_active_attempt_ids_for_total_count(
- &merchant.merchant_id,
+ merchant.get_id(),
&constraints.clone().into(),
merchant.storage_scheme,
)
@@ -2978,7 +2980,7 @@ pub async fn apply_filters_on_payments(
let total_count = db
.get_total_count_of_filtered_payment_attempts(
- &merchant.merchant_id,
+ merchant.get_id(),
&active_attempt_ids,
constraints.connector,
constraints.payment_method,
@@ -3010,7 +3012,7 @@ pub async fn get_filters_for_payments(
let pi = db
.filter_payment_intents_by_time_range_constraints(
&(&state).into(),
- &merchant.merchant_id,
+ merchant.get_id(),
&time_range,
&merchant_key_store,
merchant.storage_scheme,
@@ -3021,7 +3023,7 @@ pub async fn get_filters_for_payments(
let filters = db
.get_filters_for_payments(
pi.as_slice(),
- &merchant.merchant_id,
+ merchant.get_id(),
// since OLAP doesn't have KV. Force to get the data from PSQL.
storage_enums::MerchantStorageScheme::PostgresOnly,
)
@@ -3046,7 +3048,7 @@ pub async fn get_payment_filters(
merchant: domain::MerchantAccount,
) -> RouterResponse<api::PaymentListFiltersV2> {
let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) =
- super::admin::list_payment_connectors(state, merchant.merchant_id).await?
+ super::admin::list_payment_connectors(state, merchant.get_id().to_owned()).await?
{
data
} else {
@@ -3443,7 +3445,7 @@ where
#[cfg(feature = "retry")]
let should_do_retry =
- retry::config_should_call_gsm(&*state.store, &merchant_account.merchant_id).await;
+ retry::config_should_call_gsm(&*state.store, merchant_account.get_id()).await;
#[cfg(feature = "retry")]
if payment_data.payment_attempt.payment_method_type
@@ -3946,7 +3948,7 @@ where
let connectors = routing::perform_static_routing_v1(
state,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
algorithm_ref,
&transaction_data,
)
@@ -4018,7 +4020,7 @@ pub async fn payment_external_authentication(
req: api_models::payments::PaymentsExternalAuthenticationRequest,
) -> RouterResponse<api_models::payments::PaymentsExternalAuthenticationResponse> {
let db = &*state.store;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let storage_scheme = merchant_account.storage_scheme;
let payment_id = req.payment_id;
let payment_intent = db
@@ -4059,7 +4061,7 @@ pub async fn payment_external_authentication(
.find_customer_by_customer_id_merchant_id(
&(&state).into(),
customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&key_store,
storage_scheme,
)
@@ -4118,7 +4120,7 @@ pub async fn payment_external_authentication(
.await?;
let authentication = db
.find_authentication_by_merchant_id_authentication_id(
- merchant_id.to_string(),
+ merchant_id,
payment_attempt
.authentication_id
.clone()
@@ -4229,7 +4231,7 @@ pub async fn payment_external_authentication(
#[instrument(skip_all)]
pub async fn get_extended_card_info(
state: SessionState,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
payment_id: String,
) -> RouterResponse<payments_api::ExtendedCardInfoResponse> {
let redis_conn = state
@@ -4298,7 +4300,7 @@ pub async fn payments_manual_update(
.find_payment_intent_by_payment_id_merchant_id(
&(&state).into(),
&payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
diff --git a/crates/router/src/core/payments/access_token.rs b/crates/router/src/core/payments/access_token.rs
index 39d2c4d4371..78ef29e473d 100644
--- a/crates/router/src/core/payments/access_token.rs
+++ b/crates/router/src/core/payments/access_token.rs
@@ -64,7 +64,7 @@ pub async fn add_access_token<
.connector_name
.supports_access_token(router_data.payment_method)
{
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let store = &*state.store;
// `merchant_connector_id` may not be present in the below cases
@@ -88,8 +88,8 @@ pub async fn add_access_token<
let res = match old_access_token {
Some(access_token) => {
router_env::logger::debug!(
- "Access token found in redis for merchant_id: {}, payment_id: {}, connector: {} which has expiry of: {} seconds",
- merchant_account.merchant_id,
+ "Access token found in redis for merchant_id: {:?}, payment_id: {}, connector: {} which has expiry of: {} seconds",
+ merchant_account.get_id(),
router_data.payment_id,
connector.connector_name,
access_token.expires
diff --git a/crates/router/src/core/payments/conditional_configs.rs b/crates/router/src/core/payments/conditional_configs.rs
index 7ec9a749152..4f5b84af762 100644
--- a/crates/router/src/core/payments/conditional_configs.rs
+++ b/crates/router/src/core/payments/conditional_configs.rs
@@ -21,7 +21,7 @@ pub type ConditionalConfigResult<O> = errors::CustomResult<O, ConfigError>;
pub async fn perform_decision_management<F: Clone>(
state: &routes::SessionState,
algorithm_ref: routing::RoutingAlgorithmRef,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_data: &mut payments::PaymentData<F>,
) -> ConditionalConfigResult<ConditionalConfigs> {
let algorithm_id = if let Some(id) = algorithm_ref.config_algo_id {
@@ -31,7 +31,7 @@ pub async fn perform_decision_management<F: Clone>(
};
let db = &*state.store;
- let key = format!("dsl_{merchant_id}");
+ let key = merchant_id.get_dsl_config();
let find_key_from_db = || async {
let config = db.find_config_by_key(&algorithm_id).await?;
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 183ee97edee..6dd8f194724 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -146,7 +146,7 @@ pub async fn create_or_update_address_for_payment_by_request(
session_state: &SessionState,
req_address: Option<&api::Address>,
address_id: Option<&str>,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
customer_id: Option<&id_type::CustomerId>,
merchant_key_store: &domain::MerchantKeyStore,
payment_id: &str,
@@ -279,7 +279,7 @@ pub async fn create_or_find_address_for_payment_by_request(
state: &SessionState,
req_address: Option<&api::Address>,
address_id: Option<&str>,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
customer_id: Option<&id_type::CustomerId>,
merchant_key_store: &domain::MerchantKeyStore,
payment_id: &str,
@@ -339,7 +339,7 @@ pub async fn create_or_find_address_for_payment_by_request(
pub async fn get_domain_address(
session_state: &SessionState,
address: &api_models::payments::Address,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key: &[u8],
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<domain::Address, common_utils::errors::CryptoError> {
@@ -355,7 +355,7 @@ pub async fn get_domain_address(
.and_then(|phone| phone.number.clone()),
email: address.email.clone(),
}),
- Identifier::Merchant(merchant_id.to_string()),
+ Identifier::Merchant(merchant_id.to_owned()),
key,
)
.await?;
@@ -365,7 +365,7 @@ pub async fn get_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_string(),
+ merchant_id: merchant_id.to_owned(),
address_id: generate_id(consts::ID_LENGTH, "add"),
city: address_details.and_then(|address_details| address_details.city.clone()),
country: address_details.and_then(|address_details| address_details.country),
@@ -390,7 +390,7 @@ pub async fn get_address_by_id(
address_id: Option<String>,
merchant_key_store: &domain::MerchantKeyStore,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Option<domain::Address>, errors::ApiErrorResponse> {
match address_id {
@@ -480,7 +480,7 @@ pub async fn get_token_pm_type_mandate_details(
verify_mandate_details_for_recurring_payments(
&payment_method_info.merchant_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&payment_method_info.customer_id,
customer_id,
)?;
@@ -530,7 +530,7 @@ pub async fn get_token_pm_type_mandate_details(
.store
.find_payment_method_by_customer_id_merchant_id_list(
customer_id,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
None,
)
.await
@@ -650,7 +650,7 @@ pub async fn get_token_for_recurring_mandate(
let mandate = db
.find_mandate_by_merchant_id_mandate_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
mandate_id.as_str(),
merchant_account.storage_scheme,
)
@@ -774,8 +774,8 @@ pub async fn get_token_for_recurring_mandate(
/// Check weather the merchant id in the request
/// and merchant id in the merchant account are same.
pub fn validate_merchant_id(
- merchant_id: &str,
- request_merchant_id: Option<&str>,
+ merchant_id: &id_type::MerchantId,
+ request_merchant_id: Option<&id_type::MerchantId>,
) -> CustomResult<(), errors::ApiErrorResponse> {
// Get Merchant Id from the merchant
// or get from merchant account
@@ -1091,7 +1091,10 @@ pub fn create_startpay_url(
) -> String {
format!(
"{}/payments/redirect/{}/{}/{}",
- base_url, payment_intent.payment_id, payment_intent.merchant_id, payment_attempt.attempt_id
+ base_url,
+ payment_intent.payment_id,
+ payment_intent.merchant_id.get_string_repr(),
+ payment_attempt.attempt_id
)
}
@@ -1104,7 +1107,10 @@ pub fn create_redirect_url(
let creds_identifier_path = creds_identifier.map_or_else(String::new, |cd| format!("/{}", cd));
format!(
"{}/payments/{}/{}/redirect/response/{}",
- router_base_url, payment_attempt.payment_id, payment_attempt.merchant_id, connector_name,
+ router_base_url,
+ payment_attempt.payment_id,
+ payment_attempt.merchant_id.get_string_repr(),
+ connector_name,
) + creds_identifier_path.as_ref()
}
@@ -1125,18 +1131,23 @@ pub fn create_authorize_url(
) -> String {
format!(
"{}/payments/{}/{}/authorize/{}",
- router_base_url, payment_attempt.payment_id, payment_attempt.merchant_id, connector_name
+ router_base_url,
+ payment_attempt.payment_id,
+ payment_attempt.merchant_id.get_string_repr(),
+ connector_name
)
}
pub fn create_webhook_url(
router_base_url: &String,
- merchant_id: &String,
+ merchant_id: &id_type::MerchantId,
connector_name: &String,
) -> String {
format!(
"{}/webhooks/{}/{}",
- router_base_url, merchant_id, connector_name
+ router_base_url,
+ merchant_id.get_string_repr(),
+ connector_name
)
}
pub fn create_complete_authorize_url(
@@ -1146,7 +1157,10 @@ pub fn create_complete_authorize_url(
) -> String {
format!(
"{}/payments/{}/{}/redirect/complete/{}",
- router_base_url, payment_attempt.payment_id, payment_attempt.merchant_id, connector_name
+ router_base_url,
+ payment_attempt.payment_id,
+ payment_attempt.merchant_id.get_string_repr(),
+ connector_name
)
}
@@ -1219,8 +1233,8 @@ pub fn verify_mandate_details(
}
pub fn verify_mandate_details_for_recurring_payments(
- mandate_merchant_id: &str,
- merchant_id: &str,
+ mandate_merchant_id: &id_type::MerchantId,
+ merchant_id: &id_type::MerchantId,
mandate_customer_id: &id_type::CustomerId,
customer_id: &id_type::CustomerId,
) -> RouterResult<()> {
@@ -1400,7 +1414,7 @@ pub(crate) async fn get_payment_method_create_request(
pub async fn get_customer_from_details<F: Clone>(
state: &SessionState,
customer_id: Option<id_type::CustomerId>,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_data: &mut PaymentData<F>,
merchant_key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
@@ -1524,7 +1538,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>(
operation: BoxedOperation<'a, F, R>,
payment_data: &mut PaymentData<F>,
req: Option<CustomerDetails>,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: common_enums::enums::MerchantStorageScheme,
) -> CustomResult<(BoxedOperation<'a, F, R>, Option<domain::Customer>), errors::StorageError> {
@@ -1645,7 +1659,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>(
db.update_customer_by_customer_id_merchant_id(
key_manager_state,
customer_id,
- merchant_id.to_string(),
+ merchant_id.to_owned(),
c,
customer_update,
key_store,
@@ -1659,7 +1673,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>(
None => {
let new_customer = domain::Customer {
customer_id,
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
name: encryptable_customer.name,
email: encryptable_customer.email,
phone: encryptable_customer.phone,
@@ -2474,7 +2488,7 @@ where
pub(super) async fn filter_by_constraints(
state: &SessionState,
constraints: &api::PaymentListConstraints,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, errors::DataStorageError> {
@@ -2611,7 +2625,7 @@ pub fn make_merchant_url_with_response(
pub async fn make_ephemeral_key(
state: SessionState,
customer_id: id_type::CustomerId,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> errors::RouterResponse<ephemeral_key::EphemeralKey> {
let store = &state.store;
let id = utils::generate_id(consts::ID_LENGTH, "eki");
@@ -2619,7 +2633,7 @@ pub async fn make_ephemeral_key(
let ek = ephemeral_key::EphemeralKeyNew {
id,
customer_id,
- merchant_id,
+ merchant_id: merchant_id.to_owned(),
secret,
};
let ek = store
@@ -2734,7 +2748,7 @@ pub fn check_if_operation_confirm<Op: std::fmt::Debug>(operations: Op) -> bool {
#[allow(clippy::too_many_arguments)]
pub fn generate_mandate(
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
payment_id: String,
connector: String,
setup_mandate_details: Option<MandateData>,
@@ -2912,7 +2926,7 @@ pub async fn verify_payment_intent_time_and_client_secret(
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
@@ -3010,7 +3024,7 @@ mod tests {
fn test_authenticate_client_secret_session_not_expired() {
let payment_intent = PaymentIntent {
payment_id: "23".to_string(),
- merchant_id: "22".to_string(),
+ merchant_id: id_type::MerchantId::default(),
status: storage_enums::IntentStatus::RequiresCapture,
amount: MinorUnit::new(200),
currency: None,
@@ -3075,7 +3089,7 @@ mod tests {
common_utils::date_time::now().saturating_sub(time::Duration::seconds(20 * 60));
let payment_intent = PaymentIntent {
payment_id: "23".to_string(),
- merchant_id: "22".to_string(),
+ merchant_id: id_type::MerchantId::default(),
status: storage_enums::IntentStatus::RequiresCapture,
amount: MinorUnit::new(200),
currency: None,
@@ -3136,7 +3150,7 @@ mod tests {
fn test_authenticate_client_secret_expired() {
let payment_intent = PaymentIntent {
payment_id: "23".to_string(),
- merchant_id: "22".to_string(),
+ merchant_id: id_type::MerchantId::default(),
status: storage_enums::IntentStatus::RequiresCapture,
amount: MinorUnit::new(200),
currency: None,
@@ -3199,7 +3213,7 @@ mod tests {
#[instrument(skip_all)]
pub async fn insert_merchant_connector_creds_to_config(
db: &dyn StorageInterface,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
merchant_connector_details: admin::MerchantConnectorDetailsWrap,
) -> RouterResult<()> {
if let Some(encoded_data) = merchant_connector_details.encoded_data {
@@ -3208,10 +3222,8 @@ pub async fn insert_merchant_connector_creds_to_config(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
- let key = format!(
- "mcd_{merchant_id}_{}",
- merchant_connector_details.creds_identifier
- );
+ let key =
+ merchant_id.get_creds_identifier_key(&merchant_connector_details.creds_identifier);
redis
.serialize_and_set_key_with_expiry(
@@ -3306,7 +3318,7 @@ impl MerchantConnectorAccountType {
#[instrument(skip_all)]
pub async fn get_merchant_connector_account(
state: &SessionState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
creds_identifier: Option<String>,
key_store: &domain::MerchantKeyStore,
profile_id: &String,
@@ -3317,31 +3329,32 @@ pub async fn get_merchant_connector_account(
let key_manager_state = &state.into();
match creds_identifier {
Some(creds_identifier) => {
- let key = format!("mcd_{merchant_id}_{creds_identifier}");
+ let key = merchant_id.get_creds_identifier_key(&creds_identifier);
+ let cloned_key = key.clone();
let redis_fetch = || async {
db.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")
.async_and_then(|redis| async move {
redis
- .get_and_deserialize_key(key.as_str(), "String")
+ .get_and_deserialize_key(key.clone().as_str(), "String")
.await
.change_context(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: key.clone(),
},
)
- .attach_printable(key + ": Not found in Redis")
+ .attach_printable(key.clone() + ": Not found in Redis")
})
.await
};
let db_fetch = || async {
- db.find_config_by_key(format!("mcd_{merchant_id}_{creds_identifier}").as_str())
+ db.find_config_by_key(cloned_key.as_str())
.await
.to_not_found_response(
errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
- id: format!("mcd_{merchant_id}_{creds_identifier}"),
+ id: cloned_key.to_owned(),
},
)
};
@@ -3494,7 +3507,10 @@ pub fn get_attempt_type(
metrics::MANUAL_RETRY_REQUEST_COUNT.add(
&metrics::CONTEXT,
1,
- &add_attributes([("merchant_id", payment_attempt.merchant_id.clone())]),
+ &add_attributes([(
+ "merchant_id",
+ payment_attempt.merchant_id.get_string_repr().to_owned(),
+ )]),
);
match payment_attempt.status {
enums::AttemptStatus::Started
@@ -3518,7 +3534,10 @@ pub fn get_attempt_type(
metrics::MANUAL_RETRY_VALIDATION_FAILED.add(
&metrics::CONTEXT,
1,
- &add_attributes([("merchant_id", payment_attempt.merchant_id.clone())]),
+ &add_attributes([(
+ "merchant_id",
+ payment_attempt.merchant_id.get_string_repr().to_owned(),
+ )]),
);
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment Attempt unexpected state")
@@ -3530,7 +3549,10 @@ pub fn get_attempt_type(
metrics::MANUAL_RETRY_VALIDATION_FAILED.add(
&metrics::CONTEXT,
1,
- &add_attributes([("merchant_id", payment_attempt.merchant_id.clone())]),
+ &add_attributes([(
+ "merchant_id",
+ payment_attempt.merchant_id.get_string_repr().to_owned(),
+ )]),
);
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
message:
@@ -3545,7 +3567,10 @@ pub fn get_attempt_type(
metrics::MANUAL_RETRY_COUNT.add(
&metrics::CONTEXT,
1,
- &add_attributes([("merchant_id", payment_attempt.merchant_id.clone())]),
+ &add_attributes([(
+ "merchant_id",
+ payment_attempt.merchant_id.get_string_repr().to_owned(),
+ )]),
);
Ok(AttemptType::New)
}
@@ -3751,7 +3776,7 @@ pub fn is_manual_retry_allowed(
intent_status: &storage_enums::IntentStatus,
attempt_status: &storage_enums::AttemptStatus,
connector_request_reference_id_config: &ConnectorRequestReferenceIdConfig,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> Option<bool> {
let is_payment_status_eligible_for_retry = match intent_status {
enums::IntentStatus::Failed => match attempt_status {
@@ -4201,7 +4226,7 @@ where
let merchant_connector_account_type = get_merchant_connector_account(
state,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
payment_data.creds_identifier.to_owned(),
key_store,
profile_id,
@@ -4221,7 +4246,7 @@ where
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
false,
key_store,
)
@@ -5002,7 +5027,10 @@ pub async fn get_payment_external_authentication_flow_during_confirm<F: Clone>(
})
}
-pub fn get_redis_key_for_extended_card_info(merchant_id: &str, payment_id: &str) -> String {
+pub fn get_redis_key_for_extended_card_info(
+ merchant_id: &id_type::MerchantId,
+ payment_id: &str,
+) -> String {
format!("{merchant_id}_{payment_id}_extended_card_info")
}
@@ -5037,11 +5065,11 @@ where
pub async fn config_skip_saving_wallet_at_connector(
db: &dyn StorageInterface,
- merchant_id: &String,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<Option<Vec<storage_enums::PaymentMethodType>>, errors::ApiErrorResponse> {
let config = db
.find_config_by_key_unwrap_or(
- format!("skip_saving_wallet_at_connector_{}", merchant_id).as_str(),
+ &merchant_id.get_skip_saving_wallet_at_connector_key(),
Some("[]".to_string()),
)
.await;
@@ -5084,7 +5112,7 @@ pub async fn validate_merchant_connector_ids_in_connector_mandate_details(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
connector_mandate_details: &api_models::payment_methods::PaymentsMandateReference,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
card_network: Option<api_enums::CardNetwork>,
) -> CustomResult<(), errors::ApiErrorResponse> {
let db = &*state.store;
diff --git a/crates/router/src/core/payments/operations.rs b/crates/router/src/core/payments/operations.rs
index 70cc77aa536..336755c6e3d 100644
--- a/crates/router/src/core/payments/operations.rs
+++ b/crates/router/src/core/payments/operations.rs
@@ -72,8 +72,8 @@ pub trait Operation<F: Clone, T>: Send + std::fmt::Debug {
}
#[derive(Clone)]
-pub struct ValidateResult<'a> {
- pub merchant_id: &'a str,
+pub struct ValidateResult {
+ pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: api::PaymentIdType,
pub storage_scheme: enums::MerchantStorageScheme,
pub requeue: bool,
@@ -81,11 +81,11 @@ pub struct ValidateResult<'a> {
#[allow(clippy::type_complexity)]
pub trait ValidateRequest<F, R> {
- fn validate_request<'a, 'b>(
+ fn validate_request<'b>(
&'b self,
request: &R,
- merchant_account: &'a domain::MerchantAccount,
- ) -> RouterResult<(BoxedOperation<'b, F, R>, ValidateResult<'a>)>;
+ merchant_account: &domain::MerchantAccount,
+ ) -> RouterResult<(BoxedOperation<'b, F, R>, ValidateResult)>;
}
pub struct GetTrackerResponse<'a, F: Clone, R> {
diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rs
index 5b18512fe20..3cbcc0bb831 100644
--- a/crates/router/src/core/payments/operations/payment_approve.rs
+++ b/crates/router/src/core/payments/operations/payment_approve.rs
@@ -43,7 +43,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest>
_payment_confirm_source: Option<common_enums::PaymentSource>,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest>> {
let db = &*state.store;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let storage_scheme = merchant_account.storage_scheme;
let (mut payment_intent, payment_attempt, currency, amount);
@@ -131,11 +131,11 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCaptureRequest>
payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id);
let frm_response = db
- .find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.merchant_id.clone())
+ .find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone())
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
- format!("Error while retrieving frm_response, merchant_id: {}, payment_id: {attempt_id}", &merchant_account.merchant_id)
+ format!("Error while retrieving frm_response, merchant_id: {}, payment_id: {attempt_id}", merchant_account.get_id().get_string_repr())
});
let payment_data = PaymentData {
@@ -261,10 +261,10 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCaptureRequest> for Paymen
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsCaptureRequest>,
- operations::ValidateResult<'a>,
+ operations::ValidateResult,
)> {
- let request_merchant_id = request.merchant_id.as_deref();
- helpers::validate_merchant_id(&merchant_account.merchant_id, request_merchant_id)
+ let request_merchant_id = request.merchant_id.as_ref();
+ helpers::validate_merchant_id(merchant_account.get_id(), request_merchant_id)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
@@ -273,7 +273,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCaptureRequest> for Paymen
Ok((
Box::new(self),
operations::ValidateResult {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(crate::core::utils::validate_id(
request.payment_id.clone(),
"payment_id",
diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rs
index a8a2756a58d..4e771659a8a 100644
--- a/crates/router/src/core/payments/operations/payment_cancel.rs
+++ b/crates/router/src/core/payments/operations/payment_cancel.rs
@@ -43,7 +43,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
_payment_confirm_source: Option<common_enums::PaymentSource>,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCancelRequest>> {
let db = &*state.store;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let storage_scheme = merchant_account.storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
@@ -129,7 +129,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsCancelRequest>
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
db,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
mcd,
)
.await
@@ -288,12 +288,12 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCancelRequest> for Payment
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsCancelRequest>,
- operations::ValidateResult<'a>,
+ operations::ValidateResult,
)> {
Ok((
Box::new(self),
operations::ValidateResult {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_account.storage_scheme,
requeue: false,
diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rs
index 03a3d031e1a..cc942016225 100644
--- a/crates/router/src/core/payments/operations/payment_capture.rs
+++ b/crates/router/src/core/payments/operations/payment_capture.rs
@@ -44,7 +44,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu
_payment_confirm_source: Option<common_enums::PaymentSource>,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsCaptureRequest>> {
let db = &*state.store;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let storage_scheme = merchant_account.storage_scheme;
let (payment_intent, mut payment_attempt, currency, amount);
@@ -175,7 +175,7 @@ impl<F: Send + Clone> GetTracker<F, payments::PaymentData<F>, api::PaymentsCaptu
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
db,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
mcd,
)
.await
@@ -323,12 +323,12 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsCaptureRequest> for Paymen
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsCaptureRequest>,
- operations::ValidateResult<'a>,
+ operations::ValidateResult,
)> {
Ok((
Box::new(self),
operations::ValidateResult {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_account.storage_scheme,
requeue: false,
diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
index c6875392750..664a7c9bb03 100644
--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs
+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs
@@ -45,7 +45,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co
_payment_confirm_source: Option<common_enums::PaymentSource>,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest>> {
let db = &*state.store;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let storage_scheme = merchant_account.storage_scheme;
let (mut payment_intent, mut payment_attempt, currency, amount);
@@ -203,7 +203,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Co
state,
request.shipping.as_ref(),
payment_intent.shipping_address_id.clone().as_deref(),
- merchant_id.as_ref(),
+ merchant_id,
payment_intent.customer_id.as_ref(),
key_store,
payment_id.as_ref(),
@@ -500,15 +500,15 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for CompleteAutho
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRequest>,
- operations::ValidateResult<'a>,
+ operations::ValidateResult,
)> {
let payment_id = request
.payment_id
.clone()
.ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?;
- let request_merchant_id = request.merchant_id.as_deref();
- helpers::validate_merchant_id(&merchant_account.merchant_id, request_merchant_id)
+ let request_merchant_id = request.merchant_id.as_ref();
+ helpers::validate_merchant_id(merchant_account.get_id(), request_merchant_id)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
@@ -528,7 +528,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for CompleteAutho
Ok((
Box::new(self),
operations::ValidateResult {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
payment_id: payment_id.and_then(|id| core_utils::validate_id(id, "payment_id"))?,
storage_scheme: merchant_account.storage_scheme,
requeue: matches!(
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index ad3f8fb013e..52d76289d88 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -61,7 +61,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
auth_flow: services::AuthFlow,
payment_confirm_source: Option<common_enums::PaymentSource>,
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest>> {
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let storage_scheme = merchant_account.storage_scheme;
let (currency, amount);
@@ -78,7 +78,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&payment_id,
- m_merchant_id.as_str(),
+ &m_merchant_id,
key_store,
storage_scheme,
)
@@ -168,7 +168,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
m_payment_id.as_str(),
- m_merchant_id.as_str(),
+ &m_merchant_id,
attempt_id.as_str(),
storage_scheme,
)
@@ -193,7 +193,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
&session_state,
m_request_shipping.as_ref(),
m_payment_intent_shipping_address_id.as_deref(),
- m_merchant_id.as_str(),
+ &m_merchant_id,
m_payment_intent_customer_id
.as_ref()
.or(m_customer_details_customer_id.as_ref()),
@@ -221,7 +221,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
&session_state,
m_request_billing.as_ref(),
m_payment_intent_billing_address_id.as_deref(),
- m_merchant_id.as_ref(),
+ &m_merchant_id,
m_payment_intent_customer_id
.as_ref()
.or(m_customer_details_customer_id.as_ref()),
@@ -244,7 +244,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
store.as_ref(),
- m_merchant_id.as_str(),
+ &m_merchant_id,
mcd,
)
.await
@@ -489,7 +489,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
&session_state,
n_request_payment_method_billing_address.as_ref(),
n_payment_method_billing_address_id.as_deref(),
- m_merchant_id.as_str(),
+ &m_merchant_id,
m_payment_intent_customer_id
.as_ref()
.or(m_customer_details_customer_id.as_ref()),
@@ -1390,7 +1390,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRequest>,
- operations::ValidateResult<'a>,
+ operations::ValidateResult,
)> {
helpers::validate_customer_information(request)?;
@@ -1398,8 +1398,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir
helpers::validate_max_amount(amount)?;
}
- let request_merchant_id = request.merchant_id.as_deref();
- helpers::validate_merchant_id(&merchant_account.merchant_id, request_merchant_id)
+ let request_merchant_id = request.merchant_id.as_ref();
+ helpers::validate_merchant_id(merchant_account.get_id(), request_merchant_id)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
@@ -1434,7 +1434,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentConfir
Ok((
Box::new(self),
operations::ValidateResult {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
payment_id: payment_id.and_then(|id| core_utils::validate_id(id, "payment_id"))?,
storage_scheme: merchant_account.storage_scheme,
requeue: matches!(
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index c3fc3adcb2a..b7f86b6838a 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -70,7 +70,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest>> {
let db = &*state.store;
let ephemeral_key = Self::get_ephemeral_key(request, state, merchant_account).await;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let storage_scheme = merchant_account.storage_scheme;
let (payment_intent, payment_attempt);
@@ -236,7 +236,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
create_payment_link(
request,
payment_link_config,
- merchant_id.clone(),
+ merchant_id,
payment_id.clone(),
db,
amount,
@@ -392,7 +392,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
db,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
mcd,
)
.await
@@ -697,7 +697,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRequest>,
- operations::ValidateResult<'a>,
+ operations::ValidateResult,
)> {
helpers::validate_customer_information(request)?;
@@ -718,8 +718,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate
errors::ApiErrorResponse::PaymentNotFound
))?;
- let request_merchant_id = request.merchant_id.as_deref();
- helpers::validate_merchant_id(&merchant_account.merchant_id, request_merchant_id)
+ let request_merchant_id = request.merchant_id.as_ref();
+ helpers::validate_merchant_id(merchant_account.get_id(), request_merchant_id)
.change_context(errors::ApiErrorResponse::MerchantAccountNotFound)?;
helpers::validate_request_amount_and_amount_to_capture(
@@ -782,7 +782,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentCreate
Ok((
Box::new(self),
operations::ValidateResult {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
payment_id,
storage_scheme: merchant_account.storage_scheme,
requeue: matches!(
@@ -799,7 +799,7 @@ impl PaymentCreate {
#[allow(clippy::too_many_arguments)]
pub async fn make_payment_attempt(
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
money: (api::Amount, enums::Currency),
payment_method: Option<enums::PaymentMethod>,
payment_method_type: Option<enums::PaymentMethodType>,
@@ -924,7 +924,7 @@ impl PaymentCreate {
Ok((
storage::PaymentAttemptNew {
payment_id: payment_id.to_string(),
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
attempt_id,
status,
currency,
@@ -1116,7 +1116,7 @@ impl PaymentCreate {
Ok(storage::PaymentIntent {
payment_id: payment_id.to_string(),
- merchant_id: merchant_account.merchant_id.to_string(),
+ merchant_id: merchant_account.get_id().to_owned(),
status,
amount: MinorUnit::from(amount),
currency,
@@ -1178,7 +1178,7 @@ impl PaymentCreate {
Some(customer_id) => helpers::make_ephemeral_key(
state.clone(),
customer_id.clone(),
- merchant_account.merchant_id.clone(),
+ merchant_account.get_id().to_owned().clone(),
)
.await
.ok()
@@ -1207,7 +1207,7 @@ pub fn payments_create_request_validation(
async fn create_payment_link(
request: &api::PaymentsRequest,
payment_link_config: api_models::admin::PaymentLinkConfig,
- merchant_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: String,
db: &dyn StorageInterface,
amount: api::Amount,
@@ -1221,7 +1221,7 @@ async fn create_payment_link(
let payment_link = format!(
"{}/payment_link/{}/{}",
domain_name,
- merchant_id.clone(),
+ merchant_id.get_string_repr(),
payment_id.clone()
);
diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rs
index a83079a6a43..4e46791c8e1 100644
--- a/crates/router/src/core/payments/operations/payment_reject.rs
+++ b/crates/router/src/core/payments/operations/payment_reject.rs
@@ -40,7 +40,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P
_payment_confirm_source: Option<common_enums::PaymentSource>,
) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsCancelRequest>> {
let db = &*state.store;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let storage_scheme = merchant_account.storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
@@ -113,11 +113,11 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, PaymentsCancelRequest> for P
let amount = payment_attempt.get_total_amount().into();
let frm_response = db
- .find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.merchant_id.clone())
+ .find_fraud_check_by_payment_id(payment_intent.payment_id.clone(), merchant_account.get_id().clone())
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
- format!("Error while retrieving frm_response, merchant_id: {}, payment_id: {attempt_id}", &merchant_account.merchant_id)
+ format!("Error while retrieving frm_response, merchant_id: {}, payment_id: {attempt_id}", merchant_account.get_id())
});
let profile_id = payment_intent
@@ -266,12 +266,12 @@ impl<F: Send + Clone> ValidateRequest<F, PaymentsCancelRequest> for PaymentRejec
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, PaymentsCancelRequest>,
- operations::ValidateResult<'a>,
+ operations::ValidateResult,
)> {
Ok((
Box::new(self),
operations::ValidateResult {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
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 808b2ae6181..a9449e38d2e 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -1335,7 +1335,7 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
async move {
mandate::update_connector_mandate_id(
m_db.as_ref(),
- m_router_data_merchant_id.clone(),
+ &m_router_data_merchant_id,
m_payment_data_mandate_id,
m_payment_method_id,
m_router_data_response,
@@ -1372,7 +1372,14 @@ async fn payment_response_update_tracker<F: Clone, T: types::Capturable>(
"connector",
payment_data.payment_attempt.connector.unwrap_or_default(),
),
- ("merchant_id", payment_data.payment_attempt.merchant_id),
+ (
+ "merchant_id",
+ payment_data
+ .payment_attempt
+ .merchant_id
+ .get_string_repr()
+ .to_owned(),
+ ),
]),
);
Err(error_stack::Report::new(
diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rs
index 00f599d4095..e65fcbc390b 100644
--- a/crates/router/src/core/payments/operations/payment_session.rs
+++ b/crates/router/src/core/payments/operations/payment_session.rs
@@ -47,7 +47,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let db = &*state.store;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let storage_scheme = merchant_account.storage_scheme;
let mut payment_intent = db
@@ -139,7 +139,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest>
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
db,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
mcd,
)
.await
@@ -270,7 +270,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsSessionRequest> for Paymen
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsSessionRequest>,
- operations::ValidateResult<'a>,
+ operations::ValidateResult,
)> {
//paymentid is already generated and should be sent in the request
let given_payment_id = request.payment_id.clone();
@@ -278,7 +278,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsSessionRequest> for Paymen
Ok((
Box::new(self),
operations::ValidateResult {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id),
storage_scheme: merchant_account.storage_scheme,
requeue: false,
@@ -360,7 +360,7 @@ where
let all_connector_accounts = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
false,
key_store,
)
diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rs
index 98befe122cc..0172b5f2644 100644
--- a/crates/router/src/core/payments/operations/payment_start.rs
+++ b/crates/router/src/core/payments/operations/payment_start.rs
@@ -42,7 +42,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsStartRequest> f
let (mut payment_intent, payment_attempt, currency, amount);
let db = &*state.store;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let storage_scheme = merchant_account.storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
@@ -236,10 +236,10 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsStartRequest> for PaymentS
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsStartRequest>,
- operations::ValidateResult<'a>,
+ operations::ValidateResult,
)> {
- let request_merchant_id = Some(&request.merchant_id[..]);
- helpers::validate_merchant_id(&merchant_account.merchant_id, request_merchant_id)
+ let request_merchant_id = Some(&request.merchant_id);
+ helpers::validate_merchant_id(merchant_account.get_id(), request_merchant_id)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
@@ -250,7 +250,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsStartRequest> for PaymentS
Ok((
Box::new(self),
operations::ValidateResult {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(payment_id),
storage_scheme: merchant_account.storage_scheme,
requeue: false,
diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rs
index fff096d9b4c..a7ba54a377d 100644
--- a/crates/router/src/core/payments/operations/payment_status.rs
+++ b/crates/router/src/core/payments/operations/payment_status.rs
@@ -223,7 +223,7 @@ async fn get_tracker_for_sync<
(payment_intent, payment_attempt) = get_payment_intent_payment_attempt(
state,
payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
key_store,
storage_scheme,
)
@@ -241,7 +241,7 @@ async fn get_tracker_for_sync<
payment_intent.shipping_address_id.clone(),
key_store,
&payment_intent.payment_id.clone(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await?;
@@ -250,7 +250,7 @@ async fn get_tracker_for_sync<
payment_intent.billing_address_id.clone(),
key_store,
&payment_intent.payment_id.clone(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await?;
@@ -260,7 +260,7 @@ async fn get_tracker_for_sync<
payment_attempt.payment_method_billing_address_id.clone(),
key_store,
&payment_intent.payment_id.clone(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await?;
@@ -270,11 +270,11 @@ async fn get_tracker_for_sync<
let attempts = match request.expand_attempts {
Some(true) => {
Some(db
- .find_attempts_by_merchant_id_payment_id(&merchant_account.merchant_id, &payment_id_str, storage_scheme)
+ .find_attempts_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id_str, storage_scheme)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
- format!("Error while retrieving attempt list for, merchant_id: {}, payment_id: {payment_id_str}",&merchant_account.merchant_id)
+ format!("Error while retrieving attempt list for, merchant_id: {:?}, payment_id: {payment_id_str}",merchant_account.get_id())
})?)
},
_ => None,
@@ -291,7 +291,7 @@ async fn get_tracker_for_sync<
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
- format!("Error while retrieving capture list for, merchant_id: {}, payment_id: {payment_id_str}", merchant_account.merchant_id)
+ format!("Error while retrieving capture list for, merchant_id: {:?}, payment_id: {payment_id_str}", merchant_account.get_id())
})?;
Some(payment_types::MultipleCaptureData::new_for_sync(
captures,
@@ -304,46 +304,48 @@ async fn get_tracker_for_sync<
let refunds = db
.find_refund_by_payment_id_merchant_id(
&payment_id_str,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!(
- "Failed while getting refund list for, payment_id: {}, merchant_id: {}",
- &payment_id_str, merchant_account.merchant_id
+ "Failed while getting refund list for, payment_id: {}, merchant_id: {:?}",
+ &payment_id_str,
+ merchant_account.get_id()
)
})?;
let authorizations = db
.find_all_authorizations_by_merchant_id_payment_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&payment_id_str,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
format!(
- "Failed while getting authorizations list for, payment_id: {}, merchant_id: {}",
- &payment_id_str, merchant_account.merchant_id
+ "Failed while getting authorizations list for, payment_id: {}, merchant_id: {:?}",
+ &payment_id_str,
+ merchant_account.get_id()
)
})?;
let disputes = db
- .find_disputes_by_merchant_id_payment_id(&merchant_account.merchant_id, &payment_id_str)
+ .find_disputes_by_merchant_id_payment_id(merchant_account.get_id(), &payment_id_str)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
- format!("Error while retrieving dispute list for, merchant_id: {}, payment_id: {payment_id_str}", &merchant_account.merchant_id)
+ format!("Error while retrieving dispute list for, merchant_id: {:?}, payment_id: {payment_id_str}", merchant_account.get_id())
})?;
let frm_response = db
- .find_fraud_check_by_payment_id(payment_id_str.to_string(), merchant_account.merchant_id.clone())
+ .find_fraud_check_by_payment_id(payment_id_str.to_string(), merchant_account.get_id().clone())
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
.attach_printable_lazy(|| {
- format!("Error while retrieving frm_response, merchant_id: {}, payment_id: {payment_id_str}", &merchant_account.merchant_id)
+ format!("Error while retrieving frm_response, merchant_id: {:?}, payment_id: {payment_id_str}", merchant_account.get_id())
});
let contains_encoded_data = payment_attempt.encoded_data.is_some();
@@ -356,12 +358,8 @@ async fn get_tracker_for_sync<
.merchant_connector_details
.to_owned()
.async_map(|mcd| async {
- helpers::insert_merchant_connector_creds_to_config(
- db,
- &merchant_account.merchant_id,
- mcd,
- )
- .await
+ helpers::insert_merchant_connector_creds_to_config(db, merchant_account.get_id(), mcd)
+ .await
})
.await
.transpose()?;
@@ -405,7 +403,7 @@ async fn get_tracker_for_sync<
let merchant_id = payment_intent.merchant_id.clone();
let authentication = payment_attempt.authentication_id.clone().async_map(|authentication_id| async move {
db.find_authentication_by_merchant_id_authentication_id(
- merchant_id,
+ &merchant_id,
authentication_id.clone(),
)
.await
@@ -481,16 +479,16 @@ async fn get_tracker_for_sync<
}
impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRetrieveRequest> for PaymentStatus {
- fn validate_request<'a, 'b>(
+ fn validate_request<'b>(
&'b self,
request: &api::PaymentsRetrieveRequest,
- merchant_account: &'a domain::MerchantAccount,
+ merchant_account: &domain::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRetrieveRequest>,
- operations::ValidateResult<'a>,
+ operations::ValidateResult,
)> {
- let request_merchant_id = request.merchant_id.as_deref();
- helpers::validate_merchant_id(&merchant_account.merchant_id, request_merchant_id)
+ let request_merchant_id = request.merchant_id.as_ref();
+ helpers::validate_merchant_id(merchant_account.get_id(), request_merchant_id)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
@@ -499,7 +497,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRetrieveRequest> for Payme
Ok((
Box::new(self),
operations::ValidateResult {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
payment_id: request.resource_id.clone(),
storage_scheme: merchant_account.storage_scheme,
requeue: false,
@@ -511,7 +509,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRetrieveRequest> for Payme
pub async fn get_payment_intent_payment_attempt(
state: &SessionState,
payment_id: &api::PaymentIdType,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<(storage::PaymentIntent, storage::PaymentAttempt)> {
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index d7fcdf6e14b..3a5cd00b9c3 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -57,7 +57,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
let payment_id = payment_id
.get_payment_intent_id()
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let storage_scheme = merchant_account.storage_scheme;
let db = &*state.store;
@@ -393,7 +393,7 @@ impl<F: Send + Clone> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for Pa
.async_map(|mcd| async {
helpers::insert_merchant_connector_creds_to_config(
db,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
mcd,
)
.await
@@ -806,7 +806,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, api::PaymentsRequest>,
- operations::ValidateResult<'a>,
+ operations::ValidateResult,
)> {
helpers::validate_customer_information(request)?;
@@ -821,8 +821,8 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate
.clone()
.ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?;
- let request_merchant_id = request.merchant_id.as_deref();
- helpers::validate_merchant_id(&merchant_account.merchant_id, request_merchant_id)
+ let request_merchant_id = request.merchant_id.as_ref();
+ helpers::validate_merchant_id(merchant_account.get_id(), request_merchant_id)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string(),
@@ -861,7 +861,7 @@ impl<F: Send + Clone> ValidateRequest<F, api::PaymentsRequest> for PaymentUpdate
Ok((
Box::new(self),
operations::ValidateResult {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
payment_id: payment_id.and_then(|id| core_utils::validate_id(id, "payment_id"))?,
storage_scheme: merchant_account.storage_scheme,
requeue: matches!(
diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
index 20c2e051b61..c7311059ba2 100644
--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs
@@ -48,7 +48,7 @@ impl<F: Send + Clone>
) -> RouterResult<operations::GetTrackerResponse<'a, F, PaymentsIncrementalAuthorizationRequest>>
{
let db = &*state.store;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let storage_scheme = merchant_account.storage_scheme;
let payment_id = payment_id
.get_payment_intent_id()
@@ -273,12 +273,12 @@ impl<F: Send + Clone> ValidateRequest<F, PaymentsIncrementalAuthorizationRequest
merchant_account: &'a domain::MerchantAccount,
) -> RouterResult<(
BoxedOperation<'b, F, PaymentsIncrementalAuthorizationRequest>,
- operations::ValidateResult<'a>,
+ operations::ValidateResult,
)> {
Ok((
Box::new(self),
operations::ValidateResult {
- merchant_id: &merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
payment_id: api::PaymentIdType::PaymentIntentId(request.payment_id.to_owned()),
storage_scheme: merchant_account.storage_scheme,
requeue: false,
diff --git a/crates/router/src/core/payments/retry.rs b/crates/router/src/core/payments/retry.rs
index 99cb6aaec68..29512c21391 100644
--- a/crates/router/src/core/payments/retry.rs
+++ b/crates/router/src/core/payments/retry.rs
@@ -41,7 +41,7 @@ pub async fn do_gsm_actions<F, ApiRequest, FData>(
key_store: &domain::MerchantKeyStore,
operation: &operations::BoxedOperation<'_, F, ApiRequest>,
customer: &Option<domain::Customer>,
- validate_result: &operations::ValidateResult<'_>,
+ validate_result: &operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &storage::business_profile::BusinessProfile,
@@ -73,7 +73,7 @@ where
let should_step_up = if step_up_possible && is_no_three_ds_payment {
is_step_up_enabled_for_merchant_connector(
state,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
original_connector_data.connector_name,
)
.await
@@ -111,7 +111,7 @@ where
match get_gsm_decision(gsm) {
api_models::gsm::GsmDecision::Retry => {
- retries = get_retries(state, retries, &merchant_account.merchant_id).await;
+ retries = get_retries(state, retries, merchant_account.get_id()).await;
if retries.is_none() || retries == Some(0) {
metrics::AUTO_RETRY_EXHAUSTED_COUNT.add(&metrics::CONTEXT, 1, &[]);
@@ -166,10 +166,10 @@ where
#[instrument(skip_all)]
pub async fn is_step_up_enabled_for_merchant_connector(
state: &app::SessionState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_name: types::Connector,
) -> bool {
- let key = format!("step_up_enabled_{merchant_id}");
+ let key = merchant_id.get_step_up_enabled_key();
let db = &*state.store;
db.find_config_by_key_unwrap_or(key.as_str(), Some("[]".to_string()))
.await
@@ -191,12 +191,13 @@ pub async fn is_step_up_enabled_for_merchant_connector(
pub async fn get_retries(
state: &app::SessionState,
retries: Option<i32>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> Option<i32> {
match retries {
Some(retries) => Some(retries),
None => {
- let key = format!("max_auto_retries_enabled_{merchant_id}");
+ let key = merchant_id.get_max_auto_retries_enabled();
+
let db = &*state.store;
db.find_config_by_key(key.as_str())
.await
@@ -278,7 +279,7 @@ pub async fn do_retry<F, ApiRequest, FData>(
key_store: &domain::MerchantKeyStore,
payment_data: &mut payments::PaymentData<F>,
router_data: types::RouterData<F, FData, types::PaymentsResponseData>,
- validate_result: &operations::ValidateResult<'_>,
+ validate_result: &operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
is_step_up: bool,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
@@ -534,10 +535,13 @@ pub fn make_new_payment_attempt(
}
}
-pub async fn config_should_call_gsm(db: &dyn StorageInterface, merchant_id: &String) -> bool {
+pub async fn config_should_call_gsm(
+ db: &dyn StorageInterface,
+ merchant_id: &common_utils::id_type::MerchantId,
+) -> bool {
let config = db
.find_config_by_key_unwrap_or(
- format!("should_call_gsm_{}", merchant_id).as_str(),
+ &merchant_id.get_should_call_gsm_key(),
Some("false".to_string()),
)
.await;
diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rs
index ff9f6ddbf3a..151192fb8b7 100644
--- a/crates/router/src/core/payments/routing.rs
+++ b/crates/router/src/core/payments/routing.rs
@@ -252,7 +252,7 @@ where
pub async fn perform_static_routing_v1<F: Clone>(
state: &SessionState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
algorithm_ref: routing_types::RoutingAlgorithmRef,
transaction_data: &routing::TransactionData<'_, F>,
) -> RoutingResult<Vec<routing_types::RoutableConnectorChoice>> {
@@ -312,7 +312,7 @@ pub async fn perform_static_routing_v1<F: Clone>(
async fn ensure_algorithm_cached_v1(
state: &SessionState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
algorithm_id: &str,
profile_id: Option<String>,
transaction_type: &api_enums::TransactionType,
@@ -324,12 +324,18 @@ async fn ensure_algorithm_cached_v1(
.change_context(errors::RoutingError::ProfileIdMissing)?;
match transaction_type {
- api_enums::TransactionType::Payment => {
- format!("routing_config_{merchant_id}_{profile_id}")
+ common_enums::TransactionType::Payment => {
+ format!(
+ "routing_config_{}_{profile_id}",
+ merchant_id.get_string_repr()
+ )
}
#[cfg(feature = "payouts")]
- api_enums::TransactionType::Payout => {
- format!("routing_config_po_{merchant_id}_{profile_id}")
+ common_enums::TransactionType::Payout => {
+ format!(
+ "routing_config_po_{}_{profile_id}",
+ merchant_id.get_string_repr()
+ )
}
}
};
@@ -492,10 +498,12 @@ pub async fn get_merchant_cgraph<'a>(
.get_required_value("profile_id")
.change_context(errors::RoutingError::ProfileIdMissing)?;
match transaction_type {
- api_enums::TransactionType::Payment => format!("cgraph_{}_{}", merchant_id, profile_id),
+ api_enums::TransactionType::Payment => {
+ format!("cgraph_{}_{}", merchant_id.get_string_repr(), profile_id)
+ }
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => {
- format!("cgraph_po_{}_{}", merchant_id, profile_id)
+ format!("cgraph_po_{}_{}", merchant_id.get_string_repr(), profile_id)
}
}
};
diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rs
index 40163367139..144c7e87e2b 100644
--- a/crates/router/src/core/payments/tokenization.rs
+++ b/crates/router/src/core/payments/tokenization.rs
@@ -189,7 +189,7 @@ where
)
.await?;
let customer_id = customer_id.to_owned().get_required_value("customer_id")?;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let (mut resp, duplication_check) = if !state.conf.locker.locker_enabled {
skip_saving_card_in_locker(
merchant_account,
@@ -411,7 +411,7 @@ where
&resp,
&payment_method_create_request.clone(),
key_store,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&customer_id,
resp.metadata.clone().map(|val| val.expose()),
customer_acceptance,
@@ -641,7 +641,7 @@ async fn skip_saving_card_in_locker(
api_models::payment_methods::PaymentMethodResponse,
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let customer_id = payment_method_request
.clone()
.customer_id
@@ -679,7 +679,7 @@ async fn skip_saving_card_in_locker(
saved_to_locker: false,
};
let pm_resp = api::PaymentMethodResponse {
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
customer_id: Some(customer_id),
payment_method_id,
payment_method: payment_method_request.payment_method,
@@ -701,7 +701,7 @@ async fn skip_saving_card_in_locker(
None => {
let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
customer_id: Some(customer_id),
payment_method_id: pm_id,
payment_method: payment_method_request.payment_method,
@@ -731,7 +731,7 @@ pub async fn save_in_locker(
Option<payment_methods::transformers::DataDuplicationCheck>,
)> {
payment_method_request.validate()?;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let customer_id = payment_method_request
.customer_id
.clone()
@@ -751,7 +751,7 @@ pub async fn save_in_locker(
None => {
let pm_id = common_utils::generate_id(consts::ID_LENGTH, "pm");
let payment_method_response = api::PaymentMethodResponse {
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.clone(),
customer_id: Some(customer_id),
payment_method_id: pm_id,
payment_method: payment_method_request.payment_method,
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index 4df48806530..f28dd10fc9a 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -142,7 +142,7 @@ where
router_data = types::RouterData {
flow: PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
customer_id,
connector: connector_id.to_owned(),
payment_id: payment_data.payment_attempt.payment_id.clone(),
@@ -186,7 +186,7 @@ where
recurring_mandate_payment_data: payment_data.recurring_mandate_payment_data,
connector_request_reference_id: core_utils::get_connector_request_reference_id(
&state.conf,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&payment_data.payment_attempt,
),
preprocessing_id: payment_data.payment_attempt.preprocessing_step_id,
@@ -900,7 +900,7 @@ where
1,
&add_attributes([
("operation", format!("{:?}", operation)),
- ("merchant", merchant_id),
+ ("merchant", merchant_id.get_string_repr().to_owned()),
("payment_method_type", payment_method_type),
("payment_method", payment_method),
]),
diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rs
index 78ff9900f66..d4dd01b4ddc 100644
--- a/crates/router/src/core/payout_link.rs
+++ b/crates/router/src/core/payout_link.rs
@@ -32,7 +32,7 @@ pub async fn initiate_payout_link(
request_headers: &header::HeaderMap,
) -> RouterResponse<services::GenericLinkFormData> {
let db: &dyn StorageInterface = &*state.store;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
// Fetch payout
let payout = db
.find_payout_by_merchant_id_payout_id(
@@ -270,7 +270,7 @@ pub async fn filter_payout_methods(
let all_mcas = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
key_manager_state,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
false,
key_store,
)
diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rs
index 6db3c1edf43..3f6cfd11741 100644
--- a/crates/router/src/core/payouts.rs
+++ b/crates/router/src/core/payouts.rs
@@ -6,6 +6,8 @@ pub mod validator;
use std::vec::IntoIter;
use api_models::{self, admin, enums as api_enums, payouts::PayoutLinkResponse};
+#[cfg(feature = "payout_retry")]
+use common_enums::PayoutRetryType;
use common_utils::{
consts,
crypto::Encryptable,
@@ -178,8 +180,8 @@ pub async fn make_connector_decision(
{
let config_bool = retry::config_should_call_gsm_payout(
&*state.store,
- &merchant_account.merchant_id,
- retry::PayoutRetryType::SingleConnector,
+ merchant_account.get_id(),
+ PayoutRetryType::SingleConnector,
)
.await;
@@ -215,8 +217,8 @@ pub async fn make_connector_decision(
{
let config_multiple_connector_bool = retry::config_should_call_gsm_payout(
&*state.store,
- &merchant_account.merchant_id,
- retry::PayoutRetryType::MultiConnector,
+ merchant_account.get_id(),
+ PayoutRetryType::MultiConnector,
)
.await;
@@ -234,8 +236,8 @@ pub async fn make_connector_decision(
let config_single_connector_bool = retry::config_should_call_gsm_payout(
&*state.store,
- &merchant_account.merchant_id,
- retry::PayoutRetryType::SingleConnector,
+ merchant_account.get_id(),
+ PayoutRetryType::SingleConnector,
)
.await;
@@ -709,7 +711,7 @@ pub async fn payouts_list_core(
constraints: payouts::PayoutListConstraints,
) -> RouterResponse<payouts::PayoutListResponse> {
validator::validate_payout_list_request(&constraints)?;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let db = state.store.as_ref();
let payouts = helpers::filter_by_constraints(
db,
@@ -815,7 +817,7 @@ pub async fn payouts_filtered_list_core(
diesel_models::Customer,
)> = db
.filter_payouts_and_attempts(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&filters.clone().into(),
merchant_account.storage_scheme,
)
@@ -827,7 +829,7 @@ pub async fn payouts_filtered_list_core(
&(&state).into(),
c,
&key_store.key,
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
{
@@ -865,7 +867,7 @@ pub async fn payouts_list_available_filters_core(
let db = state.store.as_ref();
let payout = db
.filter_payouts_by_time_range_constraints(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&time_range,
merchant_account.storage_scheme,
)
@@ -875,7 +877,7 @@ pub async fn payouts_list_available_filters_core(
let filters = db
.get_filters_for_payouts(
payout.as_slice(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
storage_enums::MerchantStorageScheme::PostgresOnly,
)
.await
@@ -1081,7 +1083,7 @@ pub async fn create_recipient(
let db = &*state.store;
if let Some(customer) = customer_details {
let customer_id = customer.customer_id.to_owned();
- let merchant_id = merchant_account.merchant_id.to_owned();
+ let merchant_id = merchant_account.get_id().to_owned();
if let Some(updated_customer) =
customers::update_connector_customer_in_customers(
&connector_label,
@@ -2092,7 +2094,7 @@ pub async fn response_handler(
let response = api::PayoutCreateResponse {
payout_id: payouts.payout_id.to_owned(),
- merchant_id: merchant_account.merchant_id.to_owned(),
+ merchant_id: merchant_account.get_id().to_owned(),
amount: payouts.amount,
currency: payouts.destination_currency.to_owned(),
connector: payout_attempt.connector.to_owned(),
@@ -2146,7 +2148,7 @@ pub async fn payout_create_db_entries(
stored_payout_method_data: Option<&payouts::PayoutMethodData>,
) -> RouterResult<PayoutData> {
let db = &*state.store;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
// Get or create customer
let customer_details = payments::CustomerDetails {
@@ -2182,7 +2184,7 @@ pub async fn payout_create_db_entries(
state,
&business_profile,
&customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
req,
payout_id,
)
@@ -2240,7 +2242,7 @@ pub async fn payout_create_db_entries(
let payouts_req = storage::PayoutsNew {
payout_id: payout_id.to_string(),
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
customer_id: customer_id.to_owned(),
address_id: address_id.to_owned(),
payout_type,
@@ -2326,7 +2328,7 @@ pub async fn make_payout_data(
req: &payouts::PayoutRequest,
) -> RouterResult<PayoutData> {
let db = &*state.store;
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let payout_id = match req {
payouts::PayoutRequest::PayoutActionRequest(r) => r.payout_id.clone(),
payouts::PayoutRequest::PayoutCreateRequest(r) => r.payout_id.clone().unwrap_or_default(),
@@ -2395,7 +2397,7 @@ pub async fn make_payout_data(
None,
Some(&payout_token),
&customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
payouts.payout_type,
key_store,
None,
@@ -2471,7 +2473,7 @@ pub async fn add_external_account_addition_task(
async fn validate_and_get_business_profile(
state: &SessionState,
profile_id: &String,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<storage::BusinessProfile> {
let db = &*state.store;
if let Some(business_profile) =
@@ -2492,7 +2494,7 @@ pub async fn create_payout_link(
state: &SessionState,
business_profile: &storage::BusinessProfile,
customer_id: &CustomerId,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
req: &payouts::PayoutCreateRequest,
payout_id: &String,
) -> RouterResult<PayoutLink> {
@@ -2548,7 +2550,10 @@ pub async fn create_payout_link(
.session_expiry
.as_ref()
.map_or(default_config.expiry, |expiry| *expiry);
- let url = format!("{base_url}/payout_link/{merchant_id}/{payout_id}");
+ let url = format!(
+ "{base_url}/payout_link/{}/{payout_id}",
+ merchant_id.get_string_repr()
+ );
let link = url::Url::parse(&url)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Failed to form payout link URL - {}", url))?;
@@ -2592,7 +2597,7 @@ pub async fn create_payout_link(
pub async fn create_payout_link_db_entry(
state: &SessionState,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_link_data: &PayoutLinkData,
return_url: Option<String>,
) -> RouterResult<PayoutLink> {
@@ -2605,7 +2610,7 @@ pub async fn create_payout_link_db_entry(
let payout_link = GenericLinkNew {
link_id: payout_link_data.payout_link_id.to_string(),
primary_reference: payout_link_data.payout_id.to_string(),
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
link_type: common_enums::GenericLinkType::PayoutLink,
link_status: GenericLinkStatus::PayoutLink(PayoutLinkStatus::Initiated),
link_data,
diff --git a/crates/router/src/core/payouts/access_token.rs b/crates/router/src/core/payouts/access_token.rs
index c70f3c3667a..b7f52b259c0 100644
--- a/crates/router/src/core/payouts/access_token.rs
+++ b/crates/router/src/core/payouts/access_token.rs
@@ -61,7 +61,7 @@ pub async fn add_access_token_for_payout<F: Clone + 'static>(
.connector_name
.supports_access_token_for_payout(payout_type)
{
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let store = &*state.store;
let old_access_token = store
.get_access_token(merchant_id, connector.connector.id())
diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rs
index c3aa128f2fb..41229552ad5 100644
--- a/crates/router/src/core/payouts/helpers.rs
+++ b/crates/router/src/core/payouts/helpers.rs
@@ -50,7 +50,7 @@ pub async fn make_payout_method_data<'a>(
payout_method_data: Option<&api::PayoutMethodData>,
payout_token: Option<&str>,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payout_type: Option<api_enums::PayoutType>,
merchant_key_store: &domain::MerchantKeyStore,
payout_data: Option<&mut PayoutData>,
@@ -213,7 +213,7 @@ pub async fn save_payout_data_to_locker(
card_type: None,
};
let payload = StoreLockerReq::LockerCard(StoreCardReq {
- merchant_id: merchant_account.merchant_id.as_ref(),
+ merchant_id: merchant_account.get_id().clone(),
merchant_customer_id: payout_attempt.customer_id.to_owned(),
card: Card {
card_number: card.card_number.to_owned(),
@@ -266,7 +266,7 @@ pub async fn save_payout_data_to_locker(
Ok(hex::encode(e.peek()))
})?;
let payload = StoreLockerReq::LockerGeneric(StoreGenericReq {
- merchant_id: merchant_account.merchant_id.as_ref(),
+ merchant_id: merchant_account.get_id().to_owned(),
merchant_customer_id: payout_attempt.customer_id.to_owned(),
enc_data,
ttl: state.conf.locker.ttl_for_storage_in_secs,
@@ -506,7 +506,7 @@ pub async fn save_payout_data_to_locker(
&payout_attempt.customer_id,
&payment_method_id,
Some(stored_resp.card_reference.clone()),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
None,
None,
card_details_encrypted.clone().map(Into::into),
@@ -535,7 +535,7 @@ pub async fn save_payout_data_to_locker(
cards::delete_card_from_hs_locker(
state,
&payout_attempt.customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
card_reference,
)
.await
@@ -559,7 +559,7 @@ pub async fn save_payout_data_to_locker(
if let Err(err) = stored_resp {
logger::error!(vault_err=?err);
db.delete_payment_method_by_merchant_id_payment_method_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&existing_pm.payment_method_id,
)
.await
@@ -611,7 +611,7 @@ pub async fn get_or_create_customer_details(
.clone()
.unwrap_or_else(generate_customer_id_of_default_length);
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
let key = key_store.key.get_inner().peek();
let key_manager_state = &state.into();
@@ -646,7 +646,7 @@ pub async fn get_or_create_customer_details(
let customer = domain::Customer {
customer_id,
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned().clone(),
name: encryptable_customer.name,
email: encryptable_customer.email,
phone: encryptable_customer.phone,
@@ -964,7 +964,7 @@ pub fn is_eligible_for_local_payout_cancellation(status: api_enums::PayoutStatus
pub(super) async fn filter_by_constraints(
db: &dyn StorageInterface,
constraints: &api::PayoutListConstraints,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage::Payouts>, errors::DataStorageError> {
let result = db
diff --git a/crates/router/src/core/payouts/retry.rs b/crates/router/src/core/payouts/retry.rs
index fa61ab8a22b..284f81a1702 100644
--- a/crates/router/src/core/payouts/retry.rs
+++ b/crates/router/src/core/payouts/retry.rs
@@ -1,5 +1,6 @@
use std::{cmp::Ordering, str::FromStr, vec::IntoIter};
+use common_enums::PayoutRetryType;
use error_stack::{report, ResultExt};
use router_env::{
logger,
@@ -18,13 +19,6 @@ use crate::{
utils,
};
-#[derive(Clone, Debug, serde::Serialize)]
-#[serde(rename_all = "snake_case")]
-pub enum PayoutRetryType {
- SingleConnector,
- MultiConnector,
-}
-
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn do_gsm_multiple_connector_actions(
@@ -49,7 +43,7 @@ pub async fn do_gsm_multiple_connector_actions(
retries = get_retries(
state,
retries,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
PayoutRetryType::MultiConnector,
)
.await;
@@ -121,7 +115,7 @@ pub async fn do_gsm_single_connector_actions(
retries = get_retries(
state,
retries,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
PayoutRetryType::SingleConnector,
)
.await;
@@ -160,20 +154,13 @@ pub async fn do_gsm_single_connector_actions(
pub async fn get_retries(
state: &app::SessionState,
retries: Option<i32>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
retry_type: PayoutRetryType,
) -> Option<i32> {
match retries {
Some(retries) => Some(retries),
None => {
- let key = match retry_type {
- PayoutRetryType::SingleConnector => {
- format!("max_auto_single_connector_payout_retries_enabled_{merchant_id}")
- }
- PayoutRetryType::MultiConnector => {
- format!("max_auto_multiple_connector_payout_retries_enabled_{merchant_id}")
- }
- };
+ let key = merchant_id.get_max_auto_single_connector_payout_retries_enabled(retry_type);
let db = &*state.store;
db.find_config_by_key(key.as_str())
.await
@@ -318,17 +305,10 @@ pub async fn modify_trackers(
pub async fn config_should_call_gsm_payout(
db: &dyn StorageInterface,
- merchant_id: &String,
+ merchant_id: &common_utils::id_type::MerchantId,
retry_type: PayoutRetryType,
) -> bool {
- let key = match retry_type {
- PayoutRetryType::SingleConnector => {
- format!("should_call_gsm_single_connector_payout_{}", merchant_id)
- }
- PayoutRetryType::MultiConnector => {
- format!("should_call_gsm_multiple_connector_payout_{}", merchant_id)
- }
- };
+ let key = merchant_id.get_should_call_gsm_payout_key(retry_type);
let config = db
.find_config_by_key_unwrap_or(key.as_str(), Some("false".to_string()))
.await;
diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rs
index a1332181f6d..7d5b8c05ee2 100644
--- a/crates/router/src/core/payouts/validator.rs
+++ b/crates/router/src/core/payouts/validator.rs
@@ -26,7 +26,7 @@ use crate::{
pub async fn validate_uniqueness_of_payout_id_against_merchant_id(
db: &dyn StorageInterface,
payout_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> RouterResult<Option<storage::Payouts>> {
let maybe_payouts = db
@@ -56,7 +56,7 @@ pub async fn validate_create_request(
req: &payouts::PayoutCreateRequest,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<(String, Option<payouts::PayoutMethodData>, String)> {
- let merchant_id = &merchant_account.merchant_id;
+ let merchant_id = merchant_account.get_id();
if let Some(payout_link) = &req.payout_link {
if *payout_link {
@@ -86,7 +86,7 @@ pub async fn validate_create_request(
.await
.attach_printable_lazy(|| {
format!(
- "Unique violation while checking payout_id: {} against merchant_id: {}",
+ "Unique violation while checking payout_id: {} against merchant_id: {:?}",
payout_id.to_owned(),
merchant_id
)
@@ -109,7 +109,7 @@ pub async fn validate_create_request(
req.payout_method_data.as_ref(),
Some(&payout_token),
&customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
req.payout_type,
merchant_key_store,
None,
diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rs
index df28d257b36..f2d5d2d7d5e 100644
--- a/crates/router/src/core/pm_auth.rs
+++ b/crates/router/src/core/pm_auth.rs
@@ -125,7 +125,7 @@ pub async fn create_link_token(
pi.billing_address_id.clone(),
&key_store,
&pi.payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
@@ -140,20 +140,20 @@ pub async fn create_link_token(
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&(&state).into(),
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
&selected_config.mca_id,
&key_store,
)
.await
.change_context(ApiErrorResponse::MerchantConnectorAccountNotFound {
- id: merchant_account.merchant_id.clone(),
+ id: merchant_account.get_id().get_string_repr().to_owned(),
})?;
let auth_type = helpers::get_connector_auth_type(merchant_connector_account)?;
let router_data = pm_auth_types::LinkTokenRouterData {
flow: std::marker::PhantomData,
- merchant_id: Some(merchant_account.merchant_id),
+ merchant_id: Some(merchant_account.get_id().clone()),
connector: Some(connector_name.to_string()),
request: pm_auth_types::LinkTokenRequest {
client_name: "HyperSwitch".to_string(),
@@ -235,13 +235,13 @@ pub async fn exchange_token_core(
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&(&state).into(),
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
&config.mca_id,
&key_store,
)
.await
.change_context(ApiErrorResponse::MerchantConnectorAccountNotFound {
- id: merchant_account.merchant_id.clone(),
+ id: merchant_account.get_id().get_string_repr().to_owned(),
})?;
let auth_type = helpers::get_connector_auth_type(merchant_connector_account.clone())?;
@@ -297,7 +297,7 @@ async fn store_bank_details_in_payment_methods(
.find_payment_intent_by_payment_id_merchant_id(
&(&state).into(),
&payload.payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&key_store,
merchant_account.storage_scheme,
)
@@ -311,7 +311,7 @@ async fn store_bank_details_in_payment_methods(
let payment_methods = db
.find_payment_method_by_customer_id_merchant_id_list(
&customer_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
None,
)
.await
@@ -459,7 +459,7 @@ async fn store_bank_details_in_payment_methods(
let now = common_utils::date_time::now();
let pm_new = storage::PaymentMethodNew {
customer_id: customer_id.clone(),
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
payment_method_id: pm_id,
payment_method: Some(enums::PaymentMethod::BankDebit),
payment_method_type: Some(creds.payment_method_type),
@@ -555,7 +555,7 @@ pub async fn get_bank_account_creds(
let router_data_bank_details = pm_auth_types::BankDetailsRouterData {
flow: std::marker::PhantomData,
- merchant_id: Some(merchant_account.merchant_id.clone()),
+ merchant_id: Some(merchant_account.get_id().clone()),
connector: Some(connector_name.to_string()),
request: pm_auth_types::BankAccountCredentialsRequest {
access_token: access_token.clone(),
@@ -784,7 +784,7 @@ pub async fn retrieve_payment_method_from_auth_service(
payment_intent.billing_address_id.clone(),
key_store,
&payment_intent.payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await?;
diff --git a/crates/router/src/core/poll.rs b/crates/router/src/core/poll.rs
index 53b4b02e610..f0a464be287 100644
--- a/crates/router/src/core/poll.rs
+++ b/crates/router/src/core/poll.rs
@@ -21,7 +21,7 @@ pub async fn retrieve_poll_status(
.attach_printable("Failed to get redis connection")?;
let request_poll_id = req.poll_id;
// prepend 'poll_{merchant_id}_' to restrict access to only fetching Poll IDs, as this is a freely passed string in the request
- let poll_id = super::utils::get_poll_id(merchant_account.merchant_id, request_poll_id.clone());
+ let poll_id = super::utils::get_poll_id(merchant_account.get_id(), request_poll_id.clone());
let redis_value = redis_conn
.get_key::<Option<String>>(poll_id.as_str())
.await
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index 374c37dc217..5a8e12992cc 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -53,7 +53,7 @@ pub async fn refund_create_core(
let db = &*state.store;
let (merchant_id, payment_intent, payment_attempt, amount);
- merchant_id = &merchant_account.merchant_id;
+ merchant_id = merchant_account.get_id();
payment_intent = db
.find_payment_intent_by_payment_id_merchant_id(
@@ -112,12 +112,7 @@ pub async fn refund_create_core(
req.merchant_connector_details
.to_owned()
.async_map(|mcd| async {
- payments::helpers::insert_merchant_connector_creds_to_config(
- db,
- merchant_id.as_str(),
- mcd,
- )
- .await
+ payments::helpers::insert_merchant_connector_creds_to_config(db, merchant_id, mcd).await
})
.await
.transpose()?;
@@ -301,7 +296,10 @@ pub async fn trigger_refund_to_gateway(
1,
&add_attributes([
("connector", connector.connector_name.to_string()),
- ("merchant_id", merchant_account.merchant_id.clone()),
+ (
+ "merchant_id",
+ merchant_account.get_id().get_string_repr().to_owned(),
+ ),
]),
);
storage::RefundUpdate::ErrorUpdate {
@@ -402,7 +400,7 @@ pub async fn refund_retrieve_core(
let db = &*state.store;
let (merchant_id, payment_intent, payment_attempt, refund, response);
- merchant_id = &merchant_account.merchant_id;
+ merchant_id = merchant_account.get_id();
refund = db
.find_refund_by_merchant_id_refund_id(
@@ -443,12 +441,7 @@ pub async fn refund_retrieve_core(
.merchant_connector_details
.to_owned()
.async_map(|mcd| async {
- payments::helpers::insert_merchant_connector_creds_to_config(
- db,
- merchant_id.as_str(),
- mcd,
- )
- .await
+ payments::helpers::insert_merchant_connector_creds_to_config(db, merchant_id, mcd).await
})
.await
.transpose()?;
@@ -596,7 +589,10 @@ pub async fn sync_refund_with_gateway(
1,
&add_attributes([
("connector", connector.connector_name.to_string()),
- ("merchant_id", merchant_account.merchant_id.clone()),
+ (
+ "merchant_id",
+ merchant_account.get_id().get_string_repr().to_owned(),
+ ),
]),
);
let refund_connector_transaction_id = err.connector_transaction_id;
@@ -650,7 +646,7 @@ pub async fn refund_update_core(
let db = state.store.as_ref();
let refund = db
.find_refund_by_merchant_id_refund_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&req.refund_id,
merchant_account.storage_scheme,
)
@@ -735,7 +731,7 @@ pub async fn validate_and_create_refund(
let predicate = req
.merchant_id
.as_ref()
- .map(|merchant_id| merchant_id != &merchant_account.merchant_id);
+ .map(|merchant_id| merchant_id != merchant_account.get_id());
utils::when(predicate.unwrap_or(false), || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
@@ -752,7 +748,7 @@ pub async fn validate_and_create_refund(
let all_refunds = db
.find_refund_by_merchant_id_connector_transaction_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&connecter_transaction_id,
merchant_account.storage_scheme,
)
@@ -799,7 +795,7 @@ pub async fn validate_and_create_refund(
.set_internal_reference_id(utils::generate_id(consts::ID_LENGTH, "refid"))
.set_external_reference_id(Some(refund_id.clone()))
.set_payment_id(req.payment_id)
- .set_merchant_id(merchant_account.merchant_id.clone())
+ .set_merchant_id(merchant_account.get_id().clone())
.set_connector_transaction_id(connecter_transaction_id.to_string())
.set_connector(connector)
.set_refund_type(req.refund_type.unwrap_or_default().foreign_into())
@@ -868,7 +864,7 @@ pub async fn refund_list(
let refund_list = db
.filter_refund_by_constraints(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&req,
merchant_account.storage_scheme,
limit,
@@ -884,7 +880,7 @@ pub async fn refund_list(
let total_count = db
.get_total_count_of_refunds(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&req,
merchant_account.storage_scheme,
)
@@ -910,7 +906,7 @@ pub async fn refund_filter_list(
let db = state.store;
let filter_list = db
.filter_refund_by_meta_constraints(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&req,
merchant_account.storage_scheme,
)
@@ -946,7 +942,7 @@ pub async fn refund_manual_update(
let refund = state
.store
.find_refund_by_merchant_id_refund_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&req.refund_id,
merchant_account.storage_scheme,
)
@@ -983,7 +979,7 @@ pub async fn get_filters_for_refunds(
merchant_account: domain::MerchantAccount,
) -> RouterResponse<api_models::refunds::RefundListFilters> {
let merchant_connector_accounts = if let services::ApplicationResponse::Json(data) =
- super::admin::list_payment_connectors(state, merchant_account.merchant_id).await?
+ super::admin::list_payment_connectors(state, merchant_account.get_id().to_owned()).await?
{
data
} else {
@@ -1452,7 +1448,7 @@ pub async fn add_refund_execute_task(
pub async fn get_refund_sync_process_schedule_time(
db: &dyn db::StorageInterface,
connector: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let redis_mapping: errors::CustomResult<process_data::ConnectorPTMapping, errors::RedisError> =
diff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rs
index b17217737be..c8ba5d6a0df 100644
--- a/crates/router/src/core/routing.rs
+++ b/crates/router/src/core/routing.rs
@@ -49,7 +49,7 @@ pub async fn retrieve_merchant_routing_dictionary(
let routing_metadata = state
.store
.list_routing_algorithm_metadata_by_merchant_id_transaction_type(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
transaction_type,
i64::from(query_params.limit.unwrap_or_default()),
i64::from(query_params.offset.unwrap_or_default()),
@@ -101,7 +101,7 @@ pub async fn create_routing_config(
let algorithm_id = common_utils::generate_id(
consts::ROUTING_CONFIG_ID_LENGTH,
- &format!("routing_{}", &merchant_account.merchant_id),
+ &format!("routing_{}", merchant_account.get_id().get_string_repr()),
);
let profile_id = request
@@ -112,17 +112,13 @@ pub async fn create_routing_config(
})
.attach_printable("Profile_id not provided")?;
- core_utils::validate_and_get_business_profile(
- db,
- Some(&profile_id),
- &merchant_account.merchant_id,
- )
- .await?;
+ core_utils::validate_and_get_business_profile(db, Some(&profile_id), merchant_account.get_id())
+ .await?;
helpers::validate_connectors_in_routing_config(
&state,
&key_store,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&profile_id,
&algorithm,
)
@@ -132,7 +128,7 @@ pub async fn create_routing_config(
let algo = RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id,
- merchant_id: merchant_account.merchant_id,
+ merchant_id: merchant_account.get_id().to_owned(),
name: name.clone(),
description: Some(description.clone()),
kind: algorithm.get_kind().foreign_into(),
@@ -164,7 +160,7 @@ pub async fn link_routing_config(
let routing_algorithm = db
.find_routing_algorithm_by_algorithm_id_merchant_id(
&algorithm_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
)
.await
.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;
@@ -172,7 +168,7 @@ pub async fn link_routing_config(
let business_profile = core_utils::validate_and_get_business_profile(
db,
Some(&routing_algorithm.profile_id),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
)
.await?
.get_required_value("BusinessProfile")
@@ -232,7 +228,7 @@ pub async fn retrieve_routing_config(
let routing_algorithm = db
.find_routing_algorithm_by_algorithm_id_merchant_id(
&algorithm_id.0,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
@@ -240,7 +236,7 @@ pub async fn retrieve_routing_config(
core_utils::validate_and_get_business_profile(
db,
Some(&routing_algorithm.profile_id),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
)
.await?
.get_required_value("BusinessProfile")
@@ -271,7 +267,7 @@ pub async fn unlink_routing_config(
let business_profile = core_utils::validate_and_get_business_profile(
db,
Some(&profile_id),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
)
.await?;
match business_profile {
@@ -338,9 +334,12 @@ pub async fn update_default_routing_config(
) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
metrics::ROUTING_UPDATE_CONFIG.add(&metrics::CONTEXT, 1, &[]);
let db = state.store.as_ref();
- let default_config =
- helpers::get_merchant_default_config(db, &merchant_account.merchant_id, transaction_type)
- .await?;
+ let default_config = helpers::get_merchant_default_config(
+ db,
+ merchant_account.get_id().get_string_repr(),
+ transaction_type,
+ )
+ .await?;
utils::when(default_config.len() != updated_config.len(), || {
Err(errors::ApiErrorResponse::PreconditionFailed {
@@ -369,7 +368,7 @@ pub async fn update_default_routing_config(
helpers::update_merchant_default_config(
db,
- &merchant_account.merchant_id,
+ merchant_account.get_id().get_string_repr(),
updated_config.clone(),
transaction_type,
)
@@ -387,16 +386,16 @@ pub async fn retrieve_default_routing_config(
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(&metrics::CONTEXT, 1, &[]);
let db = state.store.as_ref();
- helpers::get_merchant_default_config(db, &merchant_account.merchant_id, transaction_type)
- .await
- .map(|conn_choice| {
- metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(
- &metrics::CONTEXT,
- 1,
- &[],
- );
- service_api::ApplicationResponse::Json(conn_choice)
- })
+ helpers::get_merchant_default_config(
+ db,
+ merchant_account.get_id().get_string_repr(),
+ transaction_type,
+ )
+ .await
+ .map(|conn_choice| {
+ metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(&metrics::CONTEXT, 1, &[]);
+ service_api::ApplicationResponse::Json(conn_choice)
+ })
}
pub async fn retrieve_linked_routing_config(
@@ -412,14 +411,14 @@ pub async fn retrieve_linked_routing_config(
core_utils::validate_and_get_business_profile(
db,
Some(&profile_id),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
)
.await?
.map(|profile| vec![profile])
.get_required_value("BusinessProfile")
.change_context(errors::ApiErrorResponse::BusinessProfileNotFound { id: profile_id })?
} else {
- db.list_business_profile_by_merchant_id(&merchant_account.merchant_id)
+ db.list_business_profile_by_merchant_id(merchant_account.get_id())
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?
};
@@ -467,7 +466,7 @@ pub async fn retrieve_default_routing_config_for_profiles(
let db = state.store.as_ref();
let all_profiles = db
- .list_business_profile_by_merchant_id(&merchant_account.merchant_id)
+ .list_business_profile_by_merchant_id(merchant_account.get_id())
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)
.attach_printable("error retrieving all business profiles for merchant")?;
@@ -510,7 +509,7 @@ pub async fn update_default_routing_config_for_profile(
let business_profile = core_utils::validate_and_get_business_profile(
db,
Some(&profile_id),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
)
.await?
.get_required_value("BusinessProfile")
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 707ed41d95a..5978ef521a8 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -23,55 +23,56 @@ use crate::{
/// provides the complete merchant routing dictionary that is basically a list of all the routing
/// configs a merchant configured with an active_id field that specifies the current active routing
/// config
-pub async fn get_merchant_routing_dictionary(
- db: &dyn StorageInterface,
- merchant_id: &str,
-) -> RouterResult<routing_types::RoutingDictionary> {
- let key = get_routing_dictionary_key(merchant_id);
- let maybe_dict = db.find_config_by_key(&key).await;
-
- match maybe_dict {
- Ok(config) => config
- .config
- .parse_struct("RoutingDictionary")
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Merchant routing dictionary has invalid structure"),
-
- Err(e) if e.current_context().is_db_not_found() => {
- let new_dictionary = routing_types::RoutingDictionary {
- merchant_id: merchant_id.to_string(),
- active_id: None,
- records: Vec::new(),
- };
-
- let serialized = new_dictionary
- .encode_to_string_of_json()
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error serializing newly created merchant dictionary")?;
-
- let new_config = configs::ConfigNew {
- key,
- config: serialized,
- };
-
- db.insert_config(new_config)
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error inserting new routing dictionary for merchant")?;
-
- Ok(new_dictionary)
- }
-
- Err(e) => Err(e)
- .change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Error fetching routing dictionary for merchant"),
- }
-}
+// pub async fn get_merchant_routing_dictionary(
+// db: &dyn StorageInterface,
+// merchant_id: &str,
+// ) -> RouterResult<routing_types::RoutingDictionary> {
+// let key = get_routing_dictionary_key(merchant_id);
+// let maybe_dict = db.find_config_by_key(&key).await;
+
+// match maybe_dict {
+// Ok(config) => config
+// .config
+// .parse_struct("RoutingDictionary")
+// .change_context(errors::ApiErrorResponse::InternalServerError)
+// .attach_printable("Merchant routing dictionary has invalid structure"),
+
+// Err(e) if e.current_context().is_db_not_found() => {
+// let new_dictionary = routing_types::RoutingDictionary {
+// merchant_id: merchant_id.to_owned(),
+// active_id: None,
+// records: Vec::new(),
+// };
+
+// let serialized = new_dictionary
+// .encode_to_string_of_json()
+// .change_context(errors::ApiErrorResponse::InternalServerError)
+// .attach_printable("Error serializing newly created merchant dictionary")?;
+
+// let new_config = configs::ConfigNew {
+// key,
+// config: serialized,
+// };
+
+// db.insert_config(new_config)
+// .await
+// .change_context(errors::ApiErrorResponse::InternalServerError)
+// .attach_printable("Error inserting new routing dictionary for merchant")?;
+
+// Ok(new_dictionary)
+// }
+
+// Err(e) => Err(e)
+// .change_context(errors::ApiErrorResponse::InternalServerError)
+// .attach_printable("Error fetching routing dictionary for merchant"),
+// }
+// }
/// Provides us with all the configured configs of the Merchant in the ascending time configured
/// manner and chooses the first of them
pub async fn get_merchant_default_config(
db: &dyn StorageInterface,
+ // Cannot make this as merchant id domain type because, we are passing profile id also here
merchant_id: &str,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> {
@@ -253,8 +254,13 @@ pub async fn update_business_profile_active_algorithm_ref(
let profile_id = current_business_profile.profile_id.clone();
- let routing_cache_key =
- cache::CacheKind::Routing(format!("routing_config_{merchant_id}_{profile_id}").into());
+ let routing_cache_key = cache::CacheKind::Routing(
+ format!(
+ "routing_config_{}_{profile_id}",
+ merchant_id.get_string_repr()
+ )
+ .into(),
+ );
let (routing_algorithm, payout_routing_algorithm) = match transaction_type {
storage::enums::TransactionType::Payment => (Some(ref_val), None),
@@ -304,7 +310,7 @@ pub async fn update_business_profile_active_algorithm_ref(
pub async fn validate_connectors_in_routing_config(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
profile_id: &str,
routing_algorithm: &routing_types::RoutingAlgorithm,
) -> RouterResult<()> {
@@ -318,7 +324,7 @@ pub async fn validate_connectors_in_routing_config(
)
.await
.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
- id: merchant_id.to_string(),
+ id: merchant_id.get_string_repr().to_owned(),
})?;
let name_mca_id_set = all_mcas
@@ -426,10 +432,3 @@ pub fn get_default_config_key(
storage::enums::TransactionType::Payout => format!("routing_default_po_{merchant_id}"),
}
}
-pub fn get_payment_config_routing_id(merchant_id: &str) -> String {
- format!("payment_config_id_{merchant_id}")
-}
-
-pub fn get_payment_method_surcharge_routing_id(merchant_id: &str) -> String {
- format!("payment_method_surcharge_id_{merchant_id}")
-}
diff --git a/crates/router/src/core/surcharge_decision_config.rs b/crates/router/src/core/surcharge_decision_config.rs
index 55ea4ba16f8..03e4f337372 100644
--- a/crates/router/src/core/surcharge_decision_config.rs
+++ b/crates/router/src/core/surcharge_decision_config.rs
@@ -11,9 +11,7 @@ use error_stack::ResultExt;
use euclid::frontend::ast;
use storage_impl::redis::cache;
-use super::routing::helpers::{
- get_payment_method_surcharge_routing_id, update_merchant_active_algorithm_ref,
-};
+use super::routing::helpers::update_merchant_active_algorithm_ref;
use crate::{
core::errors::{self, RouterResponse},
routes::SessionState,
@@ -50,7 +48,9 @@ pub async fn upsert_surcharge_decision_config(
.attach_printable("Could not decode the routing algorithm")?
.unwrap_or_default();
- let key = get_payment_method_surcharge_routing_id(merchant_account.merchant_id.as_str());
+ let key = merchant_account
+ .get_id()
+ .get_payment_method_surcharge_routing_id();
let read_config_key = db.find_config_by_key(&key).await;
ast::lowering::lower_program(program.clone())
@@ -147,7 +147,9 @@ pub async fn delete_surcharge_decision_config(
merchant_account: domain::MerchantAccount,
) -> RouterResponse<()> {
let db = state.store.as_ref();
- let key = get_payment_method_surcharge_routing_id(&merchant_account.merchant_id);
+ let key = merchant_account
+ .get_id()
+ .get_payment_method_surcharge_routing_id();
let mut algo_id: routing::RoutingAlgorithmRef = merchant_account
.routing_algorithm
.clone()
@@ -175,8 +177,9 @@ pub async fn retrieve_surcharge_decision_config(
merchant_account: domain::MerchantAccount,
) -> RouterResponse<SurchargeDecisionManagerResponse> {
let db = state.store.as_ref();
- let algorithm_id =
- get_payment_method_surcharge_routing_id(merchant_account.merchant_id.as_str());
+ let algorithm_id = merchant_account
+ .get_id()
+ .get_payment_method_surcharge_routing_id();
let algo_config = db
.find_config_by_key(&algorithm_id)
.await
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index e44493cff39..9389240c972 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -197,7 +197,7 @@ pub async fn signin(
let signin_strategy =
if let Some(preferred_merchant_id) = user_from_db.get_preferred_merchant_id() {
let preferred_role = user_from_db
- .get_role_from_db_by_merchant_id(&state, preferred_merchant_id.as_str())
+ .get_role_from_db_by_merchant_id(&state, &preferred_merchant_id)
.await
.to_not_found_response(UserErrors::InternalServerError)
.attach_printable("User role with preferred_merchant_id not found")?;
@@ -1110,7 +1110,9 @@ pub async fn create_internal_user(
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- consts::user_role::INTERNAL_USER_MERCHANT_ID,
+ &common_utils::id_type::MerchantId::get_internal_user_merchant_id(
+ consts::user_role::INTERNAL_USER_MERCHANT_ID,
+ ),
&state.store.get_master_key().to_vec().into(),
)
.await
@@ -1126,7 +1128,9 @@ pub async fn create_internal_user(
.store
.find_merchant_account_by_merchant_id(
key_manager_state,
- consts::user_role::INTERNAL_USER_MERCHANT_ID,
+ &common_utils::id_type::MerchantId::get_internal_user_merchant_id(
+ consts::user_role::INTERNAL_USER_MERCHANT_ID,
+ ),
&key_store,
)
.await
@@ -1195,7 +1199,7 @@ pub async fn switch_merchant_id(
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- request.merchant_id.as_str(),
+ &request.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
@@ -1211,7 +1215,7 @@ pub async fn switch_merchant_id(
.store
.find_merchant_account_by_merchant_id(
key_manager_state,
- request.merchant_id.as_str(),
+ &request.merchant_id,
&key_store,
)
.await
@@ -1294,7 +1298,7 @@ pub async fn create_merchant_account(
if let Err(e) = role_insertion_res {
let _ = state
.store
- .delete_merchant_account_by_merchant_id(new_merchant.get_merchant_id().as_str())
+ .delete_merchant_account_by_merchant_id(&new_merchant.get_merchant_id())
.await;
return Err(e);
}
@@ -1386,7 +1390,7 @@ pub async fn list_users_for_merchant_account(
) -> UserResponse<user_api::ListUsersResponse> {
let user_roles: HashMap<String, _> = state
.store
- .list_user_roles_by_merchant_id(user_from_token.merchant_id.as_str())
+ .list_user_roles_by_merchant_id(&user_from_token.merchant_id)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("No user roles for given merchant id")?
@@ -1481,7 +1485,7 @@ pub async fn verify_email(
let signin_strategy =
if let Some(preferred_merchant_id) = user_from_db.get_preferred_merchant_id() {
let preferred_role = user_from_db
- .get_role_from_db_by_merchant_id(&state, preferred_merchant_id.as_str())
+ .get_role_from_db_by_merchant_id(&state, &preferred_merchant_id)
.await
.change_context(UserErrors::InternalServerError)
.attach_printable("User role with preferred_merchant_id not found")?;
@@ -1626,7 +1630,7 @@ pub async fn verify_token(
.merchant_id;
Ok(ApplicationResponse::Json(user_api::VerifyTokenResponse {
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
user_email: user.email,
}))
}
diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs
index b279d852d40..6eb1dd572dd 100644
--- a/crates/router/src/core/user/dashboard_metadata.rs
+++ b/crates/router/src/core/user/dashboard_metadata.rs
@@ -707,7 +707,7 @@ pub async fn backfill_metadata(
pub async fn get_merchant_connector_account_by_name(
state: &SessionState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
key_store: &MerchantKeyStore,
) -> UserResult<Option<domain::MerchantConnectorAccount>> {
diff --git a/crates/router/src/core/user/sample_data.rs b/crates/router/src/core/user/sample_data.rs
index b679753b56c..f5faf68435f 100644
--- a/crates/router/src/core/user/sample_data.rs
+++ b/crates/router/src/core/user/sample_data.rs
@@ -19,8 +19,7 @@ pub async fn generate_sample_data_for_user(
req: SampleDataRequest,
_req_state: ReqState,
) -> SampleDataApiResponse<()> {
- let sample_data =
- generate_sample_data(&state, req, user_from_token.merchant_id.as_str()).await?;
+ let sample_data = generate_sample_data(&state, req, &user_from_token.merchant_id).await?;
let key_store = state
.store
@@ -74,13 +73,13 @@ pub async fn delete_sample_data_for_user(
_req: SampleDataRequest,
_req_state: ReqState,
) -> SampleDataApiResponse<()> {
- let merchant_id_del = user_from_token.merchant_id.as_str();
+ let merchant_id_del = user_from_token.merchant_id;
let key_manager_state = &(&state).into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- &user_from_token.merchant_id,
+ &merchant_id_del,
&state.store.get_master_key().to_vec().into(),
)
.await
@@ -89,17 +88,17 @@ pub async fn delete_sample_data_for_user(
state
.store
- .delete_payment_intents_for_sample_data(key_manager_state, merchant_id_del, &key_store)
+ .delete_payment_intents_for_sample_data(key_manager_state, &merchant_id_del, &key_store)
.await
.switch()?;
state
.store
- .delete_payment_attempts_for_sample_data(merchant_id_del)
+ .delete_payment_attempts_for_sample_data(&merchant_id_del)
.await
.switch()?;
state
.store
- .delete_refunds_for_sample_data(merchant_id_del)
+ .delete_refunds_for_sample_data(&merchant_id_del)
.await
.switch()?;
diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rs
index 429907a73a6..5d93c00909d 100644
--- a/crates/router/src/core/user_role.rs
+++ b/crates/router/src/core/user_role.rs
@@ -101,7 +101,7 @@ pub async fn update_user_role(
.store
.update_user_role_by_user_id_merchant_id(
user_to_be_updated.get_user_id(),
- user_role_to_be_updated.merchant_id.as_str(),
+ &user_role_to_be_updated.merchant_id,
UserRoleUpdate::UpdateRole {
role_id: req.role_id.clone(),
modified_by: user_from_token.user_id,
@@ -335,7 +335,7 @@ pub async fn delete_user_role(
match user_roles
.iter()
- .find(|&role| role.merchant_id == user_from_token.merchant_id.as_str())
+ .find(|&role| role.merchant_id == user_from_token.merchant_id)
{
Some(user_role) => {
let role_info = roles::RoleInfo::from_role_id(
@@ -362,7 +362,7 @@ pub async fn delete_user_role(
.store
.delete_user_role_by_user_id_merchant_id(
user_from_db.get_user_id(),
- user_from_token.merchant_id.as_str(),
+ &user_from_token.merchant_id,
)
.await
.change_context(UserErrors::InternalServerError)
@@ -379,7 +379,7 @@ pub async fn delete_user_role(
.store
.delete_user_role_by_user_id_merchant_id(
user_from_db.get_user_id(),
- user_from_token.merchant_id.as_str(),
+ &user_from_token.merchant_id,
)
.await
.change_context(UserErrors::InternalServerError)
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 3af36d493d7..f25e13161aa 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -56,7 +56,7 @@ pub async fn get_mca_for_payout<'a>(
None => {
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
None,
key_store,
&payout_data.profile_id,
@@ -150,7 +150,7 @@ pub async fn construct_payout_router_data<'a, F>(
let router_data = types::RouterData {
flow: PhantomData,
- merchant_id: merchant_account.merchant_id.to_owned(),
+ merchant_id: merchant_account.get_id().to_owned(),
customer_id: customer_details.to_owned().map(|c| c.customer_id),
connector_customer: connector_customer_id,
connector: connector_name.to_string(),
@@ -243,7 +243,7 @@ pub async fn construct_refund_router_data<'a, F>(
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
creds_identifier,
key_store,
&profile_id,
@@ -268,7 +268,7 @@ pub async fn construct_refund_router_data<'a, F>(
let webhook_url = Some(helpers::create_webhook_url(
&state.base_url.clone(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&connector_id.to_string(),
));
let test_mode: Option<bool> = merchant_connector_account.is_test_mode_on();
@@ -306,7 +306,7 @@ pub async fn construct_refund_router_data<'a, F>(
let router_data = types::RouterData {
flow: PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
customer_id: payment_intent.customer_id.to_owned(),
connector: connector_id.to_string(),
payment_id: payment_attempt.payment_id.clone(),
@@ -538,7 +538,7 @@ pub async fn construct_accept_dispute_router_data<'a>(
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
None,
key_store,
&profile_id,
@@ -557,7 +557,7 @@ pub async fn construct_accept_dispute_router_data<'a>(
.get_required_value("payment_method_type")?;
let router_data = types::RouterData {
flow: PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
connector: dispute.connector.to_string(),
payment_id: payment_attempt.payment_id.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
@@ -590,7 +590,7 @@ pub async fn construct_accept_dispute_router_data<'a>(
preprocessing_id: None,
connector_request_reference_id: get_connector_request_reference_id(
&state.conf,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
payment_attempt,
),
#[cfg(feature = "payouts")]
@@ -637,7 +637,7 @@ pub async fn construct_submit_evidence_router_data<'a>(
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
None,
key_store,
&profile_id,
@@ -656,7 +656,7 @@ pub async fn construct_submit_evidence_router_data<'a>(
.get_required_value("payment_method_type")?;
let router_data = types::RouterData {
flow: PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
connector: connector_id.to_string(),
payment_id: payment_attempt.payment_id.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
@@ -687,7 +687,7 @@ pub async fn construct_submit_evidence_router_data<'a>(
payment_method_status: None,
connector_request_reference_id: get_connector_request_reference_id(
&state.conf,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
payment_attempt,
),
#[cfg(feature = "payouts")]
@@ -734,7 +734,7 @@ pub async fn construct_upload_file_router_data<'a>(
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
None,
key_store,
&profile_id,
@@ -753,7 +753,7 @@ pub async fn construct_upload_file_router_data<'a>(
.get_required_value("payment_method_type")?;
let router_data = types::RouterData {
flow: PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
connector: connector_id.to_string(),
payment_id: payment_attempt.payment_id.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
@@ -789,7 +789,7 @@ pub async fn construct_upload_file_router_data<'a>(
payment_method_balance: None,
connector_request_reference_id: get_connector_request_reference_id(
&state.conf,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
payment_attempt,
),
#[cfg(feature = "payouts")]
@@ -835,7 +835,7 @@ pub async fn construct_defend_dispute_router_data<'a>(
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
None,
key_store,
&profile_id,
@@ -854,7 +854,7 @@ pub async fn construct_defend_dispute_router_data<'a>(
.get_required_value("payment_method_type")?;
let router_data = types::RouterData {
flow: PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
connector: connector_id.to_string(),
payment_id: payment_attempt.payment_id.clone(),
attempt_id: payment_attempt.attempt_id.clone(),
@@ -888,7 +888,7 @@ pub async fn construct_defend_dispute_router_data<'a>(
payment_method_balance: None,
connector_request_reference_id: get_connector_request_reference_id(
&state.conf,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
payment_attempt,
),
#[cfg(feature = "payouts")]
@@ -928,7 +928,7 @@ pub async fn construct_retrieve_file_router_data<'a>(
let merchant_connector_account = helpers::get_merchant_connector_account(
state,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
None,
key_store,
profile_id,
@@ -944,7 +944,7 @@ pub async fn construct_retrieve_file_router_data<'a>(
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let router_data = types::RouterData {
flow: PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
connector: connector_id.to_string(),
customer_id: None,
connector_customer: None,
@@ -999,7 +999,7 @@ pub async fn construct_retrieve_file_router_data<'a>(
pub fn is_merchant_enabled_for_payment_id_as_connector_request_id(
conf: &Settings,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> bool {
let config_map = &conf
.connector_request_reference_id_config
@@ -1009,7 +1009,7 @@ pub fn is_merchant_enabled_for_payment_id_as_connector_request_id(
pub fn get_connector_request_reference_id(
conf: &Settings,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> String {
let is_config_enabled_for_merchant =
@@ -1026,7 +1026,7 @@ pub fn get_connector_request_reference_id(
pub async fn validate_and_get_business_profile(
db: &dyn StorageInterface,
profile_id: Option<&String>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<Option<storage::business_profile::BusinessProfile>> {
profile_id
.async_map(|profile_id| async {
@@ -1108,7 +1108,7 @@ pub async fn get_profile_id_from_business_details(
let _ = validate_and_get_business_profile(
db,
Some(profile_id),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
)
.await?;
}
@@ -1120,7 +1120,7 @@ pub async fn get_profile_id_from_business_details(
let business_profile = db
.find_business_profile_by_profile_name_merchant_id(
&profile_name,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::BusinessProfileNotFound {
@@ -1136,8 +1136,8 @@ pub async fn get_profile_id_from_business_details(
}
}
-pub fn get_poll_id(merchant_id: String, unique_id: String) -> String {
- format!("poll_{}_{}", merchant_id, unique_id)
+pub fn get_poll_id(merchant_id: &common_utils::id_type::MerchantId, unique_id: String) -> String {
+ merchant_id.get_poll_id(&unique_id)
}
pub fn get_external_authentication_request_poll_id(payment_id: &String) -> String {
diff --git a/crates/router/src/core/verification.rs b/crates/router/src/core/verification.rs
index 65ac5688325..724f244d397 100644
--- a/crates/router/src/core/verification.rs
+++ b/crates/router/src/core/verification.rs
@@ -11,7 +11,7 @@ const APPLEPAY_INTERNAL_MERCHANT_NAME: &str = "Applepay_merchant";
pub async fn verify_merchant_creds_for_applepay(
state: SessionState,
body: verifications::ApplepayMerchantVerificationRequest,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
) -> CustomResult<services::ApplicationResponse<ApplepayMerchantResponse>, errors::ApiErrorResponse>
{
let applepay_merchant_configs = state.conf.applepay_merchant_configs.get_inner();
@@ -84,7 +84,7 @@ pub async fn verify_merchant_creds_for_applepay(
pub async fn get_verified_apple_domains_with_mid_mca_id(
state: SessionState,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
merchant_connector_id: String,
) -> CustomResult<
services::ApplicationResponse<verifications::ApplepayVerifiedDomainsResponse>,
@@ -104,7 +104,7 @@ pub async fn get_verified_apple_domains_with_mid_mca_id(
let verified_domains = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
- merchant_id.as_str(),
+ &merchant_id,
merchant_connector_id.as_str(),
&key_store,
)
diff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rs
index a59789b2802..c286497e5cf 100644
--- a/crates/router/src/core/verification/utils.rs
+++ b/crates/router/src/core/verification/utils.rs
@@ -11,7 +11,7 @@ use crate::{
pub async fn check_existence_and_add_domain_to_db(
state: &SessionState,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
merchant_connector_id: String,
domain_from_req: Vec<String>,
) -> CustomResult<Vec<String>, errors::ApiErrorResponse> {
@@ -49,7 +49,6 @@ pub async fn check_existence_and_add_domain_to_db(
already_verified_domains.append(&mut new_verified_domains);
let updated_mca = storage::MerchantConnectorAccountUpdate::Update {
- merchant_id: None,
connector_type: None,
connector_name: None,
connector_account_details: None,
diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rs
index 5c5346ce134..61207aebb9e 100644
--- a/crates/router/src/core/webhooks/incoming.rs
+++ b/crates/router/src/core/webhooks/incoming.rs
@@ -86,7 +86,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>(
.attach_printable("Unable to extract request id from request")
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let auth_type = auth::AuthenticationType::WebhookAuth {
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
};
let status_code = 200;
let api_event = ApiEventsType::Webhooks {
@@ -98,7 +98,7 @@ pub async fn incoming_webhooks_wrapper<W: types::OutgoingWebhookType>(
.attach_printable("Could not convert webhook effect to string")?;
let api_event = ApiEvent::new(
- Some(merchant_account.merchant_id.clone()),
+ Some(merchant_account.get_id().clone()),
flow,
&request_id,
request_duration,
@@ -135,7 +135,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
1,
&[metrics::KeyValue::new(
MERCHANT_ID,
- merchant_account.merchant_id.clone(),
+ merchant_account.get_id().get_string_repr().to_owned(),
)],
);
let mut request_details = IncomingWebhookRequestDetails {
@@ -160,7 +160,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
let decoded_body = connector
.decode_webhook_body(
&request_details,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_connector_account
.clone()
.and_then(|merchant_connector_account| {
@@ -200,7 +200,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
&metrics::CONTEXT,
1,
&[
- metrics::KeyValue::new(MERCHANT_ID, merchant_account.merchant_id.clone()),
+ metrics::KeyValue::new(MERCHANT_ID, merchant_account.get_id().clone()),
metrics::KeyValue::new("connector", connector_name.to_string()),
],
);
@@ -226,7 +226,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
let is_webhook_event_enabled = !utils::is_webhook_event_disabled(
&*state.clone().store,
connector_name.as_str(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&event_type,
)
.await;
@@ -295,7 +295,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
.clone()
.verify_webhook_source(
&request_details,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_connector_account.connector_webhook_details.clone(),
merchant_connector_account.connector_account_details.clone(),
connector_name.as_str(),
@@ -318,7 +318,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
1,
&[metrics::KeyValue::new(
MERCHANT_ID,
- merchant_account.merchant_id.clone(),
+ merchant_account.get_id().clone(),
)],
);
} else if connector.is_webhook_source_verification_mandatory() {
@@ -478,7 +478,7 @@ async fn incoming_webhooks_core<W: types::OutgoingWebhookType>(
1,
&[metrics::KeyValue::new(
MERCHANT_ID,
- merchant_account.merchant_id.clone(),
+ merchant_account.get_id().get_string_repr().to_owned(),
)],
);
WebhookResponseTracker::NoEffect
@@ -516,7 +516,7 @@ async fn payments_incoming_webhook_flow(
let payment_id = get_payment_id(
state.store.as_ref(),
&id,
- merchant_account.merchant_id.as_str(),
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await?;
@@ -531,7 +531,7 @@ async fn payments_incoming_webhook_flow(
lock_action
.clone()
- .perform_locking_action(&state, merchant_account.merchant_id.to_string())
+ .perform_locking_action(&state, merchant_account.get_id().to_owned())
.await?;
let response = Box::pin(payments::payments_core::<
@@ -548,7 +548,7 @@ async fn payments_incoming_webhook_flow(
payments::operations::PaymentStatus,
api::PaymentsRetrieveRequest {
resource_id: id,
- merchant_id: Some(merchant_account.merchant_id.clone()),
+ merchant_id: Some(merchant_account.get_id().clone()),
force_sync: true,
connector: None,
param: None,
@@ -565,7 +565,7 @@ async fn payments_incoming_webhook_flow(
.await;
lock_action
- .free_lock_action(&state, merchant_account.merchant_id.to_owned())
+ .free_lock_action(&state, merchant_account.get_id().to_owned())
.await?;
match response {
@@ -584,7 +584,7 @@ async fn payments_incoming_webhook_flow(
metrics::WEBHOOK_PAYMENT_NOT_FOUND.add(
&metrics::CONTEXT,
1,
- &add_attributes([("merchant_id", merchant_account.merchant_id.clone())]),
+ &add_attributes([("merchant_id", merchant_account.get_id().clone())]),
);
return Ok(WebhookResponseTracker::NoEffect);
}
@@ -656,7 +656,7 @@ async fn payouts_incoming_webhook_flow(
webhooks::ObjectReferenceId::PayoutId(payout_id_type) => match payout_id_type {
webhooks::PayoutIdType::PayoutAttemptId(id) => db
.find_payout_attempt_by_merchant_id_payout_attempt_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&id,
merchant_account.storage_scheme,
)
@@ -665,7 +665,7 @@ async fn payouts_incoming_webhook_flow(
.attach_printable("Failed to fetch the payout attempt")?,
webhooks::PayoutIdType::ConnectorPayoutId(id) => db
.find_payout_attempt_by_merchant_id_connector_payout_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&id,
merchant_account.storage_scheme,
)
@@ -679,7 +679,7 @@ async fn payouts_incoming_webhook_flow(
let payouts = db
.find_payout_by_merchant_id_payout_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&payout_attempt.payout_id,
merchant_account.storage_scheme,
)
@@ -780,7 +780,7 @@ async fn refunds_incoming_webhook_flow(
webhooks::ObjectReferenceId::RefundId(refund_id_type) => match refund_id_type {
webhooks::RefundIdType::RefundId(id) => db
.find_refund_by_merchant_id_refund_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&id,
merchant_account.storage_scheme,
)
@@ -789,7 +789,7 @@ async fn refunds_incoming_webhook_flow(
.attach_printable("Failed to fetch the refund")?,
webhooks::RefundIdType::ConnectorRefundId(id) => db
.find_refund_by_merchant_id_connector_refund_id_connector(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&id,
connector_name,
merchant_account.storage_scheme,
@@ -874,7 +874,7 @@ async fn get_payment_attempt_from_object_reference_id(
match object_reference_id {
api::ObjectReferenceId::PaymentId(api::PaymentIdType::ConnectorTransactionId(ref id)) => db
.find_payment_attempt_by_merchant_id_connector_txn_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
id,
merchant_account.storage_scheme,
)
@@ -883,7 +883,7 @@ async fn get_payment_attempt_from_object_reference_id(
api::ObjectReferenceId::PaymentId(api::PaymentIdType::PaymentAttemptId(ref id)) => db
.find_payment_attempt_by_attempt_id_merchant_id(
id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
@@ -891,7 +891,7 @@ async fn get_payment_attempt_from_object_reference_id(
api::ObjectReferenceId::PaymentId(api::PaymentIdType::PreprocessingId(ref id)) => db
.find_payment_attempt_by_preprocessing_id_merchant_id(
id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
@@ -906,7 +906,7 @@ async fn get_or_update_dispute_object(
state: SessionState,
option_dispute: Option<diesel_models::dispute::Dispute>,
dispute_details: api::disputes::DisputePayload,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
event_type: webhooks::IncomingWebhookEvent,
business_profile: &diesel_models::business_profile::BusinessProfile,
@@ -1013,7 +1013,7 @@ async fn external_authentication_incoming_webhook_flow(
webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => state
.store
.find_authentication_by_merchant_id_authentication_id(
- merchant_account.merchant_id.clone(),
+ merchant_account.get_id(),
authentication_id.clone(),
)
.await
@@ -1026,7 +1026,7 @@ async fn external_authentication_incoming_webhook_flow(
) => state
.store
.find_authentication_by_merchant_id_connector_authentication_id(
- merchant_account.merchant_id.clone(),
+ merchant_account.get_id().clone(),
connector_authentication_id.clone(),
)
.await
@@ -1062,7 +1062,7 @@ async fn external_authentication_incoming_webhook_flow(
payment_id: Some(api_models::payments::PaymentIdType::PaymentIntentId(
payment_id,
)),
- merchant_id: Some(merchant_account.merchant_id.clone()),
+ merchant_id: Some(merchant_account.get_id().clone()),
..Default::default()
};
let payments_response = Box::pin(payments::payments_core::<
@@ -1097,7 +1097,7 @@ async fn external_authentication_incoming_webhook_flow(
payments_response.status.foreign_into();
// Set poll_id as completed in redis to allow the fetch status of poll through retrieve_poll_status api from client
let poll_id = core_utils::get_poll_id(
- merchant_account.merchant_id.clone(),
+ merchant_account.get_id(),
core_utils::get_external_authentication_request_poll_id(&payment_id),
);
let redis_conn = state
@@ -1170,7 +1170,7 @@ async fn mandates_incoming_webhook_flow(
mandate_id,
)) => db
.find_mandate_by_merchant_id_mandate_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
mandate_id.as_str(),
merchant_account.storage_scheme,
)
@@ -1180,7 +1180,7 @@ async fn mandates_incoming_webhook_flow(
webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id),
) => db
.find_mandate_by_merchant_id_connector_mandate_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
connector_mandate_id.as_str(),
merchant_account.storage_scheme,
)
@@ -1195,7 +1195,7 @@ async fn mandates_incoming_webhook_flow(
let mandate_id = mandate.mandate_id.clone();
let updated_mandate = db
.update_mandate_by_merchant_id_mandate_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&mandate_id,
storage::MandateUpdate::StatusUpdate { mandate_status },
mandate,
@@ -1377,7 +1377,7 @@ async fn disputes_incoming_webhook_flow(
.await?;
let option_dispute = db
.find_by_merchant_id_payment_id_connector_dispute_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&payment_attempt.payment_id,
&dispute_details.connector_dispute_id,
)
@@ -1387,7 +1387,7 @@ async fn disputes_incoming_webhook_flow(
state.clone(),
option_dispute,
dispute_details,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&payment_attempt,
event_type,
&business_profile,
@@ -1516,7 +1516,7 @@ async fn bank_transfer_webhook_flow(
async fn get_payment_id(
db: &dyn StorageInterface,
payment_id: &api::PaymentIdType,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: enums::MerchantStorageScheme,
) -> errors::RouterResult<String> {
let pay_id = || async {
@@ -1574,7 +1574,7 @@ async fn verify_webhook_source_verification_call(
> = connector_data.connector.get_connector_integration();
let connector_webhook_secrets = connector
.get_webhook_source_verification_merchant_secret(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
connector_name,
merchant_connector_account.connector_webhook_details.clone(),
)
@@ -1676,7 +1676,7 @@ async fn fetch_optional_mca_and_connector(
let mca = db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&state.into(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
connector_name_or_mca_id,
key_store,
)
diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rs
index 7f30a58e208..39b9fac33b3 100644
--- a/crates/router/src/core/webhooks/outgoing.rs
+++ b/crates/router/src/core/webhooks/outgoing.rs
@@ -285,7 +285,7 @@ async fn trigger_webhook_to_merchant(
1,
&[metrics::KeyValue::new(
MERCHANT_ID,
- business_profile.merchant_id.clone(),
+ business_profile.merchant_id.get_string_repr().to_owned(),
)],
);
logger::debug!(outgoing_webhook_response=?response);
@@ -435,7 +435,7 @@ fn raise_webhooks_analytics_event(
state: SessionState,
trigger_webhook_result: CustomResult<(), errors::WebhooksFlowError>,
content: Option<api::OutgoingWebhookContent>,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
event: domain::Event,
) {
let error = if let Err(error) = trigger_webhook_result {
@@ -649,7 +649,7 @@ enum ScheduleWebhookRetry {
async fn update_event_if_client_error(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
error_message: String,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
@@ -698,7 +698,7 @@ async fn update_event_if_client_error(
async fn api_client_error_handler(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
client_error: error_stack::Report<errors::ApiClientError>,
delivery_attempt: enums::WebhookDeliveryAttempt,
@@ -739,7 +739,7 @@ async fn api_client_error_handler(
async fn update_event_in_storage(
state: SessionState,
merchant_key_store: domain::MerchantKeyStore,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
response: reqwest::Response,
) -> CustomResult<domain::Event, errors::WebhooksFlowError> {
@@ -812,17 +812,20 @@ async fn update_event_in_storage(
.change_context(errors::WebhooksFlowError::WebhookEventUpdationFailed)
}
-fn increment_webhook_outgoing_received_count(merchant_id: &str) {
+fn increment_webhook_outgoing_received_count(merchant_id: &common_utils::id_type::MerchantId) {
metrics::WEBHOOK_OUTGOING_RECEIVED_COUNT.add(
&metrics::CONTEXT,
1,
- &[metrics::KeyValue::new(MERCHANT_ID, merchant_id.to_owned())],
+ &[metrics::KeyValue::new(
+ MERCHANT_ID,
+ merchant_id.get_string_repr().to_owned(),
+ )],
)
}
async fn success_response_handler(
state: SessionState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
process_tracker: Option<storage::ProcessTracker>,
business_status: &'static str,
) -> CustomResult<(), errors::WebhooksFlowError> {
@@ -843,7 +846,7 @@ async fn success_response_handler(
async fn error_response_handler(
state: SessionState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
delivery_attempt: enums::WebhookDeliveryAttempt,
status_code: u16,
log_message: &'static str,
@@ -852,7 +855,10 @@ async fn error_response_handler(
metrics::WEBHOOK_OUTGOING_NOT_RECEIVED_COUNT.add(
&metrics::CONTEXT,
1,
- &[metrics::KeyValue::new(MERCHANT_ID, merchant_id.to_owned())],
+ &[metrics::KeyValue::new(
+ MERCHANT_ID,
+ merchant_id.get_string_repr().to_owned(),
+ )],
);
let error = report!(errors::WebhooksFlowError::NotReceivedByMerchant);
diff --git a/crates/router/src/core/webhooks/types.rs b/crates/router/src/core/webhooks/types.rs
index 7559f692b1f..d9eed529e88 100644
--- a/crates/router/src/core/webhooks/types.rs
+++ b/crates/router/src/core/webhooks/types.rs
@@ -58,7 +58,7 @@ impl OutgoingWebhookType for webhooks::OutgoingWebhook {
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub(crate) struct OutgoingWebhookTrackingData {
- pub(crate) merchant_id: String,
+ pub(crate) merchant_id: common_utils::id_type::MerchantId,
pub(crate) business_profile_id: String,
pub(crate) event_type: enums::EventType,
pub(crate) event_class: enums::EventClass,
diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rs
index e0a0a86c78d..f837fbba0d7 100644
--- a/crates/router/src/core/webhooks/utils.rs
+++ b/crates/router/src/core/webhooks/utils.rs
@@ -26,10 +26,10 @@ const IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_SOURCE_VERIFICATION_FLOW: &st
pub async fn is_webhook_event_disabled(
db: &dyn StorageInterface,
connector_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
event: &api::IncomingWebhookEvent,
) -> bool {
- let redis_key = format!("whconf_disabled_events_{merchant_id}_{connector_id}");
+ let redis_key = merchant_id.get_webhook_config_disabled_events_key(connector_id);
let merchant_webhook_disable_config_result: CustomResult<
api::MerchantWebhookConfig,
redis_interface::errors::RedisError,
@@ -73,7 +73,7 @@ pub async fn construct_webhook_router_data<'a>(
let router_data = types::RouterData {
flow: PhantomData,
- merchant_id: merchant_account.merchant_id.clone(),
+ merchant_id: merchant_account.get_id().clone(),
connector: connector_name.to_string(),
customer_id: None,
payment_id: IRRELEVANT_PAYMENT_ID_IN_SOURCE_VERIFICATION_FLOW.to_string(),
diff --git a/crates/router/src/core/webhooks/webhook_events.rs b/crates/router/src/core/webhooks/webhook_events.rs
index 19118ad639a..034cf936c18 100644
--- a/crates/router/src/core/webhooks/webhook_events.rs
+++ b/crates/router/src/core/webhooks/webhook_events.rs
@@ -37,7 +37,7 @@ pub async fn list_initial_delivery_attempts(
match account {
MerchantAccountOrBusinessProfile::MerchantAccount(merchant_account) => store
.list_initial_events_by_merchant_id_primary_object_id(key_manager_state,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&object_id,
&key_store,
)
@@ -74,7 +74,7 @@ pub async fn list_initial_delivery_attempts(
match account {
MerchantAccountOrBusinessProfile::MerchantAccount(merchant_account) => store
.list_initial_events_by_merchant_id_constraints(key_manager_state,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
created_after,
created_before,
limit,
@@ -122,7 +122,7 @@ pub async fn list_delivery_attempts(
store
.list_events_by_merchant_id_initial_attempt_id(
key_manager_state,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&initial_attempt_id,
&key_store,
)
@@ -272,10 +272,15 @@ async fn determine_identifier_and_get_key_store(
) -> errors::RouterResult<(MerchantAccountOrBusinessProfile, domain::MerchantKeyStore)> {
let store = state.store.as_ref();
let key_manager_state = &(&state).into();
+ let merchant_id =
+ common_utils::id_type::MerchantId::from(merchant_id_or_profile_id.clone().into())
+ .change_context(errors::ApiErrorResponse::InvalidDataValue {
+ field_name: "merchant_id",
+ })?;
match store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- &merchant_id_or_profile_id,
+ &merchant_id,
&store.get_master_key().to_vec().into(),
)
.await
@@ -285,11 +290,7 @@ async fn determine_identifier_and_get_key_store(
// Find a merchant account having `merchant_id` = `merchant_id_or_profile_id`.
Ok(key_store) => {
let merchant_account = store
- .find_merchant_account_by_merchant_id(
- key_manager_state,
- &merchant_id_or_profile_id,
- &key_store,
- )
+ .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index 7a8f143f0bd..1e415760fc8 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -299,7 +299,7 @@ impl FraudCheckInterface for KafkaStore {
async fn find_fraud_check_by_payment_id(
&self,
payment_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> CustomResult<FraudCheck, StorageError> {
let frm = self
.diesel_store
@@ -317,7 +317,7 @@ impl FraudCheckInterface for KafkaStore {
async fn find_fraud_check_by_payment_id_if_present(
&self,
payment_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> CustomResult<Option<FraudCheck>, StorageError> {
let frm = self
.diesel_store
diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs
index 04a8f673a94..f15adbeea69 100644
--- a/crates/router/src/db/address.rs
+++ b/crates/router/src/db/address.rs
@@ -64,7 +64,7 @@ where
async fn find_address_by_merchant_id_payment_id_address_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_id: &str,
address_id: &str,
key_store: &domain::MerchantKeyStore,
@@ -75,7 +75,7 @@ where
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
address: storage_types::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Address>, errors::StorageError>;
@@ -118,7 +118,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -130,7 +130,7 @@ mod storage {
async fn find_address_by_merchant_id_payment_id_address_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_id: &str,
address_id: &str,
key_store: &domain::MerchantKeyStore,
@@ -147,7 +147,7 @@ mod storage {
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|address| async {
address
- .convert(state, key_store.key.get_inner(), merchant_id.to_string())
+ .convert(state, key_store.key.get_inner(), merchant_id.clone().into())
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -171,7 +171,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -202,7 +202,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -232,7 +232,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -260,7 +260,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -273,7 +273,7 @@ mod storage {
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
address: storage_types::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Address>, errors::StorageError> {
@@ -291,7 +291,7 @@ mod storage {
for address in addresses.into_iter() {
output.push(
address
- .convert(state, key_store.key.get_inner(), merchant_id.to_string())
+ .convert(state, key_store.key.get_inner(), merchant_id.clone().into())
.await
.change_context(errors::StorageError::DecryptionError)?,
)
@@ -346,7 +346,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -358,7 +358,7 @@ mod storage {
async fn find_address_by_merchant_id_payment_id_address_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_id: &str,
address_id: &str,
key_store: &domain::MerchantKeyStore,
@@ -405,7 +405,9 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ common_utils::types::keymanager::Identifier::Merchant(
+ key_store.merchant_id.clone(),
+ ),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -428,7 +430,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -473,7 +475,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -514,7 +516,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -555,7 +557,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -619,7 +621,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?),
@@ -649,7 +651,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -662,7 +664,7 @@ mod storage {
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
address: storage_types::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Address>, errors::StorageError> {
@@ -683,7 +685,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
@@ -716,7 +718,7 @@ impl AddressInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError),
@@ -731,7 +733,7 @@ impl AddressInterface for MockDb {
async fn find_address_by_merchant_id_payment_id_address_id(
&self,
state: &KeyManagerState,
- _merchant_id: &str,
+ _merchant_id: &id_type::MerchantId,
_payment_id: &str,
address_id: &str,
key_store: &domain::MerchantKeyStore,
@@ -749,7 +751,7 @@ impl AddressInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError),
@@ -785,7 +787,7 @@ impl AddressInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError),
@@ -822,7 +824,7 @@ impl AddressInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError),
@@ -853,7 +855,7 @@ impl AddressInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -877,7 +879,7 @@ impl AddressInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -887,7 +889,7 @@ impl AddressInterface for MockDb {
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
address_update: storage_types::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Address>, errors::StorageError> {
@@ -898,7 +900,7 @@ impl AddressInterface for MockDb {
.iter_mut()
.find(|address| {
address.customer_id.as_ref() == Some(customer_id)
- && address.merchant_id == merchant_id
+ && address.merchant_id == *merchant_id
})
.map(|a| {
let address_updated =
@@ -912,7 +914,7 @@ impl AddressInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
diff --git a/crates/router/src/db/api_keys.rs b/crates/router/src/db/api_keys.rs
index ea63a881704..186bd004c16 100644
--- a/crates/router/src/db/api_keys.rs
+++ b/crates/router/src/db/api_keys.rs
@@ -19,20 +19,20 @@ pub trait ApiKeyInterface {
async fn update_api_key(
&self,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
key_id: String,
api_key: storage::ApiKeyUpdate,
) -> CustomResult<storage::ApiKey, errors::StorageError>;
async fn revoke_api_key(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key_id: &str,
) -> CustomResult<bool, errors::StorageError>;
async fn find_api_key_by_merchant_id_key_id_optional(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key_id: &str,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError>;
@@ -43,7 +43,7 @@ pub trait ApiKeyInterface {
async fn list_api_keys_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError>;
@@ -66,7 +66,7 @@ impl ApiKeyInterface for Store {
#[instrument(skip_all)]
async fn update_api_key(
&self,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
key_id: String,
api_key: storage::ApiKeyUpdate,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
@@ -114,7 +114,7 @@ impl ApiKeyInterface for Store {
#[instrument(skip_all)]
async fn revoke_api_key(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -156,7 +156,7 @@ impl ApiKeyInterface for Store {
#[instrument(skip_all)]
async fn find_api_key_by_merchant_id_key_id_optional(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key_id: &str,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -198,7 +198,7 @@ impl ApiKeyInterface for Store {
#[instrument(skip_all)]
async fn list_api_keys_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> {
@@ -239,7 +239,7 @@ impl ApiKeyInterface for MockDb {
async fn update_api_key(
&self,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
key_id: String,
api_key: storage::ApiKeyUpdate,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
@@ -281,14 +281,14 @@ impl ApiKeyInterface for MockDb {
async fn revoke_api_key(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let mut locked_api_keys = self.api_keys.lock().await;
// find the key to remove, if it exists
if let Some(pos) = locked_api_keys
.iter()
- .position(|k| k.merchant_id == merchant_id && k.key_id == key_id)
+ .position(|k| k.merchant_id == *merchant_id && k.key_id == key_id)
{
// use `remove` instead of `swap_remove` so we have a consistent order, which might
// matter to someone using limit/offset in `list_api_keys_by_merchant_id`
@@ -301,7 +301,7 @@ impl ApiKeyInterface for MockDb {
async fn find_api_key_by_merchant_id_key_id_optional(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key_id: &str,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
Ok(self
@@ -309,7 +309,7 @@ impl ApiKeyInterface for MockDb {
.lock()
.await
.iter()
- .find(|k| k.merchant_id == merchant_id && k.key_id == key_id)
+ .find(|k| k.merchant_id == *merchant_id && k.key_id == key_id)
.cloned())
}
@@ -328,7 +328,7 @@ impl ApiKeyInterface for MockDb {
async fn list_api_keys_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> {
@@ -360,7 +360,7 @@ impl ApiKeyInterface for MockDb {
.lock()
.await
.iter()
- .filter(|k| k.merchant_id == merchant_id)
+ .filter(|k| k.merchant_id == *merchant_id)
.skip(offset)
.take(limit)
.cloned()
@@ -392,10 +392,12 @@ mod tests {
.await
.expect("Failed to create Mock store");
+ let merchant_id = common_utils::id_type::MerchantId::from("merchant1".into()).unwrap();
+
let key1 = mockdb
.insert_api_key(storage::ApiKeyNew {
key_id: "key_id1".into(),
- merchant_id: "merchant1".into(),
+ merchant_id: merchant_id.clone(),
name: "Key 1".into(),
description: None,
hashed_api_key: "hashed_key1".to_string().into(),
@@ -410,7 +412,7 @@ mod tests {
mockdb
.insert_api_key(storage::ApiKeyNew {
key_id: "key_id2".into(),
- merchant_id: "merchant1".into(),
+ merchant_id: merchant_id.clone(),
name: "Key 2".into(),
description: None,
hashed_api_key: "hashed_key2".to_string().into(),
@@ -423,20 +425,20 @@ mod tests {
.unwrap();
let found_key1 = mockdb
- .find_api_key_by_merchant_id_key_id_optional("merchant1", "key_id1")
+ .find_api_key_by_merchant_id_key_id_optional(&merchant_id, "key_id1")
.await
.unwrap()
.unwrap();
assert_eq!(found_key1.key_id, key1.key_id);
assert!(mockdb
- .find_api_key_by_merchant_id_key_id_optional("merchant1", "does_not_exist")
+ .find_api_key_by_merchant_id_key_id_optional(&merchant_id, "does_not_exist")
.await
.unwrap()
.is_none());
mockdb
.update_api_key(
- "merchant1".into(),
+ merchant_id.clone(),
"key_id1".into(),
storage::ApiKeyUpdate::LastUsedUpdate {
last_used: datetime!(2023-02-04 1:11),
@@ -445,7 +447,7 @@ mod tests {
.await
.unwrap();
let updated_key1 = mockdb
- .find_api_key_by_merchant_id_key_id_optional("merchant1", "key_id1")
+ .find_api_key_by_merchant_id_key_id_optional(&merchant_id, "key_id1")
.await
.unwrap()
.unwrap();
@@ -453,16 +455,19 @@ mod tests {
assert_eq!(
mockdb
- .list_api_keys_by_merchant_id("merchant1", None, None)
+ .list_api_keys_by_merchant_id(&merchant_id, None, None)
.await
.unwrap()
.len(),
2
);
- mockdb.revoke_api_key("merchant1", "key_id1").await.unwrap();
+ mockdb
+ .revoke_api_key(&merchant_id, "key_id1")
+ .await
+ .unwrap();
assert_eq!(
mockdb
- .list_api_keys_by_merchant_id("merchant1", None, None)
+ .list_api_keys_by_merchant_id(&merchant_id, None, None)
.await
.unwrap()
.len(),
@@ -473,6 +478,8 @@ mod tests {
#[allow(clippy::unwrap_used)]
#[tokio::test]
async fn test_api_keys_cache() {
+ let merchant_id = common_utils::id_type::MerchantId::from("test_merchant".into()).unwrap();
+
#[allow(clippy::expect_used)]
let db = MockDb::new(&redis_interface::RedisSettings::default())
.await
@@ -484,10 +491,9 @@ mod tests {
.await
.unwrap();
- let merchant_id = "test_merchant";
let api = storage::ApiKeyNew {
key_id: "test_key".into(),
- merchant_id: merchant_id.into(),
+ merchant_id: merchant_id.clone(),
name: "My test key".into(),
description: None,
hashed_api_key: "a_hashed_key".to_string().into(),
@@ -506,19 +512,28 @@ mod tests {
};
let _: Option<storage::ApiKey> = cache::get_or_populate_in_memory(
&db,
- &format!("{}_{}", merchant_id, hashed_api_key.clone().into_inner()),
+ &format!(
+ "{}_{}",
+ merchant_id.get_string_repr(),
+ hashed_api_key.clone().into_inner()
+ ),
find_call,
&ACCOUNTS_CACHE,
)
.await
.unwrap();
- let delete_call = || async { db.revoke_api_key(merchant_id, &api.key_id).await };
+ let delete_call = || async { db.revoke_api_key(&merchant_id, &api.key_id).await };
cache::publish_and_redact(
&db,
CacheKind::Accounts(
- format!("{}_{}", merchant_id, hashed_api_key.clone().into_inner()).into(),
+ format!(
+ "{}_{}",
+ merchant_id.get_string_repr(),
+ hashed_api_key.clone().into_inner()
+ )
+ .into(),
),
delete_call,
)
@@ -527,7 +542,11 @@ mod tests {
assert!(ACCOUNTS_CACHE
.get_val::<storage::ApiKey>(CacheKey {
- key: format!("{}_{}", merchant_id, hashed_api_key.into_inner()),
+ key: format!(
+ "{}_{}",
+ merchant_id.get_string_repr(),
+ hashed_api_key.into_inner()
+ ),
prefix: String::default(),
},)
.await
diff --git a/crates/router/src/db/authentication.rs b/crates/router/src/db/authentication.rs
index 43f30afd881..1307c53338d 100644
--- a/crates/router/src/db/authentication.rs
+++ b/crates/router/src/db/authentication.rs
@@ -18,13 +18,13 @@ pub trait AuthenticationInterface {
async fn find_authentication_by_merchant_id_authentication_id(
&self,
- merchant_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
authentication_id: String,
) -> CustomResult<storage::Authentication, errors::StorageError>;
async fn find_authentication_by_merchant_id_connector_authentication_id(
&self,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
connector_authentication_id: String,
) -> CustomResult<storage::Authentication, errors::StorageError>;
@@ -52,13 +52,13 @@ impl AuthenticationInterface for Store {
#[instrument(skip_all)]
async fn find_authentication_by_merchant_id_authentication_id(
&self,
- merchant_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
authentication_id: String,
) -> CustomResult<storage::Authentication, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Authentication::find_by_merchant_id_authentication_id(
&conn,
- &merchant_id,
+ merchant_id,
&authentication_id,
)
.await
@@ -67,7 +67,7 @@ impl AuthenticationInterface for Store {
async fn find_authentication_by_merchant_id_connector_authentication_id(
&self,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
connector_authentication_id: String,
) -> CustomResult<storage::Authentication, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -157,23 +157,23 @@ impl AuthenticationInterface for MockDb {
async fn find_authentication_by_merchant_id_authentication_id(
&self,
- merchant_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
authentication_id: String,
) -> CustomResult<storage::Authentication, errors::StorageError> {
let authentications = self.authentications.lock().await;
authentications
.iter()
- .find(|a| a.merchant_id == merchant_id && a.authentication_id == authentication_id)
+ .find(|a| a.merchant_id == *merchant_id && a.authentication_id == authentication_id)
.ok_or(
errors::StorageError::ValueNotFound(format!(
- "cannot find authentication for authentication_id = {authentication_id} and merchant_id = {merchant_id}"
+ "cannot find authentication for authentication_id = {authentication_id} and merchant_id = {merchant_id:?}"
)).into(),
).cloned()
}
async fn find_authentication_by_merchant_id_connector_authentication_id(
&self,
- _merchant_id: String,
+ _merchant_id: common_utils::id_type::MerchantId,
_connector_authentication_id: String,
) -> CustomResult<storage::Authentication, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
@@ -199,7 +199,7 @@ impl AuthenticationInterface for MockDb {
})
.ok_or(
errors::StorageError::ValueNotFound(format!(
- "cannot find authentication for authentication_id = {authentication_id} and merchant_id = {merchant_id}"
+ "cannot find authentication for authentication_id = {authentication_id} and merchant_id = {merchant_id:?}"
))
.into(),
)
diff --git a/crates/router/src/db/authorization.rs b/crates/router/src/db/authorization.rs
index 7b7802d64e5..40902ce8882 100644
--- a/crates/router/src/db/authorization.rs
+++ b/crates/router/src/db/authorization.rs
@@ -18,13 +18,13 @@ pub trait AuthorizationInterface {
async fn find_all_authorizations_by_merchant_id_payment_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
) -> CustomResult<Vec<storage::Authorization>, errors::StorageError>;
async fn update_authorization_by_merchant_id_authorization_id(
&self,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
authorization_id: String,
authorization: storage::AuthorizationUpdate,
) -> CustomResult<storage::Authorization, errors::StorageError>;
@@ -47,7 +47,7 @@ impl AuthorizationInterface for Store {
#[instrument(skip_all)]
async fn find_all_authorizations_by_merchant_id_payment_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -59,7 +59,7 @@ impl AuthorizationInterface for Store {
#[instrument(skip_all)]
async fn update_authorization_by_merchant_id_authorization_id(
&self,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
authorization_id: String,
authorization: storage::AuthorizationUpdate,
) -> CustomResult<storage::Authorization, errors::StorageError> {
@@ -109,13 +109,13 @@ impl AuthorizationInterface for MockDb {
async fn find_all_authorizations_by_merchant_id_payment_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> {
let authorizations = self.authorizations.lock().await;
let authorizations_found: Vec<storage::Authorization> = authorizations
.iter()
- .filter(|a| a.merchant_id == merchant_id && a.payment_id == payment_id)
+ .filter(|a| a.merchant_id == *merchant_id && a.payment_id == payment_id)
.cloned()
.collect();
@@ -124,7 +124,7 @@ impl AuthorizationInterface for MockDb {
async fn update_authorization_by_merchant_id_authorization_id(
&self,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
authorization_id: String,
authorization_update: storage::AuthorizationUpdate,
) -> CustomResult<storage::Authorization, errors::StorageError> {
@@ -141,7 +141,7 @@ impl AuthorizationInterface for MockDb {
})
.ok_or(
errors::StorageError::ValueNotFound(format!(
- "cannot find authorization for authorization_id = {authorization_id} and merchant_id = {merchant_id}"
+ "cannot find authorization for authorization_id = {authorization_id} and merchant_id = {merchant_id:?}"
))
.into(),
)
diff --git a/crates/router/src/db/blocklist.rs b/crates/router/src/db/blocklist.rs
index 4a7236c95a7..4740af9f818 100644
--- a/crates/router/src/db/blocklist.rs
+++ b/crates/router/src/db/blocklist.rs
@@ -19,24 +19,24 @@ pub trait BlocklistInterface {
async fn find_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError>;
async fn delete_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError>;
async fn list_blocklist_entries_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>;
async fn list_blocklist_entries_by_merchant_id_data_kind(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
limit: i64,
offset: i64,
@@ -60,7 +60,7 @@ impl BlocklistInterface for Store {
#[instrument(skip_all)]
async fn find_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -72,7 +72,7 @@ impl BlocklistInterface for Store {
#[instrument(skip_all)]
async fn list_blocklist_entries_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Blocklist::list_by_merchant_id(&conn, merchant_id)
@@ -83,7 +83,7 @@ impl BlocklistInterface for Store {
#[instrument(skip_all)]
async fn list_blocklist_entries_by_merchant_id_data_kind(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
limit: i64,
offset: i64,
@@ -103,7 +103,7 @@ impl BlocklistInterface for Store {
#[instrument(skip_all)]
async fn delete_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -125,7 +125,7 @@ impl BlocklistInterface for MockDb {
async fn find_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_fingerprint_id: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
@@ -133,14 +133,14 @@ impl BlocklistInterface for MockDb {
async fn list_blocklist_entries_by_merchant_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn list_blocklist_entries_by_merchant_id_data_kind(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_data_kind: common_enums::BlocklistDataKind,
_limit: i64,
_offset: i64,
@@ -150,7 +150,7 @@ impl BlocklistInterface for MockDb {
async fn delete_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_fingerprint_id: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
@@ -170,7 +170,7 @@ impl BlocklistInterface for KafkaStore {
#[instrument(skip_all)]
async fn find_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
self.diesel_store
@@ -181,7 +181,7 @@ impl BlocklistInterface for KafkaStore {
#[instrument(skip_all)]
async fn delete_blocklist_entry_by_merchant_id_fingerprint_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::Blocklist, errors::StorageError> {
self.diesel_store
@@ -192,7 +192,7 @@ impl BlocklistInterface for KafkaStore {
#[instrument(skip_all)]
async fn list_blocklist_entries_by_merchant_id_data_kind(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
limit: i64,
offset: i64,
@@ -205,7 +205,7 @@ impl BlocklistInterface for KafkaStore {
#[instrument(skip_all)]
async fn list_blocklist_entries_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
self.diesel_store
.list_blocklist_entries_by_merchant_id(merchant_id)
diff --git a/crates/router/src/db/blocklist_fingerprint.rs b/crates/router/src/db/blocklist_fingerprint.rs
index 65671555c7f..835bad5ea99 100644
--- a/crates/router/src/db/blocklist_fingerprint.rs
+++ b/crates/router/src/db/blocklist_fingerprint.rs
@@ -19,7 +19,7 @@ pub trait BlocklistFingerprintInterface {
async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError>;
}
@@ -41,7 +41,7 @@ impl BlocklistFingerprintInterface for Store {
#[instrument(skip_all)]
async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint_id: &str,
) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -66,7 +66,7 @@ impl BlocklistFingerprintInterface for MockDb {
async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_fingerprint_id: &str,
) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
@@ -88,7 +88,7 @@ impl BlocklistFingerprintInterface for KafkaStore {
#[instrument(skip_all)]
async fn find_blocklist_fingerprint_by_merchant_id_fingerprint_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> {
self.diesel_store
diff --git a/crates/router/src/db/blocklist_lookup.rs b/crates/router/src/db/blocklist_lookup.rs
index 0f796946beb..8829f3804e7 100644
--- a/crates/router/src/db/blocklist_lookup.rs
+++ b/crates/router/src/db/blocklist_lookup.rs
@@ -19,13 +19,13 @@ pub trait BlocklistLookupInterface {
async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError>;
async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError>;
}
@@ -47,7 +47,7 @@ impl BlocklistLookupInterface for Store {
#[instrument(skip_all)]
async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -59,7 +59,7 @@ impl BlocklistLookupInterface for Store {
#[instrument(skip_all)]
async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -81,7 +81,7 @@ impl BlocklistLookupInterface for MockDb {
async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
@@ -89,7 +89,7 @@ impl BlocklistLookupInterface for MockDb {
async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
@@ -111,7 +111,7 @@ impl BlocklistLookupInterface for KafkaStore {
#[instrument(skip_all)]
async fn find_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
self.diesel_store
@@ -122,7 +122,7 @@ impl BlocklistLookupInterface for KafkaStore {
#[instrument(skip_all)]
async fn delete_blocklist_lookup_entry_by_merchant_id_fingerprint(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
fingerprint: &str,
) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {
self.diesel_store
diff --git a/crates/router/src/db/business_profile.rs b/crates/router/src/db/business_profile.rs
index 5e7c9bd0b20..099cad9b804 100644
--- a/crates/router/src/db/business_profile.rs
+++ b/crates/router/src/db/business_profile.rs
@@ -24,7 +24,7 @@ pub trait BusinessProfileInterface {
async fn find_business_profile_by_profile_name_merchant_id(
&self,
profile_name: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<business_profile::BusinessProfile, errors::StorageError>;
async fn update_business_profile_by_profile_id(
@@ -36,12 +36,12 @@ pub trait BusinessProfileInterface {
async fn delete_business_profile_by_profile_id_merchant_id(
&self,
profile_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError>;
async fn list_business_profile_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<business_profile::BusinessProfile>, errors::StorageError>;
}
@@ -74,7 +74,7 @@ impl BusinessProfileInterface for Store {
async fn find_business_profile_by_profile_name_merchant_id(
&self,
profile_name: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
business_profile::BusinessProfile::find_by_profile_name_merchant_id(
@@ -106,7 +106,7 @@ impl BusinessProfileInterface for Store {
async fn delete_business_profile_by_profile_id_merchant_id(
&self,
profile_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
business_profile::BusinessProfile::delete_by_profile_id_merchant_id(
@@ -121,7 +121,7 @@ impl BusinessProfileInterface for Store {
#[instrument(skip_all)]
async fn list_business_profile_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<business_profile::BusinessProfile>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
business_profile::BusinessProfile::list_business_profile_by_merchant_id(&conn, merchant_id)
@@ -191,14 +191,14 @@ impl BusinessProfileInterface for MockDb {
async fn delete_business_profile_by_profile_id_merchant_id(
&self,
profile_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
let mut business_profiles = self.business_profiles.lock().await;
let index = business_profiles
.iter()
- .position(|bp| bp.profile_id == profile_id && bp.merchant_id == merchant_id)
+ .position(|bp| bp.profile_id == profile_id && bp.merchant_id == *merchant_id)
.ok_or::<errors::StorageError>(errors::StorageError::ValueNotFound(format!(
- "No business profile found for profile_id = {} and merchant_id = {}",
+ "No business profile found for profile_id = {} and merchant_id = {:?}",
profile_id, merchant_id
)))?;
business_profiles.remove(index);
@@ -207,14 +207,14 @@ impl BusinessProfileInterface for MockDb {
async fn list_business_profile_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<business_profile::BusinessProfile>, errors::StorageError> {
let business_profile_by_merchant_id = self
.business_profiles
.lock()
.await
.iter()
- .filter(|business_profile| business_profile.merchant_id == merchant_id)
+ .filter(|business_profile| business_profile.merchant_id == *merchant_id)
.cloned()
.collect();
@@ -224,7 +224,7 @@ impl BusinessProfileInterface for MockDb {
async fn find_business_profile_by_profile_name_merchant_id(
&self,
_profile_name: &str,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
diff --git a/crates/router/src/db/capture.rs b/crates/router/src/db/capture.rs
index 48aad6a9e3f..34ef1bfddff 100644
--- a/crates/router/src/db/capture.rs
+++ b/crates/router/src/db/capture.rs
@@ -16,7 +16,7 @@ pub trait CaptureInterface {
async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
authorized_attempt_id: &str,
storage_scheme: enums::MerchantStorageScheme,
@@ -80,7 +80,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
authorized_attempt_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
@@ -151,7 +151,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
authorized_attempt_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
@@ -215,7 +215,7 @@ impl CaptureInterface for MockDb {
}
async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_payment_id: &str,
_authorized_attempt_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs
index 4bb29c37413..01c7d7737a5 100644
--- a/crates/router/src/db/customers.rs
+++ b/crates/router/src/db/customers.rs
@@ -25,14 +25,14 @@ where
async fn delete_customer_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError>;
async fn find_customer_optional_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<customer::Customer>, errors::StorageError>;
@@ -42,7 +42,7 @@ where
&self,
state: &KeyManagerState,
customer_id: id_type::CustomerId,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
customer: customer::Customer,
customer_update: storage_types::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
@@ -53,7 +53,7 @@ where
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<customer::Customer, errors::StorageError>;
@@ -61,7 +61,7 @@ where
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<customer::Customer>, errors::StorageError>;
@@ -113,7 +113,7 @@ mod storage {
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<customer::Customer>, errors::StorageError> {
@@ -161,7 +161,7 @@ mod storage {
c.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -182,7 +182,7 @@ mod storage {
&self,
state: &KeyManagerState,
customer_id: id_type::CustomerId,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
customer: customer::Customer,
customer_update: storage_types::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
@@ -203,7 +203,7 @@ mod storage {
.map_err(|error| report!(errors::StorageError::from(error)))
};
let key = PartitionKey::MerchantIdCustomerId {
- merchant_id: merchant_id.as_str(),
+ merchant_id: &merchant_id,
customer_id: customer_id.get_string_repr(),
};
let field = format!("cust_{}", customer_id.get_string_repr());
@@ -253,7 +253,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -264,7 +264,7 @@ mod storage {
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<customer::Customer, errors::StorageError> {
@@ -309,7 +309,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
@@ -327,7 +327,7 @@ mod storage {
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<customer::Customer>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -343,7 +343,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -385,7 +385,7 @@ mod storage {
}
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdCustomerId {
- merchant_id: merchant_id.as_str(),
+ merchant_id: &merchant_id,
customer_id: customer_id.get_string_repr(),
};
let field = format!("cust_{}", customer_id.get_string_repr());
@@ -426,7 +426,7 @@ mod storage {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -436,7 +436,7 @@ mod storage {
async fn delete_customer_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage_types::Customer::delete_by_customer_id_merchant_id(
@@ -483,7 +483,7 @@ mod storage {
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<customer::Customer>, errors::StorageError> {
@@ -497,7 +497,7 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
.async_map(|c| async {
- c.convert(state, key_store.key.get_inner(), merchant_id.to_string())
+ c.convert(state, key_store.key.get_inner(), merchant_id.clone().into())
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -520,7 +520,7 @@ mod storage {
&self,
state: &KeyManagerState,
customer_id: id_type::CustomerId,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
_customer: customer::Customer,
customer_update: storage_types::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
@@ -536,7 +536,7 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|c| async {
- c.convert(state, key_store.key.get_inner(), merchant_id)
+ c.convert(state, key_store.key.get_inner(), merchant_id.into())
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -548,7 +548,7 @@ mod storage {
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<customer::Customer, errors::StorageError> {
@@ -562,7 +562,7 @@ mod storage {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
.async_and_then(|c| async {
- c.convert(state, key_store.key.get_inner(), merchant_id.to_string())
+ c.convert(state, key_store.key.get_inner(), merchant_id.clone().into())
.await
.change_context(errors::StorageError::DecryptionError)
})
@@ -579,7 +579,7 @@ mod storage {
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<customer::Customer>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -592,7 +592,7 @@ mod storage {
let customers = try_join_all(encrypted_customers.into_iter().map(
|encrypted_customer| async {
encrypted_customer
- .convert(state, key_store.key.get_inner(), merchant_id.to_string())
+ .convert(state, key_store.key.get_inner(), merchant_id.clone().into())
.await
.change_context(errors::StorageError::DecryptionError)
},
@@ -622,7 +622,7 @@ mod storage {
c.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -634,7 +634,7 @@ mod storage {
async fn delete_customer_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage_types::Customer::delete_by_customer_id_merchant_id(
@@ -655,7 +655,7 @@ impl CustomerInterface for MockDb {
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<customer::Customer>, errors::StorageError> {
@@ -663,7 +663,7 @@ impl CustomerInterface for MockDb {
let customer = customers
.iter()
.find(|customer| {
- customer.customer_id == *customer_id && customer.merchant_id == merchant_id
+ customer.customer_id == *customer_id && &customer.merchant_id == merchant_id
})
.cloned();
customer
@@ -671,7 +671,7 @@ impl CustomerInterface for MockDb {
c.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -683,7 +683,7 @@ impl CustomerInterface for MockDb {
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<customer::Customer>, errors::StorageError> {
let customers = self.customers.lock().await;
@@ -691,14 +691,14 @@ impl CustomerInterface for MockDb {
let customers = try_join_all(
customers
.iter()
- .filter(|customer| customer.merchant_id == merchant_id)
+ .filter(|customer| customer.merchant_id == *merchant_id)
.map(|customer| async {
customer
.to_owned()
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -714,7 +714,7 @@ impl CustomerInterface for MockDb {
&self,
_state: &KeyManagerState,
_customer_id: id_type::CustomerId,
- _merchant_id: String,
+ _merchant_id: id_type::MerchantId,
_customer: customer::Customer,
_customer_update: storage_types::CustomerUpdate,
_key_store: &domain::MerchantKeyStore,
@@ -728,7 +728,7 @@ impl CustomerInterface for MockDb {
&self,
_state: &KeyManagerState,
_customer_id: &id_type::CustomerId,
- _merchant_id: &str,
+ _merchant_id: &id_type::MerchantId,
_key_store: &domain::MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<customer::Customer, errors::StorageError> {
@@ -756,7 +756,7 @@ impl CustomerInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -765,7 +765,7 @@ impl CustomerInterface for MockDb {
async fn delete_customer_by_customer_id_merchant_id(
&self,
_customer_id: &id_type::CustomerId,
- _merchant_id: &str,
+ _merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rs
index 2cbe6ad975d..f8aee34c49c 100644
--- a/crates/router/src/db/dashboard_metadata.rs
+++ b/crates/router/src/db/dashboard_metadata.rs
@@ -20,7 +20,7 @@ pub trait DashboardMetadataInterface {
async fn update_metadata(
&self,
user_id: Option<String>,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_key: enums::DashboardMetadata,
dashboard_metadata_update: storage::DashboardMetadataUpdate,
@@ -29,14 +29,14 @@ pub trait DashboardMetadataInterface {
async fn find_user_scoped_dashboard_metadata(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>;
async fn find_merchant_scoped_dashboard_metadata(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError>;
@@ -44,13 +44,13 @@ pub trait DashboardMetadataInterface {
async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError>;
async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
data_key: enums::DashboardMetadata,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError>;
}
@@ -73,7 +73,7 @@ impl DashboardMetadataInterface for Store {
async fn update_metadata(
&self,
user_id: Option<String>,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_key: enums::DashboardMetadata,
dashboard_metadata_update: storage::DashboardMetadataUpdate,
@@ -95,7 +95,7 @@ impl DashboardMetadataInterface for Store {
async fn find_user_scoped_dashboard_metadata(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
@@ -114,7 +114,7 @@ impl DashboardMetadataInterface for Store {
#[instrument(skip_all)]
async fn find_merchant_scoped_dashboard_metadata(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
@@ -133,7 +133,7 @@ impl DashboardMetadataInterface for Store {
async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::DashboardMetadata::delete_all_user_scoped_dashboard_metadata_by_merchant_id(
@@ -149,7 +149,7 @@ impl DashboardMetadataInterface for Store {
async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
data_key: enums::DashboardMetadata,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -202,7 +202,7 @@ impl DashboardMetadataInterface for MockDb {
async fn update_metadata(
&self,
user_id: Option<String>,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_key: enums::DashboardMetadata,
dashboard_metadata_update: storage::DashboardMetadataUpdate,
@@ -237,7 +237,7 @@ impl DashboardMetadataInterface for MockDb {
async fn find_user_scoped_dashboard_metadata(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
@@ -250,7 +250,7 @@ impl DashboardMetadataInterface for MockDb {
.clone()
.map(|user_id_inner| user_id_inner == user_id)
.unwrap_or(false)
- && metadata_inner.merchant_id == merchant_id
+ && metadata_inner.merchant_id == *merchant_id
&& metadata_inner.org_id == *org_id
&& data_keys.contains(&metadata_inner.data_key)
})
@@ -260,7 +260,7 @@ impl DashboardMetadataInterface for MockDb {
if query_result.is_empty() {
return Err(errors::StorageError::ValueNotFound(format!(
"No dashboard_metadata available for user_id = {user_id},\
- merchant_id = {merchant_id}, org_id = {org_id:?} and data_keys = {data_keys:?}",
+ merchant_id = {merchant_id:?}, org_id = {org_id:?} and data_keys = {data_keys:?}",
))
.into());
}
@@ -269,7 +269,7 @@ impl DashboardMetadataInterface for MockDb {
async fn find_merchant_scoped_dashboard_metadata(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
@@ -277,7 +277,7 @@ impl DashboardMetadataInterface for MockDb {
let query_result = dashboard_metadata
.iter()
.filter(|metadata_inner| {
- metadata_inner.merchant_id == merchant_id
+ metadata_inner.merchant_id == *merchant_id
&& metadata_inner.org_id == *org_id
&& data_keys.contains(&metadata_inner.data_key)
})
@@ -286,7 +286,7 @@ impl DashboardMetadataInterface for MockDb {
if query_result.is_empty() {
return Err(errors::StorageError::ValueNotFound(format!(
- "No dashboard_metadata available for merchant_id = {merchant_id},\
+ "No dashboard_metadata available for merchant_id = {merchant_id:?},\
org_id = {org_id:?} and data_keyss = {data_keys:?}",
))
.into());
@@ -296,7 +296,7 @@ impl DashboardMetadataInterface for MockDb {
async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
let mut dashboard_metadata = self.dashboard_metadata.lock().await;
@@ -308,12 +308,12 @@ impl DashboardMetadataInterface for MockDb {
.clone()
.map(|user_id_inner| user_id_inner == user_id)
.unwrap_or(false)
- && metadata_inner.merchant_id == merchant_id)
+ && metadata_inner.merchant_id == *merchant_id)
});
if dashboard_metadata.len() == initial_len {
return Err(errors::StorageError::ValueNotFound(format!(
- "No user available for user_id = {user_id} and merchant id = {merchant_id}"
+ "No user available for user_id = {user_id} and merchant id = {merchant_id:?}"
))
.into());
}
@@ -324,7 +324,7 @@ impl DashboardMetadataInterface for MockDb {
async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
data_key: enums::DashboardMetadata,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
let mut dashboard_metadata = self.dashboard_metadata.lock().await;
@@ -336,7 +336,7 @@ impl DashboardMetadataInterface for MockDb {
.user_id
.as_deref()
.map_or(false, |user_id_inner| user_id_inner == user_id)
- && metadata_inner.merchant_id == merchant_id
+ && metadata_inner.merchant_id == *merchant_id
&& metadata_inner.data_key == data_key
})
.ok_or(errors::StorageError::ValueNotFound(
diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rs
index 097ad9beab9..4de14057c18 100644
--- a/crates/router/src/db/dispute.rs
+++ b/crates/router/src/db/dispute.rs
@@ -17,26 +17,26 @@ pub trait DisputeInterface {
async fn find_by_merchant_id_payment_id_connector_dispute_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
connector_dispute_id: &str,
) -> CustomResult<Option<storage::Dispute>, errors::StorageError>;
async fn find_dispute_by_merchant_id_dispute_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
dispute_id: &str,
) -> CustomResult<storage::Dispute, errors::StorageError>;
async fn find_disputes_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
dispute_constraints: api_models::disputes::DisputeListConstraints,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError>;
async fn find_disputes_by_merchant_id_payment_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError>;
@@ -64,7 +64,7 @@ impl DisputeInterface for Store {
#[instrument(skip_all)]
async fn find_by_merchant_id_payment_id_connector_dispute_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
connector_dispute_id: &str,
) -> CustomResult<Option<storage::Dispute>, errors::StorageError> {
@@ -82,7 +82,7 @@ impl DisputeInterface for Store {
#[instrument(skip_all)]
async fn find_dispute_by_merchant_id_dispute_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
dispute_id: &str,
) -> CustomResult<storage::Dispute, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -94,7 +94,7 @@ impl DisputeInterface for Store {
#[instrument(skip_all)]
async fn find_disputes_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
dispute_constraints: api_models::disputes::DisputeListConstraints,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -106,7 +106,7 @@ impl DisputeInterface for Store {
#[instrument(skip_all)]
async fn find_disputes_by_merchant_id_payment_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -180,7 +180,7 @@ impl DisputeInterface for MockDb {
}
async fn find_by_merchant_id_payment_id_connector_dispute_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
connector_dispute_id: &str,
) -> CustomResult<Option<storage::Dispute>, errors::StorageError> {
@@ -190,7 +190,7 @@ impl DisputeInterface for MockDb {
.await
.iter()
.find(|d| {
- d.merchant_id == merchant_id
+ d.merchant_id == *merchant_id
&& d.payment_id == payment_id
&& d.connector_dispute_id == connector_dispute_id
})
@@ -199,22 +199,22 @@ impl DisputeInterface for MockDb {
async fn find_dispute_by_merchant_id_dispute_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
dispute_id: &str,
) -> CustomResult<storage::Dispute, errors::StorageError> {
let locked_disputes = self.disputes.lock().await;
locked_disputes
.iter()
- .find(|d| d.merchant_id == merchant_id && d.dispute_id == dispute_id)
+ .find(|d| d.merchant_id == *merchant_id && d.dispute_id == dispute_id)
.cloned()
- .ok_or(errors::StorageError::ValueNotFound(format!("No dispute available for merchant_id = {merchant_id} and dispute_id = {dispute_id}"))
+ .ok_or(errors::StorageError::ValueNotFound(format!("No dispute available for merchant_id = {merchant_id:?} and dispute_id = {dispute_id}"))
.into())
}
async fn find_disputes_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
dispute_constraints: api_models::disputes::DisputeListConstraints,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
let locked_disputes = self.disputes.lock().await;
@@ -222,7 +222,7 @@ impl DisputeInterface for MockDb {
Ok(locked_disputes
.iter()
.filter(|d| {
- d.merchant_id == merchant_id
+ d.merchant_id == *merchant_id
&& dispute_constraints
.dispute_status
.as_ref()
@@ -285,14 +285,14 @@ impl DisputeInterface for MockDb {
async fn find_disputes_by_merchant_id_payment_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
let locked_disputes = self.disputes.lock().await;
Ok(locked_disputes
.iter()
- .filter(|d| d.merchant_id == merchant_id && d.payment_id == payment_id)
+ .filter(|d| d.merchant_id == *merchant_id && d.payment_id == payment_id)
.cloned()
.collect())
}
@@ -381,7 +381,7 @@ mod tests {
dispute_id: String,
payment_id: String,
attempt_id: String,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
connector_dispute_id: String,
}
@@ -417,11 +417,13 @@ mod tests {
.await
.expect("Failed to create a mock DB");
+ let merchant_id = common_utils::id_type::MerchantId::from("merchant_1".into()).unwrap();
+
let created_dispute = mockdb
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: merchant_id.clone(),
payment_id: "payment_1".into(),
connector_dispute_id: "connector_dispute_1".into(),
}))
@@ -443,6 +445,8 @@ mod tests {
#[tokio::test]
async fn test_find_by_merchant_id_payment_id_connector_dispute_id() {
+ let merchant_id = common_utils::id_type::MerchantId::from("merchant_1".into()).unwrap();
+
#[allow(clippy::expect_used)]
let mockdb = MockDb::new(&RedisSettings::default())
.await
@@ -452,7 +456,7 @@ mod tests {
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: merchant_id.clone(),
payment_id: "payment_1".into(),
connector_dispute_id: "connector_dispute_1".into(),
}))
@@ -463,7 +467,7 @@ mod tests {
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_2".into(),
attempt_id: "attempt_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: merchant_id.clone(),
payment_id: "payment_1".into(),
connector_dispute_id: "connector_dispute_2".into(),
}))
@@ -472,7 +476,7 @@ mod tests {
let found_dispute = mockdb
.find_by_merchant_id_payment_id_connector_dispute_id(
- "merchant_1",
+ &merchant_id,
"payment_1",
"connector_dispute_1",
)
@@ -486,6 +490,7 @@ mod tests {
#[tokio::test]
async fn test_find_dispute_by_merchant_id_dispute_id() {
+ let merchant_id = common_utils::id_type::MerchantId::from("merchant_1".into()).unwrap();
#[allow(clippy::expect_used)]
let mockdb = MockDb::new(&RedisSettings::default())
.await
@@ -495,7 +500,7 @@ mod tests {
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: merchant_id.clone(),
payment_id: "payment_1".into(),
connector_dispute_id: "connector_dispute_1".into(),
}))
@@ -506,7 +511,7 @@ mod tests {
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_2".into(),
attempt_id: "attempt_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: merchant_id.clone(),
payment_id: "payment_1".into(),
connector_dispute_id: "connector_dispute_1".into(),
}))
@@ -514,7 +519,7 @@ mod tests {
.unwrap();
let found_dispute = mockdb
- .find_dispute_by_merchant_id_dispute_id("merchant_1", "dispute_1")
+ .find_dispute_by_merchant_id_dispute_id(&merchant_id, "dispute_1")
.await
.unwrap();
@@ -523,6 +528,7 @@ mod tests {
#[tokio::test]
async fn test_find_disputes_by_merchant_id() {
+ let merchant_id = common_utils::id_type::MerchantId::from("merchant_2".into()).unwrap();
#[allow(clippy::expect_used)]
let mockdb = MockDb::new(&RedisSettings::default())
.await
@@ -532,7 +538,7 @@ mod tests {
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: merchant_id.clone(),
payment_id: "payment_1".into(),
connector_dispute_id: "connector_dispute_1".into(),
}))
@@ -543,7 +549,7 @@ mod tests {
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_2".into(),
attempt_id: "attempt_1".into(),
- merchant_id: "merchant_2".into(),
+ merchant_id: merchant_id.clone(),
payment_id: "payment_1".into(),
connector_dispute_id: "connector_dispute_1".into(),
}))
@@ -552,7 +558,7 @@ mod tests {
let found_disputes = mockdb
.find_disputes_by_merchant_id(
- "merchant_1",
+ &merchant_id,
DisputeListConstraints {
limit: None,
dispute_status: None,
@@ -577,6 +583,7 @@ mod tests {
#[tokio::test]
async fn test_find_disputes_by_merchant_id_payment_id() {
+ let merchant_id = common_utils::id_type::MerchantId::from("merchant_1".into()).unwrap();
#[allow(clippy::expect_used)]
let mockdb = MockDb::new(&RedisSettings::default())
.await
@@ -586,7 +593,7 @@ mod tests {
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: merchant_id.clone(),
payment_id: "payment_1".into(),
connector_dispute_id: "connector_dispute_1".into(),
}))
@@ -597,7 +604,7 @@ mod tests {
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_2".into(),
attempt_id: "attempt_1".into(),
- merchant_id: "merchant_2".into(),
+ merchant_id: merchant_id.clone(),
payment_id: "payment_1".into(),
connector_dispute_id: "connector_dispute_1".into(),
}))
@@ -605,7 +612,7 @@ mod tests {
.unwrap();
let found_disputes = mockdb
- .find_disputes_by_merchant_id_payment_id("merchant_1", "payment_1")
+ .find_disputes_by_merchant_id_payment_id(&merchant_id, "payment_1")
.await
.unwrap();
@@ -633,6 +640,8 @@ mod tests {
#[tokio::test]
async fn test_update_dispute_update() {
+ let merchant_id =
+ common_utils::id_type::MerchantId::from("merchant_1".into()).unwrap();
#[allow(clippy::expect_used)]
let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
.await
@@ -642,7 +651,7 @@ mod tests {
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: merchant_id.clone(),
payment_id: "payment_1".into(),
connector_dispute_id: "connector_dispute_1".into(),
}))
@@ -713,6 +722,8 @@ mod tests {
#[tokio::test]
async fn test_update_dispute_update_status() {
+ let merchant_id =
+ common_utils::id_type::MerchantId::from("merchant_1".into()).unwrap();
#[allow(clippy::expect_used)]
let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
.await
@@ -722,7 +733,7 @@ mod tests {
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: merchant_id.clone(),
payment_id: "payment_1".into(),
connector_dispute_id: "connector_dispute_1".into(),
}))
@@ -788,6 +799,8 @@ mod tests {
#[tokio::test]
async fn test_update_dispute_update_evidence() {
+ let merchant_id =
+ common_utils::id_type::MerchantId::from("merchant_1".into()).unwrap();
#[allow(clippy::expect_used)]
let mockdb = MockDb::new(&redis_interface::RedisSettings::default())
.await
@@ -797,7 +810,7 @@ mod tests {
.insert_dispute(create_dispute_new(DisputeNewIds {
dispute_id: "dispute_1".into(),
attempt_id: "attempt_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: merchant_id.clone(),
payment_id: "payment_1".into(),
connector_dispute_id: "connector_dispute_1".into(),
}))
diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rs
index 2fd8a09f173..4cb05ba5ba0 100644
--- a/crates/router/src/db/events.rs
+++ b/crates/router/src/db/events.rs
@@ -31,7 +31,7 @@ where
async fn find_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError>;
@@ -39,7 +39,7 @@ where
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
@@ -48,7 +48,7 @@ where
async fn list_initial_events_by_merchant_id_constraints(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
created_after: Option<time::PrimitiveDateTime>,
created_before: Option<time::PrimitiveDateTime>,
limit: Option<i64>,
@@ -59,7 +59,7 @@ where
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError>;
@@ -95,7 +95,7 @@ where
async fn update_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
event: domain::EventUpdate,
merchant_key_store: &domain::MerchantKeyStore,
@@ -122,7 +122,7 @@ impl EventInterface for Store {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -132,7 +132,7 @@ impl EventInterface for Store {
async fn find_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
@@ -143,7 +143,7 @@ impl EventInterface for Store {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -153,7 +153,7 @@ impl EventInterface for Store {
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
@@ -173,7 +173,7 @@ impl EventInterface for Store {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
@@ -188,7 +188,7 @@ impl EventInterface for Store {
async fn list_initial_events_by_merchant_id_constraints(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
created_after: Option<time::PrimitiveDateTime>,
created_before: Option<time::PrimitiveDateTime>,
limit: Option<i64>,
@@ -214,7 +214,7 @@ impl EventInterface for Store {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
@@ -229,7 +229,7 @@ impl EventInterface for Store {
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
@@ -249,7 +249,7 @@ impl EventInterface for Store {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
@@ -284,7 +284,7 @@ impl EventInterface for Store {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
@@ -325,7 +325,9 @@ impl EventInterface for Store {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ common_utils::types::keymanager::Identifier::Merchant(
+ merchant_key_store.merchant_id.clone(),
+ ),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
@@ -356,7 +358,7 @@ impl EventInterface for Store {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
@@ -371,7 +373,7 @@ impl EventInterface for Store {
async fn update_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
event: domain::EventUpdate,
merchant_key_store: &domain::MerchantKeyStore,
@@ -383,7 +385,7 @@ impl EventInterface for Store {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -410,7 +412,7 @@ impl EventInterface for MockDb {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -419,7 +421,7 @@ impl EventInterface for MockDb {
async fn find_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
@@ -435,7 +437,7 @@ impl EventInterface for MockDb {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -444,7 +446,7 @@ impl EventInterface for MockDb {
.transpose()?
.ok_or(
errors::StorageError::ValueNotFound(format!(
- "No event available with merchant_id = {merchant_id} and event_id = {event_id}"
+ "No event available with merchant_id = {merchant_id:?} and event_id = {event_id}"
))
.into(),
)
@@ -453,7 +455,7 @@ impl EventInterface for MockDb {
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
@@ -475,7 +477,7 @@ impl EventInterface for MockDb {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
@@ -488,7 +490,7 @@ impl EventInterface for MockDb {
async fn list_initial_events_by_merchant_id_constraints(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
created_after: Option<time::PrimitiveDateTime>,
created_before: Option<time::PrimitiveDateTime>,
limit: Option<i64>,
@@ -545,7 +547,7 @@ impl EventInterface for MockDb {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
@@ -558,7 +560,7 @@ impl EventInterface for MockDb {
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
@@ -578,7 +580,7 @@ impl EventInterface for MockDb {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
@@ -613,7 +615,7 @@ impl EventInterface for MockDb {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
@@ -683,7 +685,7 @@ impl EventInterface for MockDb {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
@@ -716,7 +718,7 @@ impl EventInterface for MockDb {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?;
@@ -729,7 +731,7 @@ impl EventInterface for MockDb {
async fn update_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
event_id: &str,
event: domain::EventUpdate,
merchant_key_store: &domain::MerchantKeyStore,
@@ -757,7 +759,7 @@ impl EventInterface for MockDb {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -804,7 +806,7 @@ mod tests {
let state = &Arc::new(app_state)
.get_session_state("public", || {})
.unwrap();
- let merchant_id = "merchant1";
+ let merchant_id = common_utils::id_type::MerchantId::from("merchant_1".into()).unwrap();
let business_profile_id = "profile1";
let payment_id = "test_payment_id";
let key_manager_state = &state.into();
@@ -813,11 +815,11 @@ mod tests {
.insert_merchant_key_store(
key_manager_state,
domain::MerchantKeyStore {
- merchant_id: merchant_id.into(),
+ merchant_id: merchant_id.clone(),
key: domain::types::encrypt(
key_manager_state,
services::generate_aes256_key().unwrap().to_vec().into(),
- Identifier::Merchant(merchant_id.to_string()),
+ Identifier::Merchant(merchant_id.to_owned()),
master_key,
)
.await
@@ -831,7 +833,7 @@ mod tests {
let merchant_key_store = mockdb
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- merchant_id,
+ &merchant_id,
&master_key.to_vec().into(),
)
.await
@@ -870,7 +872,7 @@ mod tests {
let updated_event = mockdb
.update_event_by_merchant_id_event_id(
key_manager_state,
- merchant_id,
+ &merchant_id,
event_id,
domain::EventUpdate::UpdateResponse {
is_webhook_notified: true,
diff --git a/crates/router/src/db/file.rs b/crates/router/src/db/file.rs
index da28404971d..f81afa8d838 100644
--- a/crates/router/src/db/file.rs
+++ b/crates/router/src/db/file.rs
@@ -17,13 +17,13 @@ pub trait FileMetadataInterface {
async fn find_file_metadata_by_merchant_id_file_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> CustomResult<storage::FileMetadata, errors::StorageError>;
async fn delete_file_metadata_by_merchant_id_file_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> CustomResult<bool, errors::StorageError>;
@@ -50,7 +50,7 @@ impl FileMetadataInterface for Store {
#[instrument(skip_all)]
async fn find_file_metadata_by_merchant_id_file_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> CustomResult<storage::FileMetadata, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -62,7 +62,7 @@ impl FileMetadataInterface for Store {
#[instrument(skip_all)]
async fn delete_file_metadata_by_merchant_id_file_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
file_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -96,7 +96,7 @@ impl FileMetadataInterface for MockDb {
async fn find_file_metadata_by_merchant_id_file_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_file_id: &str,
) -> CustomResult<storage::FileMetadata, errors::StorageError> {
// TODO: Implement function for `MockDb`
@@ -105,7 +105,7 @@ impl FileMetadataInterface for MockDb {
async fn delete_file_metadata_by_merchant_id_file_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_file_id: &str,
) -> CustomResult<bool, errors::StorageError> {
// TODO: Implement function for `MockDb`
diff --git a/crates/router/src/db/fraud_check.rs b/crates/router/src/db/fraud_check.rs
index 9e27f451019..20e3bfb32aa 100644
--- a/crates/router/src/db/fraud_check.rs
+++ b/crates/router/src/db/fraud_check.rs
@@ -25,13 +25,13 @@ pub trait FraudCheckInterface {
async fn find_fraud_check_by_payment_id(
&self,
payment_id: String,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
) -> CustomResult<FraudCheck, errors::StorageError>;
async fn find_fraud_check_by_payment_id_if_present(
&self,
payment_id: String,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
) -> CustomResult<Option<FraudCheck>, errors::StorageError>;
}
@@ -64,7 +64,7 @@ impl FraudCheckInterface for Store {
async fn find_fraud_check_by_payment_id(
&self,
payment_id: String,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
) -> CustomResult<FraudCheck, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
FraudCheck::get_with_payment_id(&conn, payment_id, merchant_id)
@@ -76,7 +76,7 @@ impl FraudCheckInterface for Store {
async fn find_fraud_check_by_payment_id_if_present(
&self,
payment_id: String,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
) -> CustomResult<Option<FraudCheck>, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
FraudCheck::get_with_payment_id_if_present(&conn, payment_id, merchant_id)
@@ -103,7 +103,7 @@ impl FraudCheckInterface for MockDb {
async fn find_fraud_check_by_payment_id(
&self,
_payment_id: String,
- _merchant_id: String,
+ _merchant_id: common_utils::id_type::MerchantId,
) -> CustomResult<FraudCheck, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
@@ -111,7 +111,7 @@ impl FraudCheckInterface for MockDb {
async fn find_fraud_check_by_payment_id_if_present(
&self,
_payment_id: String,
- _merchant_id: String,
+ _merchant_id: common_utils::id_type::MerchantId,
) -> CustomResult<Option<FraudCheck>, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 030af82dc92..003f3ff4845 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -160,7 +160,7 @@ impl AddressInterface for KafkaStore {
async fn find_address_by_merchant_id_payment_id_address_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_id: &str,
address_id: &str,
key_store: &domain::MerchantKeyStore,
@@ -193,7 +193,7 @@ impl AddressInterface for KafkaStore {
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
address: storage::AddressUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Address>, errors::StorageError> {
@@ -220,7 +220,7 @@ impl ApiKeyInterface for KafkaStore {
async fn update_api_key(
&self,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
key_id: String,
api_key: storage::ApiKeyUpdate,
) -> CustomResult<storage::ApiKey, errors::StorageError> {
@@ -231,7 +231,7 @@ impl ApiKeyInterface for KafkaStore {
async fn revoke_api_key(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_id: &str,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store.revoke_api_key(merchant_id, key_id).await
@@ -239,7 +239,7 @@ impl ApiKeyInterface for KafkaStore {
async fn find_api_key_by_merchant_id_key_id_optional(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_id: &str,
) -> CustomResult<Option<storage::ApiKey>, errors::StorageError> {
self.diesel_store
@@ -258,7 +258,7 @@ impl ApiKeyInterface for KafkaStore {
async fn list_api_keys_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
limit: Option<i64>,
offset: Option<i64>,
) -> CustomResult<Vec<storage::ApiKey>, errors::StorageError> {
@@ -344,7 +344,7 @@ impl CustomerInterface for KafkaStore {
async fn delete_customer_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_customer_by_customer_id_merchant_id(customer_id, merchant_id)
@@ -355,7 +355,7 @@ impl CustomerInterface for KafkaStore {
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
@@ -374,7 +374,7 @@ impl CustomerInterface for KafkaStore {
&self,
state: &KeyManagerState,
customer_id: id_type::CustomerId,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
customer: domain::Customer,
customer_update: storage::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
@@ -396,7 +396,7 @@ impl CustomerInterface for KafkaStore {
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Customer>, errors::StorageError> {
self.diesel_store
@@ -408,7 +408,7 @@ impl CustomerInterface for KafkaStore {
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
@@ -457,7 +457,7 @@ impl DisputeInterface for KafkaStore {
async fn find_by_merchant_id_payment_id_connector_dispute_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_id: &str,
connector_dispute_id: &str,
) -> CustomResult<Option<storage::Dispute>, errors::StorageError> {
@@ -472,7 +472,7 @@ impl DisputeInterface for KafkaStore {
async fn find_dispute_by_merchant_id_dispute_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
dispute_id: &str,
) -> CustomResult<storage::Dispute, errors::StorageError> {
self.diesel_store
@@ -482,7 +482,7 @@ impl DisputeInterface for KafkaStore {
async fn find_disputes_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
dispute_constraints: api_models::disputes::DisputeListConstraints,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
self.diesel_store
@@ -512,7 +512,7 @@ impl DisputeInterface for KafkaStore {
async fn find_disputes_by_merchant_id_payment_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_id: &str,
) -> CustomResult<Vec<storage::Dispute>, errors::StorageError> {
self.diesel_store
@@ -560,7 +560,7 @@ impl EventInterface for KafkaStore {
async fn find_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
event_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Event, errors::StorageError> {
@@ -572,7 +572,7 @@ impl EventInterface for KafkaStore {
async fn list_initial_events_by_merchant_id_primary_object_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
primary_object_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
@@ -589,7 +589,7 @@ impl EventInterface for KafkaStore {
async fn list_initial_events_by_merchant_id_constraints(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
created_after: Option<PrimitiveDateTime>,
created_before: Option<PrimitiveDateTime>,
limit: Option<i64>,
@@ -612,7 +612,7 @@ impl EventInterface for KafkaStore {
async fn list_events_by_merchant_id_initial_attempt_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
initial_attempt_id: &str,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::Event>, errors::StorageError> {
@@ -686,7 +686,7 @@ impl EventInterface for KafkaStore {
async fn update_event_by_merchant_id_event_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
event_id: &str,
event: domain::EventUpdate,
merchant_key_store: &domain::MerchantKeyStore,
@@ -731,7 +731,7 @@ impl LockerMockUpInterface for KafkaStore {
impl MandateInterface for KafkaStore {
async fn find_mandate_by_merchant_id_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Mandate, errors::StorageError> {
@@ -742,7 +742,7 @@ impl MandateInterface for KafkaStore {
async fn find_mandate_by_merchant_id_connector_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
connector_mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Mandate, errors::StorageError> {
@@ -757,7 +757,7 @@ impl MandateInterface for KafkaStore {
async fn find_mandate_by_merchant_id_customer_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> {
self.diesel_store
@@ -767,7 +767,7 @@ impl MandateInterface for KafkaStore {
async fn update_mandate_by_merchant_id_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_id: &str,
mandate_update: storage::MandateUpdate,
mandate: storage::Mandate,
@@ -786,7 +786,7 @@ impl MandateInterface for KafkaStore {
async fn find_mandates_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<storage::Mandate>, errors::StorageError> {
self.diesel_store
@@ -827,7 +827,7 @@ impl PaymentLinkInterface for KafkaStore {
async fn list_payment_link_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_link_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> {
self.diesel_store
@@ -852,7 +852,7 @@ impl MerchantAccountInterface for KafkaStore {
async fn find_merchant_account_by_merchant_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
self.diesel_store
@@ -875,7 +875,7 @@ impl MerchantAccountInterface for KafkaStore {
async fn update_specific_fields_in_merchant(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
merchant_account: storage::MerchantAccountUpdate,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
@@ -916,7 +916,7 @@ impl MerchantAccountInterface for KafkaStore {
async fn delete_merchant_account_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_merchant_account_by_merchant_id(merchant_id)
@@ -927,7 +927,7 @@ impl MerchantAccountInterface for KafkaStore {
async fn list_multiple_merchant_accounts(
&self,
state: &KeyManagerState,
- merchant_ids: Vec<String>,
+ merchant_ids: Vec<id_type::MerchantId>,
) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> {
self.diesel_store
.list_multiple_merchant_accounts(state, merchant_ids)
@@ -939,7 +939,7 @@ impl MerchantAccountInterface for KafkaStore {
impl ConnectorAccessToken for KafkaStore {
async fn get_access_token(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
merchant_connector_id: &str,
) -> CustomResult<Option<AccessToken>, errors::StorageError> {
self.diesel_store
@@ -949,7 +949,7 @@ impl ConnectorAccessToken for KafkaStore {
async fn set_access_token(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
merchant_connector_id: &str,
access_token: AccessToken,
) -> CustomResult<(), errors::StorageError> {
@@ -970,7 +970,7 @@ impl FileMetadataInterface for KafkaStore {
async fn find_file_metadata_by_merchant_id_file_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
file_id: &str,
) -> CustomResult<storage::FileMetadata, errors::StorageError> {
self.diesel_store
@@ -980,7 +980,7 @@ impl FileMetadataInterface for KafkaStore {
async fn delete_file_metadata_by_merchant_id_file_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
file_id: &str,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
@@ -1015,7 +1015,7 @@ impl MerchantConnectorAccountInterface for KafkaStore {
async fn find_merchant_connector_account_by_merchant_id_connector_label(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
connector: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
@@ -1032,7 +1032,7 @@ impl MerchantConnectorAccountInterface for KafkaStore {
async fn find_merchant_connector_account_by_merchant_id_connector_name(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
connector_name: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
@@ -1077,7 +1077,7 @@ impl MerchantConnectorAccountInterface for KafkaStore {
async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
merchant_connector_id: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
@@ -1094,7 +1094,7 @@ impl MerchantConnectorAccountInterface for KafkaStore {
async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
get_disabled: bool,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
@@ -1122,7 +1122,7 @@ impl MerchantConnectorAccountInterface for KafkaStore {
async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
merchant_connector_id: &str,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
@@ -1239,7 +1239,7 @@ impl PaymentAttemptInterface for KafkaStore {
&self,
connector_transaction_id: &str,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> {
self.diesel_store
@@ -1254,7 +1254,7 @@ impl PaymentAttemptInterface for KafkaStore {
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
connector_txn_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> {
@@ -1270,7 +1270,7 @@ impl PaymentAttemptInterface for KafkaStore {
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
attempt_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> {
@@ -1287,7 +1287,7 @@ impl PaymentAttemptInterface for KafkaStore {
async fn find_payment_attempt_by_attempt_id_merchant_id(
&self,
attempt_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> {
self.diesel_store
@@ -1298,7 +1298,7 @@ impl PaymentAttemptInterface for KafkaStore {
async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> {
self.diesel_store
@@ -1313,7 +1313,7 @@ impl PaymentAttemptInterface for KafkaStore {
async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> {
self.diesel_store
@@ -1328,7 +1328,7 @@ impl PaymentAttemptInterface for KafkaStore {
async fn find_payment_attempt_by_preprocessing_id_merchant_id(
&self,
preprocessing_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentAttempt, errors::DataStorageError> {
self.diesel_store
@@ -1343,7 +1343,7 @@ impl PaymentAttemptInterface for KafkaStore {
async fn get_filters_for_payments(
&self,
pi: &[hyperswitch_domain_models::payments::PaymentIntent],
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<
hyperswitch_domain_models::payments::payment_attempt::PaymentListFilters,
@@ -1356,7 +1356,7 @@ impl PaymentAttemptInterface for KafkaStore {
async fn get_total_count_of_filtered_payment_attempts(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<api_models::enums::Connector>>,
payment_method: Option<Vec<common_enums::PaymentMethod>>,
@@ -1381,7 +1381,7 @@ impl PaymentAttemptInterface for KafkaStore {
async fn find_attempts_by_merchant_id_payment_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::PaymentAttempt>, errors::DataStorageError> {
@@ -1451,7 +1451,7 @@ impl PaymentIntentInterface for KafkaStore {
&self,
state: &KeyManagerState,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PaymentIntent, errors::DataStorageError> {
@@ -1470,7 +1470,7 @@ impl PaymentIntentInterface for KafkaStore {
async fn filter_payment_intent_by_constraints(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
@@ -1490,7 +1490,7 @@ impl PaymentIntentInterface for KafkaStore {
async fn filter_payment_intents_by_time_range_constraints(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
time_range: &api_models::payments::TimeRange,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
@@ -1510,7 +1510,7 @@ impl PaymentIntentInterface for KafkaStore {
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
@@ -1535,7 +1535,7 @@ impl PaymentIntentInterface for KafkaStore {
#[cfg(feature = "olap")]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<String>, errors::DataStorageError> {
@@ -1574,7 +1574,7 @@ impl PaymentMethodInterface for KafkaStore {
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
limit: Option<i64>,
) -> CustomResult<Vec<storage::PaymentMethod>, errors::StorageError> {
self.diesel_store
@@ -1585,7 +1585,7 @@ impl PaymentMethodInterface for KafkaStore {
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
@@ -1604,7 +1604,7 @@ impl PaymentMethodInterface for KafkaStore {
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
self.diesel_store
@@ -1649,7 +1649,7 @@ impl PaymentMethodInterface for KafkaStore {
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_method_id: &str,
) -> CustomResult<storage::PaymentMethod, errors::StorageError> {
self.diesel_store
@@ -1666,7 +1666,7 @@ impl PayoutAttemptInterface for KafkaStore {}
impl PayoutAttemptInterface for KafkaStore {
async fn find_payout_attempt_by_merchant_id_payout_attempt_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payout_attempt_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PayoutAttempt, errors::DataStorageError> {
@@ -1681,7 +1681,7 @@ impl PayoutAttemptInterface for KafkaStore {
async fn find_payout_attempt_by_merchant_id_connector_payout_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
connector_payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::PayoutAttempt, errors::DataStorageError> {
@@ -1748,7 +1748,7 @@ impl PayoutAttemptInterface for KafkaStore {
async fn get_filters_for_payouts(
&self,
payouts: &[hyperswitch_domain_models::payouts::payouts::Payouts],
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<
hyperswitch_domain_models::payouts::payout_attempt::PayoutListFilters,
@@ -1768,7 +1768,7 @@ impl PayoutsInterface for KafkaStore {}
impl PayoutsInterface for KafkaStore {
async fn find_payout_by_merchant_id_payout_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Payouts, errors::DataStorageError> {
@@ -1814,7 +1814,7 @@ impl PayoutsInterface for KafkaStore {
async fn find_optional_payout_by_merchant_id_payout_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<storage::Payouts>, errors::DataStorageError> {
@@ -1826,7 +1826,7 @@ impl PayoutsInterface for KafkaStore {
#[cfg(feature = "olap")]
async fn filter_payouts_by_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::Payouts>, errors::DataStorageError> {
@@ -1838,7 +1838,7 @@ impl PayoutsInterface for KafkaStore {
#[cfg(feature = "olap")]
async fn filter_payouts_and_attempts(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<
@@ -1857,7 +1857,7 @@ impl PayoutsInterface for KafkaStore {
#[cfg(feature = "olap")]
async fn filter_payouts_by_time_range_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
time_range: &api_models::payments::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::Payouts>, errors::DataStorageError> {
@@ -1975,7 +1975,7 @@ impl CaptureInterface for KafkaStore {
async fn find_all_captures_by_merchant_id_payment_id_authorized_attempt_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_id: &str,
authorized_attempt_id: &str,
storage_scheme: MerchantStorageScheme,
@@ -1996,7 +1996,7 @@ impl RefundInterface for KafkaStore {
async fn find_refund_by_internal_reference_id_merchant_id(
&self,
internal_reference_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Refund, errors::StorageError> {
self.diesel_store
@@ -2011,7 +2011,7 @@ impl RefundInterface for KafkaStore {
async fn find_refund_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::Refund>, errors::StorageError> {
self.diesel_store
@@ -2021,7 +2021,7 @@ impl RefundInterface for KafkaStore {
async fn find_refund_by_merchant_id_refund_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
refund_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage::Refund, errors::StorageError> {
@@ -2032,7 +2032,7 @@ impl RefundInterface for KafkaStore {
async fn find_refund_by_merchant_id_connector_refund_id_connector(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
connector_refund_id: &str,
connector: &str,
storage_scheme: MerchantStorageScheme,
@@ -2070,7 +2070,7 @@ impl RefundInterface for KafkaStore {
async fn find_refund_by_merchant_id_connector_transaction_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
connector_transaction_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<storage::Refund>, errors::StorageError> {
@@ -2103,7 +2103,7 @@ impl RefundInterface for KafkaStore {
#[cfg(feature = "olap")]
async fn filter_refund_by_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
refund_details: &api_models::refunds::RefundListRequest,
storage_scheme: MerchantStorageScheme,
limit: i64,
@@ -2123,7 +2123,7 @@ impl RefundInterface for KafkaStore {
#[cfg(feature = "olap")]
async fn filter_refund_by_meta_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
refund_details: &api_models::payments::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> {
@@ -2135,7 +2135,7 @@ impl RefundInterface for KafkaStore {
#[cfg(feature = "olap")]
async fn get_total_count_of_refunds(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
refund_details: &api_models::refunds::RefundListRequest,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
@@ -2161,7 +2161,7 @@ impl MerchantKeyStoreInterface for KafkaStore {
async fn get_merchant_key_store_by_merchant_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> {
self.diesel_store
@@ -2171,7 +2171,7 @@ impl MerchantKeyStoreInterface for KafkaStore {
async fn delete_merchant_key_store_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_merchant_key_store_by_merchant_id(merchant_id)
@@ -2182,7 +2182,7 @@ impl MerchantKeyStoreInterface for KafkaStore {
async fn list_multiple_key_stores(
&self,
state: &KeyManagerState,
- merchant_ids: Vec<String>,
+ merchant_ids: Vec<id_type::MerchantId>,
key: &Secret<Vec<u8>>,
) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> {
self.diesel_store
@@ -2235,7 +2235,7 @@ impl BusinessProfileInterface for KafkaStore {
async fn delete_business_profile_by_profile_id_merchant_id(
&self,
profile_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_business_profile_by_profile_id_merchant_id(profile_id, merchant_id)
@@ -2244,7 +2244,7 @@ impl BusinessProfileInterface for KafkaStore {
async fn list_business_profile_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<Vec<business_profile::BusinessProfile>, errors::StorageError> {
self.diesel_store
.list_business_profile_by_merchant_id(merchant_id)
@@ -2254,7 +2254,7 @@ impl BusinessProfileInterface for KafkaStore {
async fn find_business_profile_by_profile_name_merchant_id(
&self,
profile_name: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<business_profile::BusinessProfile, errors::StorageError> {
self.diesel_store
.find_business_profile_by_profile_name_merchant_id(profile_name, merchant_id)
@@ -2309,7 +2309,7 @@ impl RoutingAlgorithmInterface for KafkaStore {
async fn find_routing_algorithm_by_algorithm_id_merchant_id(
&self,
algorithm_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<storage::RoutingAlgorithm, errors::StorageError> {
self.diesel_store
.find_routing_algorithm_by_algorithm_id_merchant_id(algorithm_id, merchant_id)
@@ -2339,7 +2339,7 @@ impl RoutingAlgorithmInterface for KafkaStore {
async fn list_routing_algorithm_metadata_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::RoutingProfileMetadata>, errors::StorageError> {
@@ -2350,7 +2350,7 @@ impl RoutingAlgorithmInterface for KafkaStore {
async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
transaction_type: &enums::TransactionType,
limit: i64,
offset: i64,
@@ -2542,7 +2542,7 @@ impl UserRoleInterface for KafkaStore {
async fn find_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<user_storage::UserRole, errors::StorageError> {
self.diesel_store
.find_user_role_by_user_id_merchant_id(user_id, merchant_id)
@@ -2552,7 +2552,7 @@ impl UserRoleInterface for KafkaStore {
async fn update_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
update: user_storage::UserRoleUpdate,
) -> CustomResult<user_storage::UserRole, errors::StorageError> {
self.diesel_store
@@ -2574,7 +2574,7 @@ impl UserRoleInterface for KafkaStore {
async fn delete_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<user_storage::UserRole, errors::StorageError> {
self.diesel_store
.delete_user_role_by_user_id_merchant_id(user_id, merchant_id)
@@ -2601,10 +2601,10 @@ impl UserRoleInterface for KafkaStore {
async fn list_user_roles_by_merchant_id(
&self,
- user_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<Vec<user_storage::UserRole>, errors::StorageError> {
self.diesel_store
- .list_user_roles_by_merchant_id(user_id)
+ .list_user_roles_by_merchant_id(merchant_id)
.await
}
}
@@ -2621,7 +2621,7 @@ impl DashboardMetadataInterface for KafkaStore {
async fn update_metadata(
&self,
user_id: Option<String>,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
data_key: enums::DashboardMetadata,
dashboard_metadata_update: storage::DashboardMetadataUpdate,
@@ -2640,7 +2640,7 @@ impl DashboardMetadataInterface for KafkaStore {
async fn find_user_scoped_dashboard_metadata(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
@@ -2651,7 +2651,7 @@ impl DashboardMetadataInterface for KafkaStore {
async fn find_merchant_scoped_dashboard_metadata(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
data_keys: Vec<enums::DashboardMetadata>,
) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {
@@ -2663,7 +2663,7 @@ impl DashboardMetadataInterface for KafkaStore {
async fn delete_all_user_scoped_dashboard_metadata_by_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_all_user_scoped_dashboard_metadata_by_merchant_id(user_id, merchant_id)
@@ -2673,7 +2673,7 @@ impl DashboardMetadataInterface for KafkaStore {
async fn delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
data_key: enums::DashboardMetadata,
) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {
self.diesel_store
@@ -2754,7 +2754,7 @@ impl BatchSampleDataInterface for KafkaStore {
async fn delete_payment_intents_for_sample_data(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
key_store: &hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,
) -> CustomResult<
Vec<hyperswitch_domain_models::payments::PaymentIntent>,
@@ -2776,7 +2776,7 @@ impl BatchSampleDataInterface for KafkaStore {
async fn delete_payment_attempts_for_sample_data(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<
Vec<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>,
hyperswitch_domain_models::errors::StorageError,
@@ -2798,7 +2798,7 @@ impl BatchSampleDataInterface for KafkaStore {
async fn delete_refunds_for_sample_data(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<Vec<diesel_models::Refund>, hyperswitch_domain_models::errors::StorageError>
{
let refunds_list = self
@@ -2828,7 +2828,7 @@ impl AuthorizationInterface for KafkaStore {
async fn find_all_authorizations_by_merchant_id_payment_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_id: &str,
) -> CustomResult<Vec<storage::Authorization>, errors::StorageError> {
self.diesel_store
@@ -2838,7 +2838,7 @@ impl AuthorizationInterface for KafkaStore {
async fn update_authorization_by_merchant_id_authorization_id(
&self,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
authorization_id: String,
authorization: storage::AuthorizationUpdate,
) -> CustomResult<storage::Authorization, errors::StorageError> {
@@ -2876,7 +2876,7 @@ impl AuthenticationInterface for KafkaStore {
async fn find_authentication_by_merchant_id_authentication_id(
&self,
- merchant_id: String,
+ merchant_id: &id_type::MerchantId,
authentication_id: String,
) -> CustomResult<storage::Authentication, errors::StorageError> {
self.diesel_store
@@ -2886,7 +2886,7 @@ impl AuthenticationInterface for KafkaStore {
async fn find_authentication_by_merchant_id_connector_authentication_id(
&self,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
connector_authentication_id: String,
) -> CustomResult<storage::Authentication, errors::StorageError> {
self.diesel_store
@@ -2948,7 +2948,7 @@ impl RoleInterface for KafkaStore {
async fn find_role_by_role_id_in_merchant_scope(
&self,
role_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> CustomResult<storage::Role, errors::StorageError> {
self.diesel_store
@@ -2975,7 +2975,7 @@ impl RoleInterface for KafkaStore {
async fn list_all_roles(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
self.diesel_store.list_all_roles(merchant_id, org_id).await
diff --git a/crates/router/src/db/locker_mock_up.rs b/crates/router/src/db/locker_mock_up.rs
index 0fb675025c9..abae3fe2468 100644
--- a/crates/router/src/db/locker_mock_up.rs
+++ b/crates/router/src/db/locker_mock_up.rs
@@ -141,7 +141,7 @@ mod tests {
pub struct LockerMockUpIds {
card_id: String,
external_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
customer_id: id_type::CustomerId,
}
@@ -175,7 +175,7 @@ mod tests {
.insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds {
card_id: "card_1".into(),
external_id: "external_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: id_type::MerchantId::default(),
customer_id: generate_customer_id_of_default_length(),
}))
.await
@@ -185,7 +185,7 @@ mod tests {
.insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds {
card_id: "card_2".into(),
external_id: "external_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: id_type::MerchantId::default(),
customer_id: generate_customer_id_of_default_length(),
}))
.await;
@@ -206,7 +206,7 @@ mod tests {
.insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds {
card_id: "card_1".into(),
external_id: "external_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: id_type::MerchantId::default(),
customer_id: generate_customer_id_of_default_length(),
}))
.await
@@ -236,7 +236,7 @@ mod tests {
.insert_locker_mock_up(create_locker_mock_up_new(LockerMockUpIds {
card_id: "card_1".into(),
external_id: "external_1".into(),
- merchant_id: "merchant_1".into(),
+ merchant_id: id_type::MerchantId::default(),
customer_id: generate_customer_id_of_default_length(),
}))
.await
diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rs
index e69e3318ae6..bdc51c8ad8b 100644
--- a/crates/router/src/db/mandate.rs
+++ b/crates/router/src/db/mandate.rs
@@ -11,27 +11,27 @@ use crate::{
pub trait MandateInterface {
async fn find_mandate_by_merchant_id_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError>;
async fn find_mandate_by_merchant_id_connector_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
connector_mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError>;
async fn find_mandate_by_merchant_id_customer_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>;
async fn update_mandate_by_merchant_id_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_id: &str,
mandate_update: storage_types::MandateUpdate,
mandate: storage_types::Mandate,
@@ -40,7 +40,7 @@ pub trait MandateInterface {
async fn find_mandates_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError>;
@@ -77,7 +77,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_mandate_by_merchant_id_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
@@ -123,7 +123,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_mandate_by_merchant_id_connector_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
connector_mandate_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
@@ -143,8 +143,11 @@ mod storage {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
- let lookup_id =
- format!("mid_{}_conn_mandate_{}", merchant_id, connector_mandate_id);
+ let lookup_id = format!(
+ "mid_{}_conn_mandate_{}",
+ merchant_id.get_string_repr(),
+ connector_mandate_id
+ );
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
@@ -175,7 +178,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_mandate_by_merchant_id_customer_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -187,7 +190,7 @@ mod storage {
#[instrument(skip_all)]
async fn update_mandate_by_merchant_id_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_id: &str,
mandate_update: storage_types::MandateUpdate,
mandate: storage_types::Mandate,
@@ -227,7 +230,11 @@ mod storage {
let rev_lookup = diesel_models::ReverseLookupNew {
sk_id: field.clone(),
pk_id: key_str.clone(),
- lookup_id: format!("mid_{}_conn_mandate_{}", merchant_id, val),
+ lookup_id: format!(
+ "mid_{}_conn_mandate_{}",
+ merchant_id.get_string_repr(),
+ val
+ ),
source: "mandate".to_string(),
updated_by: storage_scheme.to_string(),
};
@@ -271,7 +278,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_mandates_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -301,11 +308,11 @@ mod storage {
.map_err(|error| report!(errors::StorageError::from(error))),
MerchantStorageScheme::RedisKv => {
let mandate_id = mandate.mandate_id.clone();
- let merchant_id = mandate.merchant_id.clone();
+ let merchant_id = &mandate.merchant_id.to_owned();
let connector_mandate_id = mandate.connector_mandate_id.clone();
let key = PartitionKey::MerchantIdMandateId {
- merchant_id: merchant_id.as_str(),
+ merchant_id,
mandate_id: mandate_id.as_str(),
};
let key_str = key.to_string();
@@ -320,8 +327,11 @@ mod storage {
};
if let Some(connector_val) = connector_mandate_id {
- let lookup_id =
- format!("mid_{}_conn_mandate_{}", merchant_id, connector_val);
+ let lookup_id = format!(
+ "mid_{}_conn_mandate_{}",
+ merchant_id.get_string_repr(),
+ connector_val
+ );
let reverse_lookup_entry = diesel_models::ReverseLookupNew {
sk_id: field.clone(),
@@ -381,7 +391,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_mandate_by_merchant_id_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
@@ -394,7 +404,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_mandate_by_merchant_id_connector_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
connector_mandate_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
@@ -411,7 +421,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_mandate_by_merchant_id_customer_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -423,7 +433,7 @@ mod storage {
#[instrument(skip_all)]
async fn update_mandate_by_merchant_id_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_id: &str,
mandate_update: storage_types::MandateUpdate,
_mandate: storage_types::Mandate,
@@ -443,7 +453,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_mandates_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -471,7 +481,7 @@ mod storage {
impl MandateInterface for MockDb {
async fn find_mandate_by_merchant_id_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
@@ -479,7 +489,7 @@ impl MandateInterface for MockDb {
.lock()
.await
.iter()
- .find(|mandate| mandate.merchant_id == merchant_id && mandate.mandate_id == mandate_id)
+ .find(|mandate| mandate.merchant_id == *merchant_id && mandate.mandate_id == mandate_id)
.cloned()
.ok_or_else(|| errors::StorageError::ValueNotFound("mandate not found".to_string()))
.map_err(|err| err.into())
@@ -487,7 +497,7 @@ impl MandateInterface for MockDb {
async fn find_mandate_by_merchant_id_connector_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
connector_mandate_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<storage_types::Mandate, errors::StorageError> {
@@ -496,7 +506,7 @@ impl MandateInterface for MockDb {
.await
.iter()
.find(|mandate| {
- mandate.merchant_id == merchant_id
+ mandate.merchant_id == *merchant_id
&& mandate.connector_mandate_id == Some(connector_mandate_id.to_string())
})
.cloned()
@@ -506,7 +516,7 @@ impl MandateInterface for MockDb {
async fn find_mandate_by_merchant_id_customer_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
return Ok(self
@@ -515,7 +525,7 @@ impl MandateInterface for MockDb {
.await
.iter()
.filter(|mandate| {
- mandate.merchant_id == merchant_id && &mandate.customer_id == customer_id
+ mandate.merchant_id == *merchant_id && &mandate.customer_id == customer_id
})
.cloned()
.collect());
@@ -523,7 +533,7 @@ impl MandateInterface for MockDb {
async fn update_mandate_by_merchant_id_mandate_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_id: &str,
mandate_update: storage_types::MandateUpdate,
_mandate: storage_types::Mandate,
@@ -532,7 +542,7 @@ impl MandateInterface for MockDb {
let mut mandates = self.mandates.lock().await;
match mandates
.iter_mut()
- .find(|mandate| mandate.merchant_id == merchant_id && mandate.mandate_id == mandate_id)
+ .find(|mandate| mandate.merchant_id == *merchant_id && mandate.mandate_id == mandate_id)
{
Some(mandate) => {
let m_update = diesel_models::MandateUpdateInternal::from(mandate_update);
@@ -547,12 +557,12 @@ impl MandateInterface for MockDb {
async fn find_mandates_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
mandate_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<storage_types::Mandate>, errors::StorageError> {
let mandates = self.mandates.lock().await;
let mandates_iter = mandates.iter().filter(|mandate| {
- let mut checker = mandate.merchant_id == merchant_id;
+ let mut checker = mandate.merchant_id == *merchant_id;
if let Some(created_time) = mandate_constraints.created_time {
checker &= mandate.created_at == created_time;
}
diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rs
index ae5ca360177..1907b9bdea8 100644
--- a/crates/router/src/db/merchant_account.rs
+++ b/crates/router/src/db/merchant_account.rs
@@ -39,7 +39,7 @@ where
async fn find_merchant_account_by_merchant_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError>;
@@ -59,7 +59,7 @@ where
async fn update_specific_fields_in_merchant(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_account: storage::MerchantAccountUpdate,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError>;
@@ -79,14 +79,14 @@ where
async fn delete_merchant_account_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError>;
#[cfg(feature = "olap")]
async fn list_multiple_merchant_accounts(
&self,
state: &KeyManagerState,
- merchant_ids: Vec<String>,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError>;
}
@@ -110,7 +110,7 @@ impl MerchantAccountInterface for Store {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -120,7 +120,7 @@ impl MerchantAccountInterface for Store {
async fn find_merchant_account_by_merchant_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
let fetch_func = || async {
@@ -137,7 +137,7 @@ impl MerchantAccountInterface for Store {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_id.to_string(),
+ merchant_id.to_owned().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -145,15 +145,20 @@ impl MerchantAccountInterface for Store {
#[cfg(feature = "accounts_cache")]
{
- cache::get_or_populate_in_memory(self, merchant_id, fetch_func, &ACCOUNTS_CACHE)
- .await?
- .convert(
- state,
- merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
- )
- .await
- .change_context(errors::StorageError::DecryptionError)
+ cache::get_or_populate_in_memory(
+ self,
+ merchant_id.get_string_repr(),
+ fetch_func,
+ &ACCOUNTS_CACHE,
+ )
+ .await?
+ .convert(
+ state,
+ merchant_key_store.key.get_inner(),
+ merchant_key_store.merchant_id.clone().into(),
+ )
+ .await
+ .change_context(errors::StorageError::DecryptionError)
}
}
@@ -182,7 +187,7 @@ impl MerchantAccountInterface for Store {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -192,7 +197,7 @@ impl MerchantAccountInterface for Store {
async fn update_specific_fields_in_merchant(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_account: storage::MerchantAccountUpdate,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
@@ -213,7 +218,7 @@ impl MerchantAccountInterface for Store {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -252,7 +257,7 @@ impl MerchantAccountInterface for Store {
let key_store = self
.get_merchant_key_store_by_merchant_id(
state,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&self.get_master_key().to_vec().into(),
)
.await?;
@@ -262,7 +267,7 @@ impl MerchantAccountInterface for Store {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
@@ -292,7 +297,7 @@ impl MerchantAccountInterface for Store {
try_join_all(encrypted_merchant_accounts.iter().map(|merchant_account| {
self.get_merchant_key_store_by_merchant_id(
state,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&db_master_key,
)
}))
@@ -307,7 +312,7 @@ impl MerchantAccountInterface for Store {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -321,7 +326,7 @@ impl MerchantAccountInterface for Store {
#[instrument(skip_all)]
async fn delete_merchant_account_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -358,7 +363,7 @@ impl MerchantAccountInterface for Store {
async fn list_multiple_merchant_accounts(
&self,
state: &KeyManagerState,
- merchant_ids: Vec<String>,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -374,7 +379,7 @@ impl MerchantAccountInterface for Store {
state,
encrypted_merchant_accounts
.iter()
- .map(|merchant_account| &merchant_account.merchant_id)
+ .map(|merchant_account| merchant_account.get_id())
.cloned()
.collect(),
&db_master_key,
@@ -389,17 +394,17 @@ impl MerchantAccountInterface for Store {
let merchant_accounts =
futures::future::try_join_all(encrypted_merchant_accounts.into_iter().map(
|merchant_account| async {
- let key_store = key_stores_by_id.get(&merchant_account.merchant_id).ok_or(
+ let key_store = key_stores_by_id.get(merchant_account.get_id()).ok_or(
errors::StorageError::ValueNotFound(format!(
- "merchant_key_store with merchant_id = {}",
- merchant_account.merchant_id
+ "merchant_key_store with merchant_id = {:?}",
+ merchant_account.get_id()
)),
)?;
merchant_account
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -462,7 +467,7 @@ impl MerchantAccountInterface for MockDb {
.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -472,19 +477,19 @@ impl MerchantAccountInterface for MockDb {
async fn find_merchant_account_by_merchant_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
let accounts = self.merchant_accounts.lock().await;
let account: Option<domain::MerchantAccount> = accounts
.iter()
- .find(|account| account.merchant_id == merchant_id)
+ .find(|account| account.merchant_id == *merchant_id)
.cloned()
.async_map(|a| async {
a.convert(
state,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -513,7 +518,7 @@ impl MerchantAccountInterface for MockDb {
async fn update_specific_fields_in_merchant(
&self,
_state: &KeyManagerState,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_merchant_account: storage::MerchantAccountUpdate,
_merchant_key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, errors::StorageError> {
@@ -539,7 +544,7 @@ impl MerchantAccountInterface for MockDb {
async fn delete_merchant_account_by_merchant_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
// [#172]: Implement function for `MockDb`
Err(errors::StorageError::MockDbError)?
@@ -558,7 +563,7 @@ impl MerchantAccountInterface for MockDb {
async fn list_multiple_merchant_accounts(
&self,
_state: &KeyManagerState,
- _merchant_ids: Vec<String>,
+ _merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> CustomResult<Vec<domain::MerchantAccount>, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
@@ -578,7 +583,7 @@ async fn publish_and_redact_merchant_account_cache(
CacheKind::CGraph(
format!(
"cgraph_{}_{}",
- merchant_account.merchant_id.clone(),
+ merchant_account.get_id().clone(),
profile_id,
)
.into(),
@@ -586,7 +591,7 @@ async fn publish_and_redact_merchant_account_cache(
});
let mut cache_keys = vec![CacheKind::Accounts(
- merchant_account.merchant_id.as_str().into(),
+ merchant_account.get_id().get_string_repr().into(),
)];
cache_keys.extend(publishable_key.into_iter());
@@ -601,7 +606,9 @@ async fn publish_and_redact_all_merchant_account_cache(
store: &dyn super::StorageInterface,
merchant_accounts: &[storage::MerchantAccount],
) -> CustomResult<(), errors::StorageError> {
- let merchant_ids = merchant_accounts.iter().map(|m| m.merchant_id.clone());
+ let merchant_ids = merchant_accounts
+ .iter()
+ .map(|m| m.merchant_id.get_string_repr().to_string());
let publishable_keys = merchant_accounts
.iter()
.filter_map(|m| m.publishable_key.clone());
diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rs
index 078980f9184..f48007d15b3 100644
--- a/crates/router/src/db/merchant_connector_account.rs
+++ b/crates/router/src/db/merchant_connector_account.rs
@@ -28,13 +28,13 @@ use crate::{
pub trait ConnectorAccessToken {
async fn get_access_token(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id_or_connector_name: &str,
) -> CustomResult<Option<types::AccessToken>, errors::StorageError>;
async fn set_access_token(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id_or_connector_name: &str,
access_token: types::AccessToken,
) -> CustomResult<(), errors::StorageError>;
@@ -45,7 +45,7 @@ impl ConnectorAccessToken for Store {
#[instrument(skip_all)]
async fn get_access_token(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id_or_connector_name: &str,
) -> CustomResult<Option<types::AccessToken>, errors::StorageError> {
//TODO: Handle race condition
@@ -75,7 +75,7 @@ impl ConnectorAccessToken for Store {
#[instrument(skip_all)]
async fn set_access_token(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id_or_connector_name: &str,
access_token: types::AccessToken,
) -> CustomResult<(), errors::StorageError> {
@@ -98,7 +98,7 @@ impl ConnectorAccessToken for Store {
impl ConnectorAccessToken for MockDb {
async fn get_access_token(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_merchant_connector_id_or_connector_name: &str,
) -> CustomResult<Option<types::AccessToken>, errors::StorageError> {
Ok(None)
@@ -106,7 +106,7 @@ impl ConnectorAccessToken for MockDb {
async fn set_access_token(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_merchant_connector_id_or_connector_name: &str,
_access_token: types::AccessToken,
) -> CustomResult<(), errors::StorageError> {
@@ -125,7 +125,7 @@ where
async fn find_merchant_connector_account_by_merchant_id_connector_label(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_label: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>;
@@ -141,7 +141,7 @@ where
async fn find_merchant_connector_account_by_merchant_id_connector_name(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError>;
@@ -156,7 +156,7 @@ where
async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError>;
@@ -164,7 +164,7 @@ where
async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
get_disabled: bool,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError>;
@@ -187,7 +187,7 @@ where
async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &str,
) -> CustomResult<bool, errors::StorageError>;
}
@@ -198,7 +198,7 @@ impl MerchantConnectorAccountInterface for Store {
async fn find_merchant_connector_account_by_merchant_id_connector_label(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_label: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
@@ -217,7 +217,7 @@ impl MerchantConnectorAccountInterface for Store {
{
find_call()
.await?
- .convert(state, key_store.key.get_inner(), merchant_id.to_string())
+ .convert(state, key_store.key.get_inner(), merchant_id.clone().into())
.await
.change_context(errors::StorageError::DeserializationFailed)
}
@@ -235,7 +235,7 @@ impl MerchantConnectorAccountInterface for Store {
item.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -270,7 +270,7 @@ impl MerchantConnectorAccountInterface for Store {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DeserializationFailed)
@@ -289,7 +289,7 @@ impl MerchantConnectorAccountInterface for Store {
item.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -302,7 +302,7 @@ impl MerchantConnectorAccountInterface for Store {
async fn find_merchant_connector_account_by_merchant_id_connector_name(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
@@ -321,7 +321,7 @@ impl MerchantConnectorAccountInterface for Store {
item.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
@@ -336,7 +336,7 @@ impl MerchantConnectorAccountInterface for Store {
async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
@@ -358,7 +358,7 @@ impl MerchantConnectorAccountInterface for Store {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -368,7 +368,11 @@ impl MerchantConnectorAccountInterface for Store {
{
cache::get_or_populate_in_memory(
self,
- &format!("{}_{}", merchant_id, merchant_connector_id),
+ &format!(
+ "{}_{}",
+ merchant_id.get_string_repr(),
+ merchant_connector_id
+ ),
find_call,
&cache::ACCOUNTS_CACHE,
)
@@ -376,7 +380,7 @@ impl MerchantConnectorAccountInterface for Store {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -401,7 +405,7 @@ impl MerchantConnectorAccountInterface for Store {
item.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -413,7 +417,7 @@ impl MerchantConnectorAccountInterface for Store {
async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
get_disabled: bool,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
@@ -428,7 +432,7 @@ impl MerchantConnectorAccountInterface for Store {
item.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
@@ -495,10 +499,16 @@ impl MerchantConnectorAccountInterface for Store {
format!("{}_{}", _profile_id, _connector_name).into(),
),
cache::CacheKind::Accounts(
- format!("{}_{}", _merchant_id, _merchant_connector_id).into(),
+ format!(
+ "{}_{}",
+ _merchant_id.get_string_repr(),
+ _merchant_connector_id
+ )
+ .into(),
),
cache::CacheKind::CGraph(
- format!("cgraph_{}_{_profile_id}", _merchant_id).into(),
+ format!("cgraph_{}_{_profile_id}", _merchant_id.get_string_repr())
+ .into(),
),
],
|| update,
@@ -568,7 +578,7 @@ impl MerchantConnectorAccountInterface for Store {
item.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -586,13 +596,22 @@ impl MerchantConnectorAccountInterface for Store {
format!("{}_{}", _profile_id, _connector_name).into(),
),
cache::CacheKind::Accounts(
- format!("{}_{}", _merchant_id, _merchant_connector_id).into(),
+ format!(
+ "{}_{}",
+ _merchant_id.get_string_repr(),
+ _merchant_connector_id
+ )
+ .into(),
),
cache::CacheKind::CGraph(
- format!("cgraph_{}_{_profile_id}", _merchant_id).into(),
+ format!("cgraph_{}_{_profile_id}", _merchant_id.get_string_repr()).into(),
),
cache::CacheKind::PmFiltersCGraph(
- format!("pm_filters_cgraph_{}_{_profile_id}", _merchant_id).into(),
+ format!(
+ "pm_filters_cgraph_{}_{_profile_id}",
+ _merchant_id.get_string_repr()
+ )
+ .into(),
),
],
update_call,
@@ -609,7 +628,7 @@ impl MerchantConnectorAccountInterface for Store {
#[instrument(skip_all)]
async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -646,13 +665,18 @@ impl MerchantConnectorAccountInterface for Store {
self,
[
cache::CacheKind::Accounts(
- format!("{}_{}", mca.merchant_id, _profile_id).into(),
+ format!("{}_{}", mca.merchant_id.get_string_repr(), _profile_id).into(),
),
cache::CacheKind::CGraph(
- format!("cgraph_{}_{_profile_id}", mca.merchant_id).into(),
+ format!("cgraph_{}_{_profile_id}", mca.merchant_id.get_string_repr())
+ .into(),
),
cache::CacheKind::PmFiltersCGraph(
- format!("pm_filters_cgraph_{}_{_profile_id}", mca.merchant_id).into(),
+ format!(
+ "pm_filters_cgraph_{}_{_profile_id}",
+ mca.merchant_id.get_string_repr()
+ )
+ .into(),
),
],
delete_call,
@@ -683,7 +707,7 @@ impl MerchantConnectorAccountInterface for MockDb {
async fn find_merchant_connector_account_by_merchant_id_connector_label(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
@@ -693,7 +717,7 @@ impl MerchantConnectorAccountInterface for MockDb {
.await
.iter()
.find(|account| {
- account.merchant_id == merchant_id
+ account.merchant_id == *merchant_id
&& account.connector_label == Some(connector.to_string())
})
.cloned()
@@ -702,7 +726,7 @@ impl MerchantConnectorAccountInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -722,7 +746,7 @@ impl MerchantConnectorAccountInterface for MockDb {
async fn find_merchant_connector_account_by_merchant_id_connector_name(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
@@ -732,7 +756,7 @@ impl MerchantConnectorAccountInterface for MockDb {
.await
.iter()
.filter(|account| {
- account.merchant_id == merchant_id && account.connector_name == connector_name
+ account.merchant_id == *merchant_id && account.connector_name == connector_name
})
.cloned()
.collect::<Vec<_>>();
@@ -743,7 +767,7 @@ impl MerchantConnectorAccountInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
@@ -776,7 +800,7 @@ impl MerchantConnectorAccountInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError),
@@ -790,7 +814,7 @@ impl MerchantConnectorAccountInterface for MockDb {
async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &str,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, errors::StorageError> {
@@ -800,7 +824,7 @@ impl MerchantConnectorAccountInterface for MockDb {
.await
.iter()
.find(|account| {
- account.merchant_id == merchant_id
+ account.merchant_id == *merchant_id
&& account.merchant_connector_id == merchant_connector_id
})
.cloned()
@@ -809,7 +833,7 @@ impl MerchantConnectorAccountInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -865,7 +889,7 @@ impl MerchantConnectorAccountInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -874,7 +898,7 @@ impl MerchantConnectorAccountInterface for MockDb {
async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
get_disabled: bool,
key_store: &domain::MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::StorageError> {
@@ -885,9 +909,9 @@ impl MerchantConnectorAccountInterface for MockDb {
.iter()
.filter(|account: &&storage::MerchantConnectorAccount| {
if get_disabled {
- account.merchant_id == merchant_id
+ account.merchant_id == *merchant_id
} else {
- account.merchant_id == merchant_id && account.disabled == Some(false)
+ account.merchant_id == *merchant_id && account.disabled == Some(false)
}
})
.cloned()
@@ -900,7 +924,7 @@ impl MerchantConnectorAccountInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
@@ -933,7 +957,7 @@ impl MerchantConnectorAccountInterface for MockDb {
.convert(
state,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
@@ -953,12 +977,12 @@ impl MerchantConnectorAccountInterface for MockDb {
async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let mut accounts = self.merchant_connector_accounts.lock().await;
match accounts.iter().position(|account| {
- account.merchant_id == merchant_id
+ account.merchant_id == *merchant_id
&& account.merchant_connector_id == merchant_connector_id
}) {
Some(index) => {
@@ -1038,7 +1062,8 @@ mod merchant_connector_account_cache_tests {
.await
.unwrap();
- let merchant_id = "test_merchant";
+ let merchant_id = common_utils::id_type::MerchantId::from("test_merchant".into()).unwrap();
+
let connector_label = "stripe_USA";
let merchant_connector_id = "simple_merchant_connector_id";
let profile_id = "pro_max_ultra";
@@ -1046,11 +1071,11 @@ mod merchant_connector_account_cache_tests {
db.insert_merchant_key_store(
key_manager_state,
domain::MerchantKeyStore {
- merchant_id: merchant_id.into(),
+ merchant_id: merchant_id.clone(),
key: domain::types::encrypt(
key_manager_state,
services::generate_aes256_key().unwrap().to_vec().into(),
- Identifier::Merchant(merchant_id.to_string()),
+ Identifier::Merchant(merchant_id.clone()),
master_key,
)
.await
@@ -1065,7 +1090,7 @@ mod merchant_connector_account_cache_tests {
let merchant_key = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- merchant_id,
+ &merchant_id,
&master_key.to_vec().into(),
)
.await
@@ -1073,7 +1098,7 @@ mod merchant_connector_account_cache_tests {
let mca = domain::MerchantConnectorAccount {
id: Some(1),
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
connector_name: "stripe".to_string(),
connector_account_details: domain::types::encrypt(
key_manager_state,
@@ -1143,7 +1168,7 @@ mod merchant_connector_account_cache_tests {
let delete_call = || async {
db.delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
- merchant_id,
+ &merchant_id,
merchant_connector_id,
)
.await
diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rs
index 21c1a184425..9540a420e97 100644
--- a/crates/router/src/db/merchant_key_store.rs
+++ b/crates/router/src/db/merchant_key_store.rs
@@ -28,20 +28,20 @@ pub trait MerchantKeyStoreInterface {
async fn get_merchant_key_store_by_merchant_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, errors::StorageError>;
async fn delete_merchant_key_store_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError>;
#[cfg(feature = "olap")]
async fn list_multiple_key_stores(
&self,
state: &KeyManagerState,
- merchant_ids: Vec<String>,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
key: &Secret<Vec<u8>>,
) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError>;
@@ -72,7 +72,7 @@ impl MerchantKeyStoreInterface for Store {
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
- .convert(state, key, merchant_id)
+ .convert(state, key, merchant_id.into())
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -81,7 +81,7 @@ impl MerchantKeyStoreInterface for Store {
async fn get_merchant_key_store_by_merchant_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> {
let fetch_func = || async {
@@ -99,7 +99,7 @@ impl MerchantKeyStoreInterface for Store {
{
fetch_func()
.await?
- .convert(state, key, merchant_id.to_string())
+ .convert(state, key, merchant_id.clone().into())
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -114,7 +114,7 @@ impl MerchantKeyStoreInterface for Store {
&ACCOUNTS_CACHE,
)
.await?
- .convert(state, key, merchant_id.to_string())
+ .convert(state, key, merchant_id.clone().into())
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -123,7 +123,7 @@ impl MerchantKeyStoreInterface for Store {
#[instrument(skip_all)]
async fn delete_merchant_key_store_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
let delete_func = || async {
let conn = connection::pg_connection_write(self).await?;
@@ -142,7 +142,8 @@ impl MerchantKeyStoreInterface for Store {
#[cfg(feature = "accounts_cache")]
{
- let key_store_cache_key = format!("merchant_key_store_{}", merchant_id);
+ let key_store_cache_key =
+ format!("merchant_key_store_{}", merchant_id.get_string_repr());
cache::publish_and_redact(
self,
CacheKind::Accounts(key_store_cache_key.into()),
@@ -157,7 +158,7 @@ impl MerchantKeyStoreInterface for Store {
async fn list_multiple_key_stores(
&self,
state: &KeyManagerState,
- merchant_ids: Vec<String>,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
key: &Secret<Vec<u8>>,
) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> {
let fetch_func = || async {
@@ -174,7 +175,7 @@ impl MerchantKeyStoreInterface for Store {
futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async {
let merchant_id = key_store.merchant_id.clone();
key_store
- .convert(state, key, merchant_id)
+ .convert(state, key, merchant_id.into())
.await
.change_context(errors::StorageError::DecryptionError)
}))
@@ -198,7 +199,7 @@ impl MerchantKeyStoreInterface for Store {
futures::future::try_join_all(stores.into_iter().map(|key_store| async {
let merchant_id = key_store.merchant_id.clone();
key_store
- .convert(state, key, merchant_id)
+ .convert(state, key, merchant_id.into())
.await
.change_context(errors::StorageError::DecryptionError)
}))
@@ -222,7 +223,7 @@ impl MerchantKeyStoreInterface for MockDb {
{
Err(errors::StorageError::DuplicateValue {
entity: "merchant_key_store",
- key: Some(merchant_key_store.merchant_id.clone()),
+ key: Some(merchant_key_store.merchant_id.get_string_repr().to_owned()),
})?;
}
@@ -232,7 +233,7 @@ impl MerchantKeyStoreInterface for MockDb {
locked_merchant_key_store.push(merchant_key.clone());
let merchant_id = merchant_key.merchant_id.clone();
merchant_key
- .convert(state, key, merchant_id)
+ .convert(state, key, merchant_id.into())
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -240,33 +241,33 @@ impl MerchantKeyStoreInterface for MockDb {
async fn get_merchant_key_store_by_merchant_id(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, errors::StorageError> {
self.merchant_key_store
.lock()
.await
.iter()
- .find(|merchant_key| merchant_key.merchant_id == merchant_id)
+ .find(|merchant_key| merchant_key.merchant_id == *merchant_id)
.cloned()
.ok_or(errors::StorageError::ValueNotFound(String::from(
"merchant_key_store",
)))?
- .convert(state, key, merchant_id.to_string())
+ .convert(state, key, merchant_id.clone().into())
.await
.change_context(errors::StorageError::DecryptionError)
}
async fn delete_merchant_key_store_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
let mut merchant_key_stores = self.merchant_key_store.lock().await;
let index = merchant_key_stores
.iter()
- .position(|mks| mks.merchant_id == merchant_id)
+ .position(|mks| mks.merchant_id == *merchant_id)
.ok_or(errors::StorageError::ValueNotFound(format!(
- "No merchant key store found for merchant_id = {}",
+ "No merchant key store found for merchant_id = {:?}",
merchant_id
)))?;
merchant_key_stores.remove(index);
@@ -277,7 +278,7 @@ impl MerchantKeyStoreInterface for MockDb {
async fn list_multiple_key_stores(
&self,
state: &KeyManagerState,
- merchant_ids: Vec<String>,
+ merchant_ids: Vec<common_utils::id_type::MerchantId>,
key: &Secret<Vec<u8>>,
) -> CustomResult<Vec<domain::MerchantKeyStore>, errors::StorageError> {
let merchant_key_stores = self.merchant_key_store.lock().await;
@@ -288,7 +289,7 @@ impl MerchantKeyStoreInterface for MockDb {
.map(|merchant_key| async {
merchant_key
.to_owned()
- .convert(state, key, merchant_key.merchant_id.clone())
+ .convert(state, key, merchant_key.merchant_id.clone().into())
.await
.change_context(errors::StorageError::DecryptionError)
}),
@@ -307,7 +308,7 @@ impl MerchantKeyStoreInterface for MockDb {
futures::future::try_join_all(merchant_key_stores.iter().map(|merchant_key| async {
merchant_key
.to_owned()
- .convert(state, key, merchant_key.merchant_id.clone())
+ .convert(state, key, merchant_key.merchant_id.clone().into())
.await
.change_context(errors::StorageError::DecryptionError)
}))
@@ -353,14 +354,14 @@ mod tests {
.await
.expect("Failed to create mock DB");
let master_key = mock_db.get_master_key();
- let merchant_id = "merchant1";
- let identifier = Identifier::Merchant(merchant_id.to_string());
+ let merchant_id = common_utils::id_type::MerchantId::from("merchant1".into()).unwrap();
+ let identifier = Identifier::Merchant(merchant_id.clone());
let key_manager_state = &state.into();
let merchant_key1 = mock_db
.insert_merchant_key_store(
key_manager_state,
domain::MerchantKeyStore {
- merchant_id: merchant_id.into(),
+ merchant_id: merchant_id.clone(),
key: domain::types::encrypt(
key_manager_state,
services::generate_aes256_key().unwrap().to_vec().into(),
@@ -379,7 +380,7 @@ mod tests {
let found_merchant_key1 = mock_db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- merchant_id,
+ &merchant_id,
&master_key.to_vec().into(),
)
.await
@@ -392,7 +393,7 @@ mod tests {
.insert_merchant_key_store(
key_manager_state,
domain::MerchantKeyStore {
- merchant_id: merchant_id.into(),
+ merchant_id: merchant_id.clone(),
key: domain::types::encrypt(
key_manager_state,
services::generate_aes256_key().unwrap().to_vec().into(),
@@ -408,10 +409,13 @@ mod tests {
.await;
assert!(insert_duplicate_merchant_key1_result.is_err());
+ let non_existent_merchant_id =
+ common_utils::id_type::MerchantId::from("non_existent".into()).unwrap();
+
let find_non_existent_merchant_key_result = mock_db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- "non_existent",
+ &non_existent_merchant_id,
&master_key.to_vec().into(),
)
.await;
@@ -420,7 +424,7 @@ mod tests {
let find_merchant_key_with_incorrect_master_key_result = mock_db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- merchant_id,
+ &merchant_id,
&vec![0; 32].into(),
)
.await;
diff --git a/crates/router/src/db/payment_link.rs b/crates/router/src/db/payment_link.rs
index c3f78767931..50be9ec7288 100644
--- a/crates/router/src/db/payment_link.rs
+++ b/crates/router/src/db/payment_link.rs
@@ -23,7 +23,7 @@ pub trait PaymentLinkInterface {
async fn list_payment_link_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_link_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError>;
}
@@ -56,7 +56,7 @@ impl PaymentLinkInterface for Store {
#[instrument(skip_all)]
async fn list_payment_link_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_link_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -86,7 +86,7 @@ impl PaymentLinkInterface for MockDb {
async fn list_payment_link_by_merchant_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_payment_link_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<storage::PaymentLink>, errors::StorageError> {
// TODO: Implement function for `MockDb`x
diff --git a/crates/router/src/db/payment_method.rs b/crates/router/src/db/payment_method.rs
index 9ec25b1d1b2..b0fed03e9b5 100644
--- a/crates/router/src/db/payment_method.rs
+++ b/crates/router/src/db/payment_method.rs
@@ -25,14 +25,14 @@ pub trait PaymentMethodInterface {
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
limit: Option<i64>,
) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError>;
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
@@ -41,7 +41,7 @@ pub trait PaymentMethodInterface {
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError>;
@@ -60,7 +60,7 @@ pub trait PaymentMethodInterface {
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_method_id: &str,
) -> CustomResult<storage_types::PaymentMethod, errors::StorageError>;
}
@@ -190,7 +190,7 @@ mod storage {
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -366,7 +366,7 @@ mod storage {
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
limit: Option<i64>,
) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -384,7 +384,7 @@ mod storage {
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
@@ -440,7 +440,7 @@ mod storage {
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_method_id: &str,
) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -499,7 +499,7 @@ mod storage {
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -544,7 +544,7 @@ mod storage {
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
limit: Option<i64>,
) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -562,7 +562,7 @@ mod storage {
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
_storage_scheme: MerchantStorageScheme,
@@ -581,7 +581,7 @@ mod storage {
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_method_id: &str,
) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -641,7 +641,7 @@ impl PaymentMethodInterface for MockDb {
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
@@ -649,7 +649,7 @@ impl PaymentMethodInterface for MockDb {
.iter()
.filter(|pm| {
pm.customer_id == *customer_id
- && pm.merchant_id == merchant_id
+ && pm.merchant_id == *merchant_id
&& pm.status == status
})
.count();
@@ -704,13 +704,13 @@ impl PaymentMethodInterface for MockDb {
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
_limit: Option<i64>,
) -> CustomResult<Vec<storage_types::PaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let payment_methods_found: Vec<storage_types::PaymentMethod> = payment_methods
.iter()
- .filter(|pm| pm.customer_id == *customer_id && pm.merchant_id == merchant_id)
+ .filter(|pm| pm.customer_id == *customer_id && pm.merchant_id == *merchant_id)
.cloned()
.collect();
@@ -727,7 +727,7 @@ impl PaymentMethodInterface for MockDb {
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
_limit: Option<i64>,
_storage_scheme: MerchantStorageScheme,
@@ -737,7 +737,7 @@ impl PaymentMethodInterface for MockDb {
.iter()
.filter(|pm| {
pm.customer_id == *customer_id
- && pm.merchant_id == merchant_id
+ && pm.merchant_id == *merchant_id
&& pm.status == status
})
.cloned()
@@ -755,12 +755,12 @@ impl PaymentMethodInterface for MockDb {
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
payment_method_id: &str,
) -> CustomResult<storage_types::PaymentMethod, errors::StorageError> {
let mut payment_methods = self.payment_methods.lock().await;
match payment_methods.iter().position(|pm| {
- pm.merchant_id == merchant_id && pm.payment_method_id == payment_method_id
+ pm.merchant_id == *merchant_id && pm.payment_method_id == payment_method_id
}) {
Some(index) => {
let deleted_payment_method = payment_methods.remove(index);
diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rs
index a36af014710..67be1d30e04 100644
--- a/crates/router/src/db/refund.rs
+++ b/crates/router/src/db/refund.rs
@@ -20,27 +20,27 @@ pub trait RefundInterface {
async fn find_refund_by_internal_reference_id_merchant_id(
&self,
internal_reference_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<storage_types::Refund, errors::StorageError>;
async fn find_refund_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError>;
async fn find_refund_by_merchant_id_refund_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_id: &str,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<storage_types::Refund, errors::StorageError>;
async fn find_refund_by_merchant_id_connector_refund_id_connector(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_refund_id: &str,
connector: &str,
storage_scheme: enums::MerchantStorageScheme,
@@ -55,7 +55,7 @@ pub trait RefundInterface {
async fn find_refund_by_merchant_id_connector_transaction_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_transaction_id: &str,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError>;
@@ -69,7 +69,7 @@ pub trait RefundInterface {
#[cfg(feature = "olap")]
async fn filter_refund_by_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_details: &api_models::refunds::RefundListRequest,
storage_scheme: enums::MerchantStorageScheme,
limit: i64,
@@ -79,7 +79,7 @@ pub trait RefundInterface {
#[cfg(feature = "olap")]
async fn filter_refund_by_meta_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_details: &api_models::payments::TimeRange,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError>;
@@ -87,7 +87,7 @@ pub trait RefundInterface {
#[cfg(feature = "olap")]
async fn get_total_count_of_refunds(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_details: &api_models::refunds::RefundListRequest,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError>;
@@ -112,7 +112,7 @@ mod storage {
async fn find_refund_by_internal_reference_id_merchant_id(
&self,
internal_reference_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<storage_types::Refund, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -140,7 +140,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_refund_by_merchant_id_connector_transaction_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_transaction_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> {
@@ -170,7 +170,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_refund_by_merchant_id_refund_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<storage_types::Refund, errors::StorageError> {
@@ -183,7 +183,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_refund_by_merchant_id_connector_refund_id_connector(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_refund_id: &str,
connector: &str,
_storage_scheme: enums::MerchantStorageScheme,
@@ -203,7 +203,7 @@ mod storage {
async fn find_refund_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
@@ -216,7 +216,7 @@ mod storage {
#[instrument(skip_all)]
async fn filter_refund_by_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_details: &api_models::refunds::RefundListRequest,
_storage_scheme: enums::MerchantStorageScheme,
limit: i64,
@@ -238,7 +238,7 @@ mod storage {
#[instrument(skip_all)]
async fn filter_refund_by_meta_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_details: &api_models::payments::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> {
@@ -255,7 +255,7 @@ mod storage {
#[instrument(skip_all)]
async fn get_total_count_of_refunds(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_details: &api_models::refunds::RefundListRequest,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
@@ -296,7 +296,7 @@ mod storage {
async fn find_refund_by_internal_reference_id_merchant_id(
&self,
internal_reference_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<storage_types::Refund, errors::StorageError> {
let database_call = || async {
@@ -315,7 +315,10 @@ mod storage {
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("ref_inter_ref_{merchant_id}_{internal_reference_id}");
+ let lookup_id = format!(
+ "ref_inter_ref_{}_{internal_reference_id}",
+ merchant_id.get_string_repr()
+ );
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
@@ -415,7 +418,8 @@ mod storage {
sk_id: field.clone(),
lookup_id: format!(
"ref_ref_id_{}_{}",
- created_refund.merchant_id, created_refund.refund_id
+ created_refund.merchant_id.get_string_repr(),
+ created_refund.refund_id
),
pk_id: key_str.clone(),
source: "refund".to_string(),
@@ -426,7 +430,8 @@ mod storage {
sk_id: field.clone(),
lookup_id: format!(
"ref_inter_ref_{}_{}",
- created_refund.merchant_id, created_refund.internal_reference_id
+ created_refund.merchant_id.get_string_repr(),
+ created_refund.internal_reference_id
),
pk_id: key_str.clone(),
source: "refund".to_string(),
@@ -439,7 +444,7 @@ mod storage {
sk_id: field.clone(),
lookup_id: format!(
"ref_connector_{}_{}_{}",
- created_refund.merchant_id,
+ created_refund.merchant_id.get_string_repr(),
connector_refund_id,
created_refund.connector
),
@@ -482,7 +487,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_refund_by_merchant_id_connector_transaction_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_transaction_id: &str,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> {
@@ -502,8 +507,10 @@ mod storage {
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
- let lookup_id =
- format!("pa_conn_trans_{merchant_id}_{connector_transaction_id}");
+ let lookup_id = format!(
+ "pa_conn_trans_{}_{connector_transaction_id}",
+ merchant_id.get_string_repr()
+ );
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
@@ -598,7 +605,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_refund_by_merchant_id_refund_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_id: &str,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<storage_types::Refund, errors::StorageError> {
@@ -614,7 +621,8 @@ mod storage {
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("ref_ref_id_{merchant_id}_{refund_id}");
+ let lookup_id =
+ format!("ref_ref_id_{}_{refund_id}", merchant_id.get_string_repr());
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
@@ -644,7 +652,7 @@ mod storage {
#[instrument(skip_all)]
async fn find_refund_by_merchant_id_connector_refund_id_connector(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_refund_id: &str,
connector: &str,
storage_scheme: enums::MerchantStorageScheme,
@@ -666,8 +674,10 @@ mod storage {
match storage_scheme {
enums::MerchantStorageScheme::PostgresOnly => database_call().await,
enums::MerchantStorageScheme::RedisKv => {
- let lookup_id =
- format!("ref_connector_{merchant_id}_{connector_refund_id}_{connector}");
+ let lookup_id = format!(
+ "ref_connector_{}_{connector_refund_id}_{connector}",
+ merchant_id.get_string_repr()
+ );
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
@@ -698,7 +708,7 @@ mod storage {
async fn find_refund_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> {
let database_call = || async {
@@ -742,7 +752,7 @@ mod storage {
#[instrument(skip_all)]
async fn filter_refund_by_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_details: &api_models::refunds::RefundListRequest,
_storage_scheme: enums::MerchantStorageScheme,
limit: i64,
@@ -764,7 +774,7 @@ mod storage {
#[instrument(skip_all)]
async fn filter_refund_by_meta_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_details: &api_models::payments::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> {
@@ -778,7 +788,7 @@ mod storage {
#[instrument(skip_all)]
async fn get_total_count_of_refunds(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_details: &api_models::refunds::RefundListRequest,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
@@ -799,14 +809,14 @@ impl RefundInterface for MockDb {
async fn find_refund_by_internal_reference_id_merchant_id(
&self,
internal_reference_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<storage_types::Refund, errors::StorageError> {
let refunds = self.refunds.lock().await;
refunds
.iter()
.find(|refund| {
- refund.merchant_id == merchant_id
+ refund.merchant_id == *merchant_id
&& refund.internal_reference_id == internal_reference_id
})
.cloned()
@@ -858,7 +868,7 @@ impl RefundInterface for MockDb {
}
async fn find_refund_by_merchant_id_connector_transaction_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_transaction_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> {
@@ -867,7 +877,7 @@ impl RefundInterface for MockDb {
Ok(refunds
.iter()
.take_while(|refund| {
- refund.merchant_id == merchant_id
+ refund.merchant_id == *merchant_id
&& refund.connector_transaction_id == connector_transaction_id
})
.cloned()
@@ -898,7 +908,7 @@ impl RefundInterface for MockDb {
async fn find_refund_by_merchant_id_refund_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_id: &str,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<storage_types::Refund, errors::StorageError> {
@@ -906,7 +916,7 @@ impl RefundInterface for MockDb {
refunds
.iter()
- .find(|refund| refund.merchant_id == merchant_id && refund.refund_id == refund_id)
+ .find(|refund| refund.merchant_id == *merchant_id && refund.refund_id == refund_id)
.cloned()
.ok_or_else(|| {
errors::StorageError::DatabaseError(DatabaseError::NotFound.into()).into()
@@ -915,7 +925,7 @@ impl RefundInterface for MockDb {
async fn find_refund_by_merchant_id_connector_refund_id_connector(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_refund_id: &str,
connector: &str,
_storage_scheme: enums::MerchantStorageScheme,
@@ -925,7 +935,7 @@ impl RefundInterface for MockDb {
refunds
.iter()
.find(|refund| {
- refund.merchant_id == merchant_id
+ refund.merchant_id == *merchant_id
&& refund.connector_refund_id == Some(connector_refund_id.to_string())
&& refund.connector == connector
})
@@ -938,14 +948,14 @@ impl RefundInterface for MockDb {
async fn find_refund_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage_types::Refund>, errors::StorageError> {
let refunds = self.refunds.lock().await;
Ok(refunds
.iter()
- .filter(|refund| refund.merchant_id == merchant_id && refund.payment_id == payment_id)
+ .filter(|refund| refund.merchant_id == *merchant_id && refund.payment_id == payment_id)
.cloned()
.collect::<Vec<_>>())
}
@@ -953,7 +963,7 @@ impl RefundInterface for MockDb {
#[cfg(feature = "olap")]
async fn filter_refund_by_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_details: &api_models::refunds::RefundListRequest,
_storage_scheme: enums::MerchantStorageScheme,
limit: i64,
@@ -994,7 +1004,7 @@ impl RefundInterface for MockDb {
let refunds = self.refunds.lock().await;
let filtered_refunds = refunds
.iter()
- .filter(|refund| refund.merchant_id == merchant_id)
+ .filter(|refund| refund.merchant_id == *merchant_id)
.filter(|refund| {
refund_details
.payment_id
@@ -1059,7 +1069,7 @@ impl RefundInterface for MockDb {
#[cfg(feature = "olap")]
async fn filter_refund_by_meta_constraints(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
refund_details: &api_models::payments::TimeRange,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::StorageError> {
@@ -1106,7 +1116,7 @@ impl RefundInterface for MockDb {
#[cfg(feature = "olap")]
async fn get_total_count_of_refunds(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_details: &api_models::refunds::RefundListRequest,
_storage_scheme: enums::MerchantStorageScheme,
) -> CustomResult<i64, errors::StorageError> {
@@ -1145,7 +1155,7 @@ impl RefundInterface for MockDb {
let refunds = self.refunds.lock().await;
let filtered_refunds = refunds
.iter()
- .filter(|refund| refund.merchant_id == merchant_id)
+ .filter(|refund| refund.merchant_id == *merchant_id)
.filter(|refund| {
refund_details
.payment_id
diff --git a/crates/router/src/db/role.rs b/crates/router/src/db/role.rs
index 88915333389..15dfc14d375 100644
--- a/crates/router/src/db/role.rs
+++ b/crates/router/src/db/role.rs
@@ -26,7 +26,7 @@ pub trait RoleInterface {
async fn find_role_by_role_id_in_merchant_scope(
&self,
role_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> CustomResult<storage::Role, errors::StorageError>;
@@ -43,7 +43,7 @@ pub trait RoleInterface {
async fn list_all_roles(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> CustomResult<Vec<storage::Role>, errors::StorageError>;
}
@@ -76,7 +76,7 @@ impl RoleInterface for Store {
async fn find_role_by_role_id_in_merchant_scope(
&self,
role_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> CustomResult<storage::Role, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -111,7 +111,7 @@ impl RoleInterface for Store {
#[instrument(skip_all)]
async fn list_all_roles(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -174,7 +174,7 @@ impl RoleInterface for MockDb {
async fn find_role_by_role_id_in_merchant_scope(
&self,
role_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> CustomResult<storage::Role, errors::StorageError> {
let roles = self.roles.lock().await;
@@ -182,14 +182,14 @@ impl RoleInterface for MockDb {
.iter()
.find(|role| {
role.role_id == role_id
- && (role.merchant_id == merchant_id
+ && (role.merchant_id == *merchant_id
|| (role.org_id == *org_id && role.scope == enums::RoleScope::Organization))
})
.cloned()
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No role available in merchant scope for role_id = {role_id}, \
- merchant_id = {merchant_id} and org_id = {org_id:?}"
+ merchant_id = {merchant_id:?} and org_id = {org_id:?}"
))
.into(),
)
@@ -246,7 +246,7 @@ impl RoleInterface for MockDb {
async fn list_all_roles(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> CustomResult<Vec<storage::Role>, errors::StorageError> {
let roles = self.roles.lock().await;
@@ -254,7 +254,7 @@ impl RoleInterface for MockDb {
let roles_list: Vec<_> = roles
.iter()
.filter(|role| {
- role.merchant_id == merchant_id
+ role.merchant_id == *merchant_id
|| (role.org_id == *org_id
&& role.scope == diesel_models::enums::RoleScope::Organization)
})
@@ -263,7 +263,7 @@ impl RoleInterface for MockDb {
if roles_list.is_empty() {
return Err(errors::StorageError::ValueNotFound(format!(
- "No role found for merchant id = {} and org_id = {:?}",
+ "No role found for merchant id = {:?} and org_id = {:?}",
merchant_id, org_id
))
.into());
diff --git a/crates/router/src/db/routing_algorithm.rs b/crates/router/src/db/routing_algorithm.rs
index f65933d8982..b5e877b5295 100644
--- a/crates/router/src/db/routing_algorithm.rs
+++ b/crates/router/src/db/routing_algorithm.rs
@@ -27,7 +27,7 @@ pub trait RoutingAlgorithmInterface {
async fn find_routing_algorithm_by_algorithm_id_merchant_id(
&self,
algorithm_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<routing_storage::RoutingAlgorithm>;
async fn find_routing_algorithm_metadata_by_algorithm_id_profile_id(
@@ -45,14 +45,14 @@ pub trait RoutingAlgorithmInterface {
async fn list_routing_algorithm_metadata_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
limit: i64,
offset: i64,
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>>;
async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
transaction_type: &common_enums::TransactionType,
limit: i64,
offset: i64,
@@ -93,7 +93,7 @@ impl RoutingAlgorithmInterface for Store {
async fn find_routing_algorithm_by_algorithm_id_merchant_id(
&self,
algorithm_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<routing_storage::RoutingAlgorithm> {
let conn = connection::pg_connection_write(self).await?;
routing_storage::RoutingAlgorithm::find_by_algorithm_id_merchant_id(
@@ -139,7 +139,7 @@ impl RoutingAlgorithmInterface for Store {
#[instrument(skip_all)]
async fn list_routing_algorithm_metadata_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
limit: i64,
offset: i64,
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> {
@@ -156,7 +156,7 @@ impl RoutingAlgorithmInterface for Store {
async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
transaction_type: &common_enums::TransactionType,
limit: i64,
offset: i64,
@@ -194,7 +194,7 @@ impl RoutingAlgorithmInterface for MockDb {
async fn find_routing_algorithm_by_algorithm_id_merchant_id(
&self,
_algorithm_id: &str,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<routing_storage::RoutingAlgorithm> {
Err(errors::StorageError::MockDbError)?
}
@@ -218,7 +218,7 @@ impl RoutingAlgorithmInterface for MockDb {
async fn list_routing_algorithm_metadata_by_merchant_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_limit: i64,
_offset: i64,
) -> StorageResult<Vec<routing_storage::RoutingProfileMetadata>> {
@@ -227,7 +227,7 @@ impl RoutingAlgorithmInterface for MockDb {
async fn list_routing_algorithm_metadata_by_merchant_id_transaction_type(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_transaction_type: &common_enums::TransactionType,
_limit: i64,
_offset: i64,
diff --git a/crates/router/src/db/user/sample_data.rs b/crates/router/src/db/user/sample_data.rs
index cabf62b850e..3bcbb624cb0 100644
--- a/crates/router/src/db/user/sample_data.rs
+++ b/crates/router/src/db/user/sample_data.rs
@@ -39,18 +39,18 @@ pub trait BatchSampleDataInterface {
async fn delete_payment_intents_for_sample_data(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentIntent>, StorageError>;
async fn delete_payment_attempts_for_sample_data(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<PaymentAttempt>, StorageError>;
async fn delete_refunds_for_sample_data(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<Refund>, StorageError>;
}
@@ -81,7 +81,7 @@ impl BatchSampleDataInterface for Store {
state,
payment_intent,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
}))
.map(|join_result| join_result.change_context(StorageError::DecryptionError))
@@ -120,7 +120,7 @@ impl BatchSampleDataInterface for Store {
async fn delete_payment_intents_for_sample_data(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
let conn = pg_connection_write(self)
@@ -135,7 +135,7 @@ impl BatchSampleDataInterface for Store {
state,
payment_intent,
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
}))
.map(|join_result| join_result.change_context(StorageError::DecryptionError))
@@ -145,7 +145,7 @@ impl BatchSampleDataInterface for Store {
async fn delete_payment_attempts_for_sample_data(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
let conn = pg_connection_write(self)
.await
@@ -161,7 +161,7 @@ impl BatchSampleDataInterface for Store {
}
async fn delete_refunds_for_sample_data(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<Refund>, StorageError> {
let conn = pg_connection_write(self)
.await
@@ -200,20 +200,20 @@ impl BatchSampleDataInterface for storage_impl::MockDb {
async fn delete_payment_intents_for_sample_data(
&self,
_state: &KeyManagerState,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_key_store: &MerchantKeyStore,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
Err(StorageError::MockDbError)?
}
async fn delete_payment_attempts_for_sample_data(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
Err(StorageError::MockDbError)?
}
async fn delete_refunds_for_sample_data(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<Refund>, StorageError> {
Err(StorageError::MockDbError)?
}
diff --git a/crates/router/src/db/user_key_store.rs b/crates/router/src/db/user_key_store.rs
index 111989a293e..eef0d0c8378 100644
--- a/crates/router/src/db/user_key_store.rs
+++ b/crates/router/src/db/user_key_store.rs
@@ -1,4 +1,7 @@
-use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState};
+use common_utils::{
+ errors::CustomResult,
+ types::keymanager::{self, KeyManagerState},
+};
use error_stack::{report, ResultExt};
use masking::Secret;
use router_env::{instrument, tracing};
@@ -57,7 +60,7 @@ impl UserKeyStoreInterface for Store {
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
- .convert(state, key, user_id)
+ .convert(state, key, keymanager::Identifier::User(user_id))
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -74,7 +77,7 @@ impl UserKeyStoreInterface for Store {
diesel_models::user_key_store::UserKeyStore::find_by_user_id(&conn, user_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?
- .convert(state, key, user_id.to_string())
+ .convert(state, key, keymanager::Identifier::User(user_id.to_owned()))
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -96,7 +99,7 @@ impl UserKeyStoreInterface for Store {
futures::future::try_join_all(key_stores.into_iter().map(|key_store| async {
let user_id = key_store.user_id.clone();
key_store
- .convert(state, key, user_id)
+ .convert(state, key, keymanager::Identifier::User(user_id))
.await
.change_context(errors::StorageError::DecryptionError)
}))
@@ -131,7 +134,7 @@ impl UserKeyStoreInterface for MockDb {
locked_user_key_store.push(user_key_store.clone());
let user_id = user_key_store.user_id.clone();
user_key_store
- .convert(state, key, user_id)
+ .convert(state, key, keymanager::Identifier::User(user_id))
.await
.change_context(errors::StorageError::DecryptionError)
}
@@ -149,7 +152,7 @@ impl UserKeyStoreInterface for MockDb {
let user_id = user_key.user_id.clone();
user_key
.to_owned()
- .convert(state, key, user_id)
+ .convert(state, key, keymanager::Identifier::User(user_id))
.await
.change_context(errors::StorageError::DecryptionError)
}))
@@ -173,7 +176,7 @@ impl UserKeyStoreInterface for MockDb {
"No user_key_store is found for user_id={}",
user_id
)))?
- .convert(state, key, user_id.to_string())
+ .convert(state, key, keymanager::Identifier::User(user_id.to_owned()))
.await
.change_context(errors::StorageError::DecryptionError)
}
diff --git a/crates/router/src/db/user_role.rs b/crates/router/src/db/user_role.rs
index 50ea4ecc9ac..7f16cedd570 100644
--- a/crates/router/src/db/user_role.rs
+++ b/crates/router/src/db/user_role.rs
@@ -28,13 +28,13 @@ pub trait UserRoleInterface {
async fn find_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<storage::UserRole, errors::StorageError>;
async fn update_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
update: storage::UserRoleUpdate,
) -> CustomResult<storage::UserRole, errors::StorageError>;
@@ -48,7 +48,7 @@ pub trait UserRoleInterface {
async fn delete_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<storage::UserRole, errors::StorageError>;
async fn list_user_roles_by_user_id(
@@ -58,7 +58,7 @@ pub trait UserRoleInterface {
async fn list_user_roles_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError>;
async fn transfer_org_ownership_between_users(
@@ -98,7 +98,7 @@ impl UserRoleInterface for Store {
async fn find_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::UserRole::find_by_user_id_merchant_id(
@@ -114,7 +114,7 @@ impl UserRoleInterface for Store {
async fn update_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
update: storage::UserRoleUpdate,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -150,7 +150,7 @@ impl UserRoleInterface for Store {
async fn delete_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
@@ -177,7 +177,7 @@ impl UserRoleInterface for Store {
#[instrument(skip_all)]
async fn list_user_roles_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::UserRole::list_by_merchant_id(&conn, merchant_id.to_owned())
@@ -224,7 +224,7 @@ impl UserRoleInterface for Store {
let new_org_admin_merchant_ids = new_org_admin_user_roles
.iter()
.map(|user_role| user_role.merchant_id.to_owned())
- .collect::<HashSet<String>>();
+ .collect::<HashSet<_>>();
let now = common_utils::date_time::now();
@@ -318,16 +318,16 @@ impl UserRoleInterface for MockDb {
async fn find_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let user_roles = self.user_roles.lock().await;
user_roles
.iter()
- .find(|user_role| user_role.user_id == user_id && user_role.merchant_id == merchant_id)
+ .find(|user_role| user_role.user_id == user_id && user_role.merchant_id == *merchant_id)
.cloned()
.ok_or(
errors::StorageError::ValueNotFound(format!(
- "No user role available for user_id = {user_id} and merchant_id = {merchant_id}"
+ "No user role available for user_id = {user_id} and merchant_id = {merchant_id:?}"
))
.into(),
)
@@ -336,13 +336,13 @@ impl UserRoleInterface for MockDb {
async fn update_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
update: storage::UserRoleUpdate,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let mut user_roles = self.user_roles.lock().await;
user_roles
.iter_mut()
- .find(|user_role| user_role.user_id == user_id && user_role.merchant_id == merchant_id)
+ .find(|user_role| user_role.user_id == user_id && user_role.merchant_id == *merchant_id)
.map(|user_role| {
*user_role = match &update {
storage::UserRoleUpdate::UpdateRole {
@@ -366,7 +366,7 @@ impl UserRoleInterface for MockDb {
})
.ok_or(
errors::StorageError::ValueNotFound(format!(
- "No user role available for user_id = {user_id} and merchant_id = {merchant_id}"
+ "No user role available for user_id = {user_id} and merchant_id = {merchant_id:?}"
))
.into(),
)
@@ -442,7 +442,7 @@ impl UserRoleInterface for MockDb {
let new_org_admin_merchant_ids = new_org_admin_user_roles
.iter()
.map(|user_role| user_role.merchant_id.to_owned())
- .collect::<HashSet<String>>();
+ .collect::<HashSet<_>>();
let now = common_utils::date_time::now();
@@ -476,13 +476,13 @@ impl UserRoleInterface for MockDb {
async fn delete_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<storage::UserRole, errors::StorageError> {
let mut user_roles = self.user_roles.lock().await;
match user_roles
.iter()
- .position(|role| role.user_id == user_id && role.merchant_id == merchant_id)
+ .position(|role| role.user_id == user_id && role.merchant_id == *merchant_id)
{
Some(index) => Ok(user_roles.remove(index)),
None => Err(errors::StorageError::ValueNotFound(
@@ -512,7 +512,7 @@ impl UserRoleInterface for MockDb {
async fn list_user_roles_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
let user_roles = self.user_roles.lock().await;
@@ -520,7 +520,7 @@ impl UserRoleInterface for MockDb {
.iter()
.cloned()
.filter_map(|ele| {
- if ele.merchant_id == merchant_id {
+ if ele.merchant_id == *merchant_id {
return Some(ele);
}
None
@@ -541,7 +541,7 @@ impl UserRoleInterface for super::KafkaStore {
async fn update_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
update: storage::UserRoleUpdate,
) -> CustomResult<storage::UserRole, errors::StorageError> {
self.diesel_store
@@ -557,7 +557,7 @@ impl UserRoleInterface for super::KafkaStore {
async fn delete_user_role_by_user_id_merchant_id(
&self,
user_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<storage::UserRole, errors::StorageError> {
self.diesel_store
.delete_user_role_by_user_id_merchant_id(user_id, merchant_id)
@@ -571,7 +571,7 @@ impl UserRoleInterface for super::KafkaStore {
}
async fn list_user_roles_by_merchant_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<storage::UserRole>, errors::StorageError> {
self.diesel_store
.list_user_roles_by_merchant_id(merchant_id)
diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs
index 9eb8f1021aa..e818b7440b0 100644
--- a/crates/router/src/events/api_logs.rs
+++ b/crates/router/src/events/api_logs.rs
@@ -24,7 +24,7 @@ use crate::{
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct ApiEvent {
- merchant_id: Option<String>,
+ merchant_id: Option<common_utils::id_type::MerchantId>,
api_flow: String,
created_at_timestamp: i128,
request_id: String,
@@ -47,7 +47,7 @@ pub struct ApiEvent {
impl ApiEvent {
#[allow(clippy::too_many_arguments)]
pub fn new(
- merchant_id: Option<String>,
+ merchant_id: Option<common_utils::id_type::MerchantId>,
api_flow: &impl FlowMetric,
request_id: &RequestId,
latency: u128,
diff --git a/crates/router/src/events/outgoing_webhook_logs.rs b/crates/router/src/events/outgoing_webhook_logs.rs
index 9accf0ff0d6..7ab100c2503 100644
--- a/crates/router/src/events/outgoing_webhook_logs.rs
+++ b/crates/router/src/events/outgoing_webhook_logs.rs
@@ -9,7 +9,7 @@ use crate::services::kafka::KafkaMessage;
#[derive(Clone, Debug, PartialEq, Serialize)]
#[serde(rename_all = "snake_case")]
pub struct OutgoingWebhookEvent {
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
event_id: String,
event_type: OutgoingWebhookEventType,
#[serde(flatten)]
@@ -90,7 +90,7 @@ impl OutgoingWebhookEventMetric for OutgoingWebhookContent {
impl OutgoingWebhookEvent {
pub fn new(
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
event_id: String,
event_type: OutgoingWebhookEventType,
content: Option<OutgoingWebhookEventContent>,
diff --git a/crates/router/src/routes/admin.rs b/crates/router/src/routes/admin.rs
index e6c4ff8dc6b..05f65b8e477 100644
--- a/crates/router/src/routes/admin.rs
+++ b/crates/router/src/routes/admin.rs
@@ -1,6 +1,4 @@
use actix_web::{web, HttpRequest, HttpResponse};
-#[cfg(feature = "olap")]
-use common_utils::id_type;
use router_env::{instrument, tracing, Flow};
use super::app::AppState;
@@ -35,7 +33,7 @@ pub async fn organization_create(
pub async fn organization_update(
state: web::Data<AppState>,
req: HttpRequest,
- org_id: web::Path<id_type::OrganizationId>,
+ org_id: web::Path<common_utils::id_type::OrganizationId>,
json_payload: web::Json<admin::OrganizationRequest>,
) -> HttpResponse {
let flow = Flow::OrganizationUpdate;
@@ -58,7 +56,7 @@ pub async fn organization_update(
pub async fn organization_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
- org_id: web::Path<id_type::OrganizationId>,
+ org_id: web::Path<common_utils::id_type::OrganizationId>,
) -> HttpResponse {
let flow = Flow::OrganizationRetrieve;
let organization_id = org_id.into_inner();
@@ -114,7 +112,7 @@ pub async fn merchant_account_create(
pub async fn retrieve_merchant_account(
state: web::Data<AppState>,
req: HttpRequest,
- mid: web::Path<String>,
+ mid: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::MerchantsAccountRetrieve;
let merchant_id = mid.into_inner();
@@ -181,7 +179,7 @@ pub async fn merchant_account_list(
pub async fn update_merchant_account(
state: web::Data<AppState>,
req: HttpRequest,
- mid: web::Path<String>,
+ mid: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<admin::MerchantAccountUpdate>,
) -> HttpResponse {
let flow = Flow::MerchantsAccountUpdate;
@@ -225,7 +223,7 @@ pub async fn update_merchant_account(
pub async fn delete_merchant_account(
state: web::Data<AppState>,
req: HttpRequest,
- mid: web::Path<String>,
+ mid: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::MerchantsAccountDelete;
let mid = mid.into_inner();
@@ -261,7 +259,7 @@ pub async fn delete_merchant_account(
pub async fn payment_connector_create(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<String>,
+ path: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<admin::MerchantConnectorCreate>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsCreate;
@@ -307,7 +305,7 @@ pub async fn payment_connector_create(
pub async fn payment_connector_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsRetrieve;
let (merchant_id, merchant_connector_id) = path.into_inner();
@@ -359,7 +357,7 @@ pub async fn payment_connector_retrieve(
pub async fn payment_connector_list(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<String>,
+ path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsList;
let merchant_id = path.into_inner();
@@ -406,7 +404,7 @@ pub async fn payment_connector_list(
pub async fn payment_connector_update(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
json_payload: web::Json<api_models::admin::MerchantConnectorUpdate>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsUpdate;
@@ -455,7 +453,7 @@ pub async fn payment_connector_update(
pub async fn payment_connector_delete(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> HttpResponse {
let flow = Flow::MerchantConnectorsDelete;
let (merchant_id, merchant_connector_id) = path.into_inner();
@@ -492,7 +490,7 @@ pub async fn payment_connector_delete(
pub async fn merchant_account_toggle_kv(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<String>,
+ path: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<admin::ToggleKVRequest>,
) -> HttpResponse {
let flow = Flow::ConfigKeyUpdate;
@@ -540,7 +538,7 @@ pub async fn business_profile_create(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<admin::BusinessProfileCreate>,
- path: web::Path<String>,
+ path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::BusinessProfileCreate;
let payload = json_payload.into_inner();
@@ -568,7 +566,7 @@ pub async fn business_profile_create(
pub async fn business_profile_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> HttpResponse {
let flow = Flow::BusinessProfileRetrieve;
let (merchant_id, profile_id) = path.into_inner();
@@ -595,7 +593,7 @@ pub async fn business_profile_retrieve(
pub async fn business_profile_update(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
json_payload: web::Json<api_models::admin::BusinessProfileUpdate>,
) -> HttpResponse {
let flow = Flow::BusinessProfileUpdate;
@@ -623,7 +621,7 @@ pub async fn business_profile_update(
pub async fn business_profile_delete(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> HttpResponse {
let flow = Flow::BusinessProfileDelete;
let (merchant_id, profile_id) = path.into_inner();
@@ -643,7 +641,7 @@ pub async fn business_profile_delete(
pub async fn business_profiles_list(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<String>,
+ path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::BusinessProfileList;
let merchant_id = path.into_inner();
@@ -671,7 +669,7 @@ pub async fn business_profiles_list(
pub async fn toggle_connector_agnostic_mit(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
json_payload: web::Json<api_models::admin::ConnectorAgnosticMitChoice>,
) -> HttpResponse {
let flow = Flow::ToggleConnectorAgnosticMit;
@@ -699,7 +697,7 @@ pub async fn toggle_connector_agnostic_mit(
pub async fn merchant_account_kv_status(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<String>,
+ path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::ConfigKeyFetch;
let merchant_id = path.into_inner();
diff --git a/crates/router/src/routes/api_keys.rs b/crates/router/src/routes/api_keys.rs
index f1170f0f0bb..3513984979b 100644
--- a/crates/router/src/routes/api_keys.rs
+++ b/crates/router/src/routes/api_keys.rs
@@ -29,7 +29,7 @@ use crate::{
pub async fn api_key_create(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<String>,
+ path: web::Path<common_utils::id_type::MerchantId>,
json_payload: web::Json<api_types::CreateApiKeyRequest>,
) -> impl Responder {
let flow = Flow::ApiKeyCreate;
@@ -78,7 +78,7 @@ pub async fn api_key_create(
pub async fn api_key_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::ApiKeyRetrieve;
let (merchant_id, key_id) = path.into_inner();
@@ -124,7 +124,7 @@ pub async fn api_key_retrieve(
pub async fn api_key_update(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
json_payload: web::Json<api_types::UpdateApiKeyRequest>,
) -> impl Responder {
let flow = Flow::ApiKeyUpdate;
@@ -174,7 +174,7 @@ pub async fn api_key_update(
pub async fn api_key_revoke(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::ApiKeyRevoke;
let (merchant_id, key_id) = path.into_inner();
@@ -219,7 +219,7 @@ pub async fn api_key_revoke(
pub async fn api_key_list(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<String>,
+ path: web::Path<common_utils::id_type::MerchantId>,
query: web::Query<api_types::ListApiKeyConstraints>,
) -> impl Responder {
let flow = Flow::ApiKeyList;
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 0970da6e0ab..309a94c1418 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -170,7 +170,6 @@ pub trait AppStateInfo {
#[cfg(feature = "email")]
fn email_client(&self) -> Arc<dyn EmailService>;
fn add_request_id(&mut self, request_id: RequestId);
- fn add_merchant_id(&mut self, merchant_id: Option<String>);
fn add_flow_name(&mut self, flow_name: String);
fn get_request_id(&self) -> Option<String>;
}
@@ -191,9 +190,6 @@ impl AppStateInfo for AppState {
self.request_id.replace(request_id);
}
- fn add_merchant_id(&mut self, merchant_id: Option<String>) {
- self.api_client.add_merchant_id(merchant_id);
- }
fn add_flow_name(&mut self, flow_name: String) {
self.api_client.add_flow_name(flow_name);
}
diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs
index cf89f2f5479..0ccf6f9a77b 100644
--- a/crates/router/src/routes/customers.rs
+++ b/crates/router/src/routes/customers.rs
@@ -81,7 +81,11 @@ pub async fn customers_list(state: web::Data<AppState>, req: HttpRequest) -> Htt
&req,
(),
|state, auth, _, _| {
- list_customers(state, auth.merchant_account.merchant_id, auth.key_store)
+ list_customers(
+ state,
+ auth.merchant_account.get_id().to_owned(),
+ auth.key_store,
+ )
},
auth::auth_type(
&auth::ApiKeyAuth,
diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs
index 9b100938468..93041bbd0a3 100644
--- a/crates/router/src/routes/ephemeral_key.rs
+++ b/crates/router/src/routes/ephemeral_key.rs
@@ -25,7 +25,7 @@ pub async fn ephemeral_key_create(
helpers::make_ephemeral_key(
state,
req.get_merchant_reference_id(),
- auth.merchant_account.merchant_id,
+ auth.merchant_account.get_id().to_owned(),
)
},
&auth::ApiKeyAuth,
diff --git a/crates/router/src/routes/locker_migration.rs b/crates/router/src/routes/locker_migration.rs
index 2a8b1ca7911..6ebad773779 100644
--- a/crates/router/src/routes/locker_migration.rs
+++ b/crates/router/src/routes/locker_migration.rs
@@ -10,7 +10,7 @@ use crate::{
pub async fn rust_locker_migration(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<String>,
+ path: web::Path<common_utils::id_type::MerchantId>,
) -> HttpResponse {
let flow = Flow::RustLockerMigration;
let merchant_id = path.into_inner();
diff --git a/crates/router/src/routes/metrics/request.rs b/crates/router/src/routes/metrics/request.rs
index 5ec2692da99..572f3dc9330 100644
--- a/crates/router/src/routes/metrics/request.rs
+++ b/crates/router/src/routes/metrics/request.rs
@@ -25,14 +25,18 @@ where
result
}
-pub fn status_code_metrics(status_code: String, flow: String, merchant_id: String) {
+pub fn status_code_metrics(
+ status_code: String,
+ flow: String,
+ merchant_id: common_utils::id_type::MerchantId,
+) {
super::REQUEST_STATUS.add(
&super::CONTEXT,
1,
&add_attributes([
("status_code", status_code),
("flow", flow),
- ("merchant_id", merchant_id),
+ ("merchant_id", merchant_id.get_string_repr().to_owned()),
]),
)
}
diff --git a/crates/router/src/routes/payment_link.rs b/crates/router/src/routes/payment_link.rs
index fed182f03a8..33d3c21ef9f 100644
--- a/crates/router/src/routes/payment_link.rs
+++ b/crates/router/src/routes/payment_link.rs
@@ -54,7 +54,7 @@ pub async fn payment_link_retrieve(
pub async fn initiate_payment_link(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::PaymentLinkInitiate;
let (merchant_id, payment_id) = path.into_inner();
@@ -128,7 +128,7 @@ pub async fn payments_link_list(
pub async fn payment_link_status(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::PaymentLinkStatus;
let (merchant_id, payment_id) = path.into_inner();
diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rs
index 17a3a21d0ee..05d56c8248f 100644
--- a/crates/router/src/routes/payment_methods.rs
+++ b/crates/router/src/routes/payment_methods.rs
@@ -95,7 +95,7 @@ pub async fn migrate_payment_method_api(
async fn get_merchant_account(
state: &SessionState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<(MerchantKeyStore, domain::MerchantAccount), errors::ApiErrorResponse> {
let key_manager_state = &state.into();
let key_store = state
@@ -131,33 +131,36 @@ pub async fn migrate_payment_methods(
Ok((merchant_id, records)) => (merchant_id, records),
Err(e) => return api::log_and_return_error_response(e.into()),
};
- let merchant_id = merchant_id.as_str();
Box::pin(api::server_wrap(
flow,
state,
&req,
records,
- |state, _, req, _| async move {
- let (key_store, merchant_account) = get_merchant_account(&state, merchant_id).await?;
- // Create customers if they are not already present
- customers::migrate_customers(
- state.clone(),
- req.iter()
- .map(|e| CustomerRequest::from(e.clone()))
- .collect(),
- merchant_account.clone(),
- key_store.clone(),
- )
- .await
- .change_context(errors::ApiErrorResponse::InternalServerError)?;
- Box::pin(migration::migrate_payment_methods(
- state,
- req,
- merchant_id,
- &merchant_account,
- &key_store,
- ))
- .await
+ |state, _, req, _| {
+ let merchant_id = merchant_id.clone();
+ async move {
+ let (key_store, merchant_account) =
+ get_merchant_account(&state, &merchant_id).await?;
+ // Create customers if they are not already present
+ customers::migrate_customers(
+ state.clone(),
+ req.iter()
+ .map(|e| CustomerRequest::from(e.clone()))
+ .collect(),
+ merchant_account.clone(),
+ key_store.clone(),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+ Box::pin(migration::migrate_payment_methods(
+ state,
+ req,
+ &merchant_id,
+ &merchant_account,
+ &key_store,
+ ))
+ .await
+ }
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
@@ -376,7 +379,7 @@ pub async fn initiate_pm_collect_link_flow(
pub async fn render_pm_collect_link(
state: web::Data<AppState>,
req: HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(id_type::MerchantId, String)>,
) -> HttpResponse {
let flow = Flow::PaymentMethodCollectLink;
let (merchant_id, pm_collect_link_id) = path.into_inner();
@@ -546,7 +549,7 @@ pub async fn default_payment_method_set_api(
|state, auth: auth::AuthenticationData, default_payment_method, _| async move {
cards::set_default_payment_method(
&state,
- auth.merchant_account.merchant_id,
+ auth.merchant_account.get_id(),
auth.key_store,
customer_id,
default_payment_method.payment_method_id,
diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rs
index 008528ee2eb..2bac740d377 100644
--- a/crates/router/src/routes/payments.rs
+++ b/crates/router/src/routes/payments.rs
@@ -170,7 +170,7 @@ pub async fn payments_create(
pub async fn payments_start(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
- path: web::Path<(String, String, String)>,
+ path: web::Path<(String, common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::PaymentsStart;
let (payment_id, merchant_id, attempt_id) = path.into_inner();
@@ -661,7 +661,7 @@ pub async fn payments_redirect_response(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
- path: web::Path<(String, String, String)>,
+ path: web::Path<(String, common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::PaymentsRedirect;
let (payment_id, merchant_id, connector) = path.into_inner();
@@ -723,7 +723,7 @@ pub async fn payments_redirect_response(
pub async fn payments_redirect_response_with_creds_identifier(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
- path: web::Path<(String, String, String, String)>,
+ path: web::Path<(String, common_utils::id_type::MerchantId, String, String)>,
) -> impl Responder {
let (payment_id, merchant_id, connector, creds_identifier) = path.into_inner();
let param_string = req.query_string();
@@ -767,7 +767,7 @@ pub async fn payments_complete_authorize_redirect(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
- path: web::Path<(String, String, String)>,
+ path: web::Path<(String, common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::PaymentsRedirect;
let (payment_id, merchant_id, connector) = path.into_inner();
@@ -1365,7 +1365,7 @@ pub async fn post_3ds_payments_authorize(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: Option<web::Form<serde_json::Value>>,
- path: web::Path<(String, String, String)>,
+ path: web::Path<(String, common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::PaymentsAuthorize;
@@ -1450,7 +1450,11 @@ pub async fn retrieve_extended_card_info(
&req,
payment_id,
|state, auth, payment_id, _| {
- payments::get_extended_card_info(state, auth.merchant_account.merchant_id, payment_id)
+ payments::get_extended_card_info(
+ state,
+ auth.merchant_account.get_id().to_owned(),
+ payment_id,
+ )
},
&auth::ApiKeyAuth,
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/routes/payout_link.rs b/crates/router/src/routes/payout_link.rs
index e3a0327c329..7bac4c5519c 100644
--- a/crates/router/src/routes/payout_link.rs
+++ b/crates/router/src/routes/payout_link.rs
@@ -15,7 +15,7 @@ use crate::{
pub async fn render_payout_link(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::PayoutLinkInitiate;
let (merchant_id, payout_id) = path.into_inner();
diff --git a/crates/router/src/routes/recon.rs b/crates/router/src/routes/recon.rs
index d8100e8d341..be489a8ea06 100644
--- a/crates/router/src/routes/recon.rs
+++ b/crates/router/src/routes/recon.rs
@@ -89,13 +89,13 @@ pub async fn send_recon_request(
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- merchant_id.as_str(),
+ &merchant_id,
&db.get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let merchant_account = db
- .find_merchant_account_by_merchant_id(key_manager_state, merchant_id.as_str(), &key_store)
+ .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
diff --git a/crates/router/src/routes/verification.rs b/crates/router/src/routes/verification.rs
index 00662663113..25e64e95bde 100644
--- a/crates/router/src/routes/verification.rs
+++ b/crates/router/src/routes/verification.rs
@@ -13,7 +13,7 @@ pub async fn apple_pay_merchant_registration(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<verifications::ApplepayMerchantVerificationRequest>,
- path: web::Path<String>,
+ path: web::Path<common_utils::id_type::MerchantId>,
) -> impl Responder {
let flow = Flow::Verification;
let merchant_id = path.into_inner();
@@ -57,7 +57,7 @@ pub async fn retrieve_apple_pay_verified_domains(
|state, _, _, _| {
verification::get_verified_apple_domains_with_mid_mca_id(
state,
- merchant_id.to_string(),
+ merchant_id.to_owned(),
mca_id.to_string(),
)
},
diff --git a/crates/router/src/routes/webhooks.rs b/crates/router/src/routes/webhooks.rs
index a198fe730fe..43b50b04601 100644
--- a/crates/router/src/routes/webhooks.rs
+++ b/crates/router/src/routes/webhooks.rs
@@ -15,7 +15,7 @@ pub async fn receive_incoming_webhook<W: types::OutgoingWebhookType>(
state: web::Data<AppState>,
req: HttpRequest,
body: web::Bytes,
- path: web::Path<(String, String)>,
+ path: web::Path<(common_utils::id_type::MerchantId, String)>,
) -> impl Responder {
let flow = Flow::IncomingWebhookReceive;
let (merchant_id, connector_id_or_name) = path.into_inner();
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index ea9ce177439..129be81e41e 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -849,14 +849,12 @@ where
let merchant_id = auth_type
.get_merchant_id()
- .unwrap_or("MERCHANT_ID_NOT_FOUND")
- .to_string();
-
- app_state.add_merchant_id(Some(merchant_id.clone()));
+ .cloned()
+ .unwrap_or(common_utils::id_type::MerchantId::get_merchant_id_not_found());
app_state.add_flow_name(flow.to_string());
- tracing::Span::current().record("merchant_id", &merchant_id);
+ tracing::Span::current().record("merchant_id", merchant_id.get_string_repr().to_owned());
let output = {
lock_action
@@ -938,7 +936,7 @@ where
metrics::request::status_code_metrics(
status_code.to_string(),
flow.to_string(),
- merchant_id.to_string(),
+ merchant_id.to_owned(),
);
output
diff --git a/crates/router/src/services/api/client.rs b/crates/router/src/services/api/client.rs
index 4dda8eab627..56bb00b2462 100644
--- a/crates/router/src/services/api/client.rs
+++ b/crates/router/src/services/api/client.rs
@@ -184,7 +184,6 @@ where
fn add_request_id(&mut self, request_id: RequestId);
fn get_request_id(&self) -> Option<String>;
- fn add_merchant_id(&mut self, _merchant_id: Option<String>);
fn add_flow_name(&mut self, flow_name: String);
}
@@ -368,8 +367,6 @@ impl ApiClient for ProxyClient {
self.request_id.clone()
}
- fn add_merchant_id(&mut self, _merchant_id: Option<String>) {}
-
fn add_flow_name(&mut self, _flow_name: String) {}
}
@@ -421,7 +418,5 @@ impl ApiClient for MockApiClient {
None
}
- fn add_merchant_id(&mut self, _merchant_id: Option<String>) {}
-
fn add_flow_name(&mut self, _flow_name: String) {}
}
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index 001eb3d168b..0ee09913e2b 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -56,12 +56,12 @@ pub struct AuthenticationData {
)]
pub enum AuthenticationType {
ApiKey {
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
key_id: String,
},
AdminApiKey,
MerchantJwt {
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
user_id: Option<String>,
},
UserJwt {
@@ -77,13 +77,13 @@ pub enum AuthenticationType {
role_id: Option<String>,
},
MerchantId {
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
},
PublishableKey {
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
},
WebhookAuth {
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
},
NoAuth,
}
@@ -100,7 +100,7 @@ impl events::EventInfo for AuthenticationType {
}
impl AuthenticationType {
- pub fn get_merchant_id(&self) -> Option<&str> {
+ pub fn get_merchant_id(&self) -> Option<&id_type::MerchantId> {
match self {
Self::ApiKey {
merchant_id,
@@ -112,7 +112,7 @@ impl AuthenticationType {
merchant_id,
user_id: _,
}
- | Self::WebhookAuth { merchant_id } => Some(merchant_id.as_ref()),
+ | Self::WebhookAuth { merchant_id } => Some(merchant_id),
Self::AdminApiKey
| Self::UserJwt { .. }
| Self::SinglePurposeJwt { .. }
@@ -166,7 +166,7 @@ impl SinglePurposeToken {
#[derive(serde::Serialize, serde::Deserialize)]
pub struct AuthToken {
pub user_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub role_id: String,
pub exp: u64,
pub org_id: id_type::OrganizationId,
@@ -176,7 +176,7 @@ pub struct AuthToken {
impl AuthToken {
pub async fn new_token(
user_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
role_id: String,
settings: &Settings,
org_id: id_type::OrganizationId,
@@ -197,7 +197,7 @@ impl AuthToken {
#[derive(Clone)]
pub struct UserFromToken {
pub user_id: String,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub role_id: String,
pub org_id: id_type::OrganizationId,
}
@@ -216,18 +216,18 @@ pub struct SinglePurposeOrLoginToken {
}
pub trait AuthInfo {
- fn get_merchant_id(&self) -> Option<&str>;
+ fn get_merchant_id(&self) -> Option<&id_type::MerchantId>;
}
impl AuthInfo for () {
- fn get_merchant_id(&self) -> Option<&str> {
+ fn get_merchant_id(&self) -> Option<&id_type::MerchantId> {
None
}
}
impl AuthInfo for AuthenticationData {
- fn get_merchant_id(&self) -> Option<&str> {
- Some(&self.merchant_account.merchant_id)
+ fn get_merchant_id(&self) -> Option<&id_type::MerchantId> {
+ Some(self.merchant_account.get_id())
}
}
@@ -349,7 +349,7 @@ where
Ok((
auth.clone(),
AuthenticationType::ApiKey {
- merchant_id: auth.merchant_account.merchant_id.clone(),
+ merchant_id: auth.merchant_account.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
@@ -529,7 +529,7 @@ where
}
}
#[derive(Debug)]
-pub struct MerchantIdAuth(pub String);
+pub struct MerchantIdAuth(pub id_type::MerchantId);
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for MerchantIdAuth
@@ -546,7 +546,7 @@ where
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- self.0.as_ref(),
+ &self.0,
&state.store().get_master_key().to_vec().into(),
)
.await
@@ -561,7 +561,7 @@ where
let merchant = state
.store()
- .find_merchant_account_by_merchant_id(key_manager_state, self.0.as_ref(), &key_store)
+ .find_merchant_account_by_merchant_id(key_manager_state, &self.0, &key_store)
.await
.map_err(|e| {
if e.current_context().is_db_not_found() {
@@ -578,7 +578,7 @@ where
Ok((
auth.clone(),
AuthenticationType::MerchantId {
- merchant_id: auth.merchant_account.merchant_id.clone(),
+ merchant_id: auth.merchant_account.get_id().clone(),
},
))
}
@@ -615,7 +615,7 @@ where
(
auth.clone(),
AuthenticationType::PublishableKey {
- merchant_id: auth.merchant_account.merchant_id.clone(),
+ merchant_id: auth.merchant_account.get_id().clone(),
},
)
})
@@ -694,7 +694,7 @@ where
}
pub struct JWTAuthMerchantFromRoute {
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub required_permission: Permission,
}
@@ -754,7 +754,7 @@ where
authorization::check_authorization(&self.required_permission, &permissions)?;
// Check if token has access to MerchantId that has been requested through path or query param
- if payload.merchant_id == self.merchant_id_or_profile_id {
+ if payload.merchant_id.get_string_repr() == self.merchant_id_or_profile_id {
return Ok((
(),
AuthenticationType::MerchantJwt {
@@ -856,7 +856,7 @@ where
Ok((
auth.clone(),
AuthenticationType::MerchantJwt {
- merchant_id: auth.merchant_account.merchant_id.clone(),
+ merchant_id: auth.merchant_account.get_id().clone(),
user_id: None,
},
))
@@ -911,7 +911,7 @@ where
Ok((
(auth.clone(), payload.user_id.clone()),
AuthenticationType::MerchantJwt {
- merchant_id: auth.merchant_account.merchant_id.clone(),
+ merchant_id: auth.merchant_account.get_id().clone(),
user_id: None,
},
))
@@ -1011,7 +1011,7 @@ where
Ok((
auth.clone(),
AuthenticationType::MerchantJwt {
- merchant_id: auth.merchant_account.merchant_id.clone(),
+ merchant_id: auth.merchant_account.get_id().clone(),
user_id: Some(payload.user_id),
},
))
@@ -1281,7 +1281,7 @@ pub struct ReconUser {
}
#[cfg(feature = "recon")]
impl AuthInfo for ReconUser {
- fn get_merchant_id(&self) -> Option<&str> {
+ fn get_merchant_id(&self) -> Option<&id_type::MerchantId> {
None
}
}
diff --git a/crates/router/src/services/authentication/decision.rs b/crates/router/src/services/authentication/decision.rs
index 2a48a8c318b..d665b0caaf4 100644
--- a/crates/router/src/services/authentication/decision.rs
+++ b/crates/router/src/services/authentication/decision.rs
@@ -65,7 +65,10 @@ pub enum AuthRuleType {
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Identifiers {
/// [`ApiKey`] is an authentication method that uses an API key. This is used with [`ApiKey`]
- ApiKey { merchant_id: String, key_id: String },
+ ApiKey {
+ merchant_id: common_utils::id_type::MerchantId,
+ key_id: String,
+ },
/// [`PublishableKey`] is an authentication method that uses a publishable key. This is used with [`PublishableKey`]
PublishableKey { merchant_id: String },
}
@@ -76,7 +79,7 @@ pub enum Identifiers {
pub async fn add_api_key(
state: &SessionState,
api_key: Secret<String>,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
key_id: String,
expiry: Option<u64>,
) -> CustomResult<(), ApiClientError> {
@@ -104,7 +107,7 @@ pub async fn add_api_key(
pub async fn add_publishable_key(
state: &SessionState,
api_key: Secret<String>,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
expiry: Option<u64>,
) -> CustomResult<(), ApiClientError> {
let decision_config = if let Some(config) = &state.conf.decision {
@@ -118,7 +121,9 @@ pub async fn add_publishable_key(
expiry,
variant: AuthRuleType::ApiKey {
api_key,
- identifiers: Identifiers::PublishableKey { merchant_id },
+ identifiers: Identifiers::PublishableKey {
+ merchant_id: merchant_id.get_string_repr().to_owned(),
+ },
},
};
diff --git a/crates/router/src/services/authorization.rs b/crates/router/src/services/authorization.rs
index 2fb809d482f..ea1264bde06 100644
--- a/crates/router/src/services/authorization.rs
+++ b/crates/router/src/services/authorization.rs
@@ -79,7 +79,7 @@ fn get_permissions_from_predefined_roles(role_id: &str) -> Option<Vec<permission
async fn get_permissions_from_db<A>(
state: &A,
role_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> RouterResult<Vec<permissions::Permission>>
where
diff --git a/crates/router/src/services/authorization/roles.rs b/crates/router/src/services/authorization/roles.rs
index 5ffd99a2d04..cda2371282a 100644
--- a/crates/router/src/services/authorization/roles.rs
+++ b/crates/router/src/services/authorization/roles.rs
@@ -69,7 +69,7 @@ impl RoleInfo {
pub async fn from_role_id(
state: &SessionState,
role_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> CustomResult<Self, errors::StorageError> {
if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) {
diff --git a/crates/router/src/services/connector_integration_interface.rs b/crates/router/src/services/connector_integration_interface.rs
index 8af9d0b58c3..d2376feb740 100644
--- a/crates/router/src/services/connector_integration_interface.rs
+++ b/crates/router/src/services/connector_integration_interface.rs
@@ -113,7 +113,7 @@ impl api::IncomingWebhook for ConnectorEnum {
async fn decode_webhook_body(
&self,
request: &IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_name: &str,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
@@ -153,7 +153,7 @@ impl api::IncomingWebhook for ConnectorEnum {
async fn get_webhook_source_verification_merchant_secret(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<api_models::webhooks::ConnectorWebhookSecrets, errors::ConnectorError> {
@@ -195,7 +195,7 @@ impl api::IncomingWebhook for ConnectorEnum {
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
match self {
@@ -215,7 +215,7 @@ impl api::IncomingWebhook for ConnectorEnum {
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_account_details: crypto::Encryptable<masking::Secret<serde_json::Value>>,
connector_name: &str,
diff --git a/crates/router/src/services/conversion_impls.rs b/crates/router/src/services/conversion_impls.rs
index 741dabe7fac..e5d39bab833 100644
--- a/crates/router/src/services/conversion_impls.rs
+++ b/crates/router/src/services/conversion_impls.rs
@@ -27,7 +27,7 @@ fn get_default_router_data<F, Req, Resp>(
) -> RouterData<F, Req, Resp> {
RouterData {
flow: std::marker::PhantomData,
- merchant_id: get_irrelevant_id_string("merchant_id", flow_name),
+ merchant_id: common_utils::id_type::MerchantId::get_irrelevant_merchant_id(),
customer_id: None,
connector_customer: None,
connector: get_irrelevant_id_string("connector", flow_name),
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index 1d4e77ff68a..56505316a6e 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -47,7 +47,7 @@ pub enum EmailBody {
},
ProFeatureRequest {
feature_name: String,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
user_name: String,
user_email: String,
},
@@ -150,7 +150,7 @@ Email : {user_email}
#[derive(serde::Serialize, serde::Deserialize)]
pub struct EmailToken {
email: String,
- merchant_id: Option<String>,
+ merchant_id: Option<common_utils::id_type::MerchantId>,
flow: domain::Origin,
exp: u64,
}
@@ -158,7 +158,7 @@ pub struct EmailToken {
impl EmailToken {
pub async fn new_token(
email: domain::UserEmail,
- merchant_id: Option<String>,
+ merchant_id: Option<common_utils::id_type::MerchantId>,
flow: domain::Origin,
settings: &configs::Settings,
) -> CustomResult<String, UserErrors> {
@@ -177,8 +177,8 @@ impl EmailToken {
pii::Email::try_from(self.email.clone())
}
- pub fn get_merchant_id(&self) -> Option<&str> {
- self.merchant_id.as_deref()
+ pub fn get_merchant_id(&self) -> Option<&common_utils::id_type::MerchantId> {
+ self.merchant_id.as_ref()
}
pub fn get_flow(&self) -> domain::Origin {
@@ -325,7 +325,7 @@ pub struct InviteUser {
pub user_name: domain::UserName,
pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub auth_id: Option<String>,
}
@@ -366,7 +366,7 @@ pub struct InviteRegisteredUser {
pub user_name: domain::UserName,
pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub auth_id: Option<String>,
}
@@ -476,7 +476,7 @@ impl EmailData for BizEmailProd {
pub struct ProFeatureRequest {
pub recipient_email: domain::UserEmail,
pub feature_name: String,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub user_name: domain::UserName,
pub settings: std::sync::Arc<configs::Settings>,
pub subject: String,
diff --git a/crates/router/src/services/kafka/authentication.rs b/crates/router/src/services/kafka/authentication.rs
index dce648aff64..be3e0933342 100644
--- a/crates/router/src/services/kafka/authentication.rs
+++ b/crates/router/src/services/kafka/authentication.rs
@@ -4,7 +4,7 @@ use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaAuthentication<'a> {
pub authentication_id: &'a String,
- pub merchant_id: &'a String,
+ pub merchant_id: &'a common_utils::id_type::MerchantId,
pub authentication_connector: &'a String,
pub connector_authentication_id: Option<&'a String>,
pub authentication_data: Option<serde_json::Value>,
@@ -88,7 +88,11 @@ impl<'a> KafkaAuthentication<'a> {
impl<'a> super::KafkaMessage for KafkaAuthentication<'a> {
fn key(&self) -> String {
- format!("{}_{}", self.merchant_id, self.authentication_id)
+ format!(
+ "{}_{}",
+ self.merchant_id.get_string_repr(),
+ self.authentication_id
+ )
}
fn event_type(&self) -> crate::events::EventType {
diff --git a/crates/router/src/services/kafka/authentication_event.rs b/crates/router/src/services/kafka/authentication_event.rs
index 6dbebe6ca76..3f10c7596ac 100644
--- a/crates/router/src/services/kafka/authentication_event.rs
+++ b/crates/router/src/services/kafka/authentication_event.rs
@@ -5,7 +5,7 @@ use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaAuthenticationEvent<'a> {
pub authentication_id: &'a String,
- pub merchant_id: &'a String,
+ pub merchant_id: &'a common_utils::id_type::MerchantId,
pub authentication_connector: &'a String,
pub connector_authentication_id: Option<&'a String>,
pub authentication_data: Option<serde_json::Value>,
@@ -89,7 +89,11 @@ impl<'a> KafkaAuthenticationEvent<'a> {
impl<'a> super::KafkaMessage for KafkaAuthenticationEvent<'a> {
fn key(&self) -> String {
- format!("{}_{}", self.merchant_id, self.authentication_id)
+ format!(
+ "{}_{}",
+ self.merchant_id.get_string_repr(),
+ self.authentication_id
+ )
}
fn event_type(&self) -> crate::events::EventType {
diff --git a/crates/router/src/services/kafka/dispute.rs b/crates/router/src/services/kafka/dispute.rs
index 1950fb253a7..b4b493a79df 100644
--- a/crates/router/src/services/kafka/dispute.rs
+++ b/crates/router/src/services/kafka/dispute.rs
@@ -13,7 +13,7 @@ pub struct KafkaDispute<'a> {
pub dispute_status: &'a storage_enums::DisputeStatus,
pub payment_id: &'a String,
pub attempt_id: &'a String,
- pub merchant_id: &'a String,
+ pub merchant_id: &'a common_utils::id_type::MerchantId,
pub connector_status: &'a String,
pub connector_dispute_id: &'a String,
pub connector_reason: Option<&'a String>,
@@ -66,7 +66,9 @@ impl<'a> super::KafkaMessage for KafkaDispute<'a> {
fn key(&self) -> String {
format!(
"{}_{}_{}",
- self.merchant_id, self.payment_id, self.dispute_id
+ self.merchant_id.get_string_repr(),
+ self.payment_id,
+ self.dispute_id
)
}
diff --git a/crates/router/src/services/kafka/dispute_event.rs b/crates/router/src/services/kafka/dispute_event.rs
index 71e0a11e04d..d6cb5d58491 100644
--- a/crates/router/src/services/kafka/dispute_event.rs
+++ b/crates/router/src/services/kafka/dispute_event.rs
@@ -14,7 +14,7 @@ pub struct KafkaDisputeEvent<'a> {
pub dispute_status: &'a storage_enums::DisputeStatus,
pub payment_id: &'a String,
pub attempt_id: &'a String,
- pub merchant_id: &'a String,
+ pub merchant_id: &'a common_utils::id_type::MerchantId,
pub connector_status: &'a String,
pub connector_dispute_id: &'a String,
pub connector_reason: Option<&'a String>,
@@ -67,7 +67,9 @@ impl<'a> super::KafkaMessage for KafkaDisputeEvent<'a> {
fn key(&self) -> String {
format!(
"{}_{}_{}",
- self.merchant_id, self.payment_id, self.dispute_id
+ self.merchant_id.get_string_repr(),
+ self.payment_id,
+ self.dispute_id
)
}
diff --git a/crates/router/src/services/kafka/fraud_check.rs b/crates/router/src/services/kafka/fraud_check.rs
index e52fbbbc9ac..cf67ac14dd9 100644
--- a/crates/router/src/services/kafka/fraud_check.rs
+++ b/crates/router/src/services/kafka/fraud_check.rs
@@ -10,7 +10,7 @@ use time::OffsetDateTime;
pub struct KafkaFraudCheck<'a> {
pub frm_id: &'a String,
pub payment_id: &'a String,
- pub merchant_id: &'a String,
+ pub merchant_id: &'a common_utils::id_type::MerchantId,
pub attempt_id: &'a String,
#[serde(with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
@@ -57,7 +57,10 @@ impl<'a> super::KafkaMessage for KafkaFraudCheck<'a> {
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
- self.merchant_id, self.payment_id, self.attempt_id, self.frm_id
+ self.merchant_id.get_string_repr(),
+ self.payment_id,
+ self.attempt_id,
+ self.frm_id
)
}
diff --git a/crates/router/src/services/kafka/fraud_check_event.rs b/crates/router/src/services/kafka/fraud_check_event.rs
index 57dc4d20876..88d1465ce1d 100644
--- a/crates/router/src/services/kafka/fraud_check_event.rs
+++ b/crates/router/src/services/kafka/fraud_check_event.rs
@@ -9,7 +9,7 @@ use time::OffsetDateTime;
pub struct KafkaFraudCheckEvent<'a> {
pub frm_id: &'a String,
pub payment_id: &'a String,
- pub merchant_id: &'a String,
+ pub merchant_id: &'a common_utils::id_type::MerchantId,
pub attempt_id: &'a String,
#[serde(default, with = "time::serde::timestamp::milliseconds")]
pub created_at: OffsetDateTime,
@@ -56,7 +56,10 @@ impl<'a> super::KafkaMessage for KafkaFraudCheckEvent<'a> {
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
- self.merchant_id, self.payment_id, self.attempt_id, self.frm_id
+ self.merchant_id.get_string_repr(),
+ self.payment_id,
+ self.attempt_id,
+ self.frm_id
)
}
diff --git a/crates/router/src/services/kafka/payment_attempt.rs b/crates/router/src/services/kafka/payment_attempt.rs
index c321093776c..df566ad8a8d 100644
--- a/crates/router/src/services/kafka/payment_attempt.rs
+++ b/crates/router/src/services/kafka/payment_attempt.rs
@@ -9,7 +9,7 @@ use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttempt<'a> {
pub payment_id: &'a String,
- pub merchant_id: &'a String,
+ pub merchant_id: &'a common_utils::id_type::MerchantId,
pub attempt_id: &'a String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
@@ -108,7 +108,9 @@ impl<'a> super::KafkaMessage for KafkaPaymentAttempt<'a> {
fn key(&self) -> String {
format!(
"{}_{}_{}",
- self.merchant_id, self.payment_id, self.attempt_id
+ self.merchant_id.get_string_repr(),
+ self.payment_id,
+ self.attempt_id
)
}
diff --git a/crates/router/src/services/kafka/payment_attempt_event.rs b/crates/router/src/services/kafka/payment_attempt_event.rs
index bb4d69eda27..95c5d9edd56 100644
--- a/crates/router/src/services/kafka/payment_attempt_event.rs
+++ b/crates/router/src/services/kafka/payment_attempt_event.rs
@@ -10,7 +10,7 @@ use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentAttemptEvent<'a> {
pub payment_id: &'a String,
- pub merchant_id: &'a String,
+ pub merchant_id: &'a common_utils::id_type::MerchantId,
pub attempt_id: &'a String,
pub status: storage_enums::AttemptStatus,
pub amount: MinorUnit,
@@ -109,7 +109,9 @@ impl<'a> super::KafkaMessage for KafkaPaymentAttemptEvent<'a> {
fn key(&self) -> String {
format!(
"{}_{}_{}",
- self.merchant_id, self.payment_id, self.attempt_id
+ self.merchant_id.get_string_repr(),
+ self.payment_id,
+ self.attempt_id
)
}
diff --git a/crates/router/src/services/kafka/payment_intent.rs b/crates/router/src/services/kafka/payment_intent.rs
index 7d9896692a9..d1bd5b2a549 100644
--- a/crates/router/src/services/kafka/payment_intent.rs
+++ b/crates/router/src/services/kafka/payment_intent.rs
@@ -8,7 +8,7 @@ use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentIntent<'a> {
pub payment_id: &'a String,
- pub merchant_id: &'a String,
+ pub merchant_id: &'a id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
@@ -86,7 +86,7 @@ impl<'a> KafkaPaymentIntent<'a> {
impl<'a> super::KafkaMessage for KafkaPaymentIntent<'a> {
fn key(&self) -> String {
- format!("{}_{}", self.merchant_id, self.payment_id)
+ format!("{}_{}", self.merchant_id.get_string_repr(), self.payment_id)
}
fn event_type(&self) -> crate::events::EventType {
diff --git a/crates/router/src/services/kafka/payment_intent_event.rs b/crates/router/src/services/kafka/payment_intent_event.rs
index b11b6b22112..cce53cbd596 100644
--- a/crates/router/src/services/kafka/payment_intent_event.rs
+++ b/crates/router/src/services/kafka/payment_intent_event.rs
@@ -9,7 +9,7 @@ use time::OffsetDateTime;
#[derive(serde::Serialize, Debug)]
pub struct KafkaPaymentIntentEvent<'a> {
pub payment_id: &'a String,
- pub merchant_id: &'a String,
+ pub merchant_id: &'a id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
@@ -87,7 +87,7 @@ impl<'a> KafkaPaymentIntentEvent<'a> {
impl<'a> super::KafkaMessage for KafkaPaymentIntentEvent<'a> {
fn key(&self) -> String {
- format!("{}_{}", self.merchant_id, self.payment_id)
+ format!("{}_{}", self.merchant_id.get_string_repr(), self.payment_id)
}
fn event_type(&self) -> crate::events::EventType {
diff --git a/crates/router/src/services/kafka/payout.rs b/crates/router/src/services/kafka/payout.rs
index 8796d2ca901..655639ed913 100644
--- a/crates/router/src/services/kafka/payout.rs
+++ b/crates/router/src/services/kafka/payout.rs
@@ -7,7 +7,7 @@ use time::OffsetDateTime;
pub struct KafkaPayout<'a> {
pub payout_id: &'a String,
pub payout_attempt_id: &'a String,
- pub merchant_id: &'a String,
+ pub merchant_id: &'a id_type::MerchantId,
pub customer_id: &'a id_type::CustomerId,
pub address_id: &'a String,
pub profile_id: &'a String,
@@ -79,7 +79,11 @@ impl<'a> KafkaPayout<'a> {
impl<'a> super::KafkaMessage for KafkaPayout<'a> {
fn key(&self) -> String {
- format!("{}_{}", self.merchant_id, self.payout_attempt_id)
+ format!(
+ "{}_{}",
+ self.merchant_id.get_string_repr(),
+ self.payout_attempt_id
+ )
}
fn event_type(&self) -> crate::events::EventType {
diff --git a/crates/router/src/services/kafka/refund.rs b/crates/router/src/services/kafka/refund.rs
index 14b317b52ea..1aaf5d2ccb3 100644
--- a/crates/router/src/services/kafka/refund.rs
+++ b/crates/router/src/services/kafka/refund.rs
@@ -7,7 +7,7 @@ pub struct KafkaRefund<'a> {
pub internal_reference_id: &'a String,
pub refund_id: &'a String, //merchant_reference id
pub payment_id: &'a String,
- pub merchant_id: &'a String,
+ pub merchant_id: &'a common_utils::id_type::MerchantId,
pub connector_transaction_id: &'a String,
pub connector: &'a String,
pub connector_refund_id: Option<&'a String>,
@@ -63,7 +63,10 @@ impl<'a> super::KafkaMessage for KafkaRefund<'a> {
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
- self.merchant_id, self.payment_id, self.attempt_id, self.refund_id
+ self.merchant_id.get_string_repr(),
+ self.payment_id,
+ self.attempt_id,
+ self.refund_id
)
}
diff --git a/crates/router/src/services/kafka/refund_event.rs b/crates/router/src/services/kafka/refund_event.rs
index fea0b8c45e7..9480220104c 100644
--- a/crates/router/src/services/kafka/refund_event.rs
+++ b/crates/router/src/services/kafka/refund_event.rs
@@ -8,7 +8,7 @@ pub struct KafkaRefundEvent<'a> {
pub internal_reference_id: &'a String,
pub refund_id: &'a String, //merchant_reference id
pub payment_id: &'a String,
- pub merchant_id: &'a String,
+ pub merchant_id: &'a common_utils::id_type::MerchantId,
pub connector_transaction_id: &'a String,
pub connector: &'a String,
pub connector_refund_id: Option<&'a String>,
@@ -64,7 +64,10 @@ impl<'a> super::KafkaMessage for KafkaRefundEvent<'a> {
fn key(&self) -> String {
format!(
"{}_{}_{}_{}",
- self.merchant_id, self.payment_id, self.attempt_id, self.refund_id
+ self.merchant_id.get_string_repr(),
+ self.payment_id,
+ self.attempt_id,
+ self.refund_id
)
}
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index c5e536de3aa..641553642a8 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -602,7 +602,7 @@ pub struct AuthenticatePaymentFlowResponse {
#[derive(Debug, Clone, Default, serde::Deserialize, serde::Serialize)]
pub struct ConnectorResponse {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub connector: String,
pub payment_id: String,
pub amount: i64,
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index 2228293320c..26dcb056e9f 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -43,6 +43,7 @@ impl ForeignFrom<diesel_models::organization::Organization> for OrganizationResp
impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse {
type Error = error_stack::Report<errors::ParsingError>;
fn foreign_try_from(item: domain::MerchantAccount) -> Result<Self, Self::Error> {
+ let merchant_id = item.get_id().to_owned();
let primary_business_details: Vec<api_models::admin::PrimaryBusinessDetails> = item
.primary_business_details
.parse_value("primary_business_details")?;
@@ -53,7 +54,7 @@ impl ForeignTryFrom<domain::MerchantAccount> for MerchantAccountResponse {
.transpose()?;
Ok(Self {
- merchant_id: item.merchant_id,
+ merchant_id,
merchant_name: item.merchant_name,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
@@ -183,6 +184,7 @@ pub async fn create_business_profile(
> {
// Generate a unique profile id
let profile_id = common_utils::generate_id_with_default_len("pro");
+ let merchant_id = merchant_account.get_id().to_owned();
let current_time = common_utils::date_time::now();
@@ -238,7 +240,7 @@ pub async fn create_business_profile(
Ok(storage::business_profile::BusinessProfileNew {
profile_id,
- merchant_id: merchant_account.merchant_id,
+ merchant_id,
profile_name: request.profile_name.unwrap_or("default".to_string()),
created_at: current_time,
modified_at: current_time,
diff --git a/crates/router/src/types/api/connector_onboarding/paypal.rs b/crates/router/src/types/api/connector_onboarding/paypal.rs
index 22bab6968a8..a1f3155cd49 100644
--- a/crates/router/src/types/api/connector_onboarding/paypal.rs
+++ b/crates/router/src/types/api/connector_onboarding/paypal.rs
@@ -148,13 +148,13 @@ impl PartnerReferralRequest {
#[derive(serde::Deserialize, Debug)]
pub struct SellerStatusResponse {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub links: Vec<HateoasLink>,
}
#[derive(serde::Deserialize, Debug)]
pub struct SellerStatusDetailsResponse {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub primary_email_confirmed: bool,
pub payments_receivable: bool,
pub products: Vec<SellerStatusProducts>,
@@ -227,8 +227,8 @@ impl SellerStatusDetailsResponse {
.and_then(|ppcp_custom| ppcp_custom.vetting_status.clone())
}
- fn get_payer_id(&self) -> String {
- self.merchant_id.to_string()
+ fn get_payer_id(&self) -> common_utils::id_type::MerchantId {
+ self.merchant_id.to_owned()
}
}
diff --git a/crates/router/src/types/api/verify_connector.rs b/crates/router/src/types/api/verify_connector.rs
index 859f02d8fcc..e54ee8706fc 100644
--- a/crates/router/src/types/api/verify_connector.rs
+++ b/crates/router/src/types/api/verify_connector.rs
@@ -79,7 +79,7 @@ impl VerifyConnectorData {
attempt_id: attempt_id.clone(),
description: None,
customer_id: None,
- merchant_id: consts::VERIFY_CONNECTOR_MERCHANT_ID.to_string(),
+ merchant_id: common_utils::id_type::MerchantId::default(),
reference_id: None,
access_token,
session_token: None,
diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs
index e14ab8ea641..c7604622f3b 100644
--- a/crates/router/src/types/domain/address.rs
+++ b/crates/router/src/types/domain/address.rs
@@ -37,7 +37,7 @@ pub struct Address {
#[serde(skip_serializing)]
#[serde(with = "custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
- pub merchant_id: String,
+ pub merchant_id: id_type::MerchantId,
pub updated_by: String,
pub email: crypto::OptionalEncryptableEmail,
}
@@ -77,7 +77,7 @@ impl behaviour::Conversion for CustomerAddress {
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
- key_store_ref_id: String,
+ key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let customer_id =
other
@@ -87,7 +87,7 @@ impl behaviour::Conversion for CustomerAddress {
field_name: "customer_id".to_string(),
})?;
- let address = Address::convert_back(state, other, key, key_store_ref_id).await?;
+ let address = Address::convert_back(state, other, key, key_manager_identifier).await?;
Ok(Self {
address,
@@ -123,7 +123,7 @@ impl behaviour::Conversion for PaymentAddress {
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
- key_store_ref_id: String,
+ key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let payment_id = other
.payment_id
@@ -134,7 +134,7 @@ impl behaviour::Conversion for PaymentAddress {
let customer_id = other.customer_id.clone();
- let address = Address::convert_back(state, other, key, key_store_ref_id).await?;
+ let address = Address::convert_back(state, other, key, key_manager_identifier).await?;
Ok(Self {
address,
@@ -188,7 +188,7 @@ impl behaviour::Conversion for Address {
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
- _key_store_ref_id: String,
+ _key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let identifier = Identifier::Merchant(other.merchant_id.clone());
let decrypted: FxHashMap<String, Encryptable<Secret<String>>> = types::batch_decrypt(
diff --git a/crates/router/src/types/domain/event.rs b/crates/router/src/types/domain/event.rs
index c5eca1ab5ea..67183a2d3a4 100644
--- a/crates/router/src/types/domain/event.rs
+++ b/crates/router/src/types/domain/event.rs
@@ -1,6 +1,6 @@
use common_utils::{
crypto::OptionalEncryptableSecretString,
- types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
+ types::keymanager::{KeyManagerState, ToEncryptable},
};
use diesel_models::{
enums::{EventClass, EventObjectType, EventType, WebhookDeliveryAttempt},
@@ -24,7 +24,7 @@ pub struct Event {
pub primary_object_id: String,
pub primary_object_type: EventObjectType,
pub created_at: time::PrimitiveDateTime,
- pub merchant_id: Option<String>,
+ pub merchant_id: Option<common_utils::id_type::MerchantId>,
pub business_profile_id: Option<String>,
pub primary_object_created_at: Option<time::PrimitiveDateTime>,
pub idempotent_event_id: Option<String>,
@@ -87,7 +87,7 @@ impl super::behaviour::Conversion for Event {
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
- key_store_ref_id: String,
+ key_manager_identifier: common_utils::types::keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
@@ -98,7 +98,7 @@ impl super::behaviour::Conversion for Event {
request: item.request.clone(),
response: item.response.clone(),
}),
- Identifier::Merchant(key_store_ref_id.clone()),
+ key_manager_identifier,
key.peek(),
)
.await
diff --git a/crates/router/src/types/domain/merchant_connector_account.rs b/crates/router/src/types/domain/merchant_connector_account.rs
index bd0bfe15e53..6b0436b6f2f 100644
--- a/crates/router/src/types/domain/merchant_connector_account.rs
+++ b/crates/router/src/types/domain/merchant_connector_account.rs
@@ -17,7 +17,7 @@ use super::{
#[derive(Clone, Debug)]
pub struct MerchantConnectorAccount {
pub id: Option<i32>,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub connector_name: String,
pub connector_account_details: Encryptable<Secret<serde_json::Value>>,
pub test_mode: Option<bool>,
@@ -45,7 +45,6 @@ pub struct MerchantConnectorAccount {
#[derive(Debug)]
pub enum MerchantConnectorAccountUpdate {
Update {
- merchant_id: Option<String>,
connector_type: Option<enums::ConnectorType>,
connector_name: Option<String>,
connector_account_details: Option<Encryptable<Secret<serde_json::Value>>>,
@@ -110,7 +109,7 @@ impl behaviour::Conversion for MerchantConnectorAccount {
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
- _key_store_ref_id: String,
+ _key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let identifier = Identifier::Merchant(other.merchant_id.clone());
Ok(Self {
@@ -202,7 +201,6 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
fn from(merchant_connector_account_update: MerchantConnectorAccountUpdate) -> Self {
match merchant_connector_account_update {
MerchantConnectorAccountUpdate::Update {
- merchant_id,
connector_type,
connector_name,
connector_account_details,
@@ -219,7 +217,6 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
status,
connector_wallets_details,
} => Self {
- merchant_id,
connector_type,
connector_name,
connector_account_details: connector_account_details.map(Encryption::from),
@@ -242,7 +239,6 @@ impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInte
connector_wallets_details,
} => Self {
connector_wallets_details: Some(Encryption::from(connector_wallets_details)),
- merchant_id: None,
connector_type: None,
connector_name: None,
connector_account_details: None,
diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rs
index e7813ec3d27..9c1c722b280 100644
--- a/crates/router/src/types/domain/user.rs
+++ b/crates/router/src/types/domain/user.rs
@@ -338,9 +338,18 @@ impl MerchantId {
}
}
+impl TryFrom<MerchantId> for id_type::MerchantId {
+ type Error = error_stack::Report<UserErrors>;
+ fn try_from(value: MerchantId) -> Result<Self, Self::Error> {
+ Self::from(value.0.into())
+ .change_context(UserErrors::MerchantIdParsingError)
+ .attach_printable("Could not convert user merchant_id to merchant_id type")
+ }
+}
+
#[derive(Clone)]
pub struct NewUserMerchant {
- merchant_id: MerchantId,
+ merchant_id: id_type::MerchantId,
company_name: Option<UserCompanyName>,
new_organization: NewUserOrganization,
}
@@ -359,8 +368,8 @@ impl NewUserMerchant {
self.company_name.clone().map(UserCompanyName::get_secret)
}
- pub fn get_merchant_id(&self) -> String {
- self.merchant_id.get_secret()
+ pub fn get_merchant_id(&self) -> id_type::MerchantId {
+ self.merchant_id.clone()
}
pub fn get_new_organization(&self) -> NewUserOrganization {
@@ -372,14 +381,14 @@ impl NewUserMerchant {
.store
.get_merchant_key_store_by_merchant_id(
&(&state).into(),
- self.get_merchant_id().as_str(),
+ &self.get_merchant_id(),
&state.store.get_master_key().to_vec().into(),
)
.await
.is_ok()
{
return Err(UserErrors::MerchantAccountCreationError(format!(
- "Merchant with {} already exists",
+ "Merchant with {:?} already exists",
self.get_merchant_id()
))
.into());
@@ -412,11 +421,7 @@ impl NewUserMerchant {
))]
fn create_merchant_account_request(&self) -> UserResult<admin_api::MerchantAccountCreate> {
Ok(admin_api::MerchantAccountCreate {
- merchant_id: id_type::MerchantId::from(self.get_merchant_id().into())
- .change_context(UserErrors::MerchantIdParsingError)
- .attach_printable(
- "Unable to convert to MerchantId type because of constraint violations",
- )?,
+ merchant_id: self.get_merchant_id(),
metadata: None,
locker_id: None,
return_url: None,
@@ -464,10 +469,8 @@ impl TryFrom<user_api::SignUpRequest> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::SignUpRequest) -> UserResult<Self> {
- let merchant_id = MerchantId::new(format!(
- "merchant_{}",
- common_utils::date_time::now_unix_timestamp()
- ))?;
+ let merchant_id = id_type::MerchantId::new_from_unix_timestamp();
+
let new_organization = NewUserOrganization::from(value);
Ok(Self {
@@ -482,10 +485,7 @@ impl TryFrom<user_api::ConnectAccountRequest> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: user_api::ConnectAccountRequest) -> UserResult<Self> {
- let merchant_id = MerchantId::new(format!(
- "merchant_{}",
- common_utils::date_time::now_unix_timestamp()
- ))?;
+ let merchant_id = id_type::MerchantId::new_from_unix_timestamp();
let new_organization = NewUserOrganization::from(value);
Ok(Self {
@@ -505,7 +505,7 @@ impl TryFrom<user_api::SignUpWithMerchantIdRequest> for NewUserMerchant {
Ok(Self {
company_name,
- merchant_id,
+ merchant_id: id_type::MerchantId::try_from(merchant_id)?,
new_organization,
})
}
@@ -517,8 +517,9 @@ impl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for
fn try_from(
value: (user_api::CreateInternalUserRequest, id_type::OrganizationId),
) -> UserResult<Self> {
- let merchant_id =
- MerchantId::new(consts::user_role::INTERNAL_USER_MERCHANT_ID.to_string())?;
+ let merchant_id = id_type::MerchantId::get_internal_user_merchant_id(
+ consts::user_role::INTERNAL_USER_MERCHANT_ID,
+ );
let new_organization = NewUserOrganization::from(value);
Ok(Self {
@@ -532,7 +533,7 @@ impl TryFrom<(user_api::CreateInternalUserRequest, id_type::OrganizationId)> for
impl TryFrom<InviteeUserRequestWithInvitedUserToken> for NewUserMerchant {
type Error = error_stack::Report<UserErrors>;
fn try_from(value: InviteeUserRequestWithInvitedUserToken) -> UserResult<Self> {
- let merchant_id = MerchantId::new(value.clone().1.merchant_id)?;
+ let merchant_id = value.clone().1.merchant_id;
let new_organization = NewUserOrganization::from(value);
Ok(Self {
company_name: None,
@@ -550,12 +551,9 @@ impl TryFrom<UserMerchantCreateRequestWithToken> for NewUserMerchant {
fn try_from(value: UserMerchantCreateRequestWithToken) -> UserResult<Self> {
let merchant_id = if matches!(env::which(), env::Env::Production) {
- MerchantId::new(value.1.company_name.clone())?
+ id_type::MerchantId::try_from(MerchantId::new(value.1.company_name.clone())?)?
} else {
- MerchantId::new(format!(
- "merchant_{}",
- common_utils::date_time::now_unix_timestamp()
- ))?
+ id_type::MerchantId::new_from_unix_timestamp()
};
Ok(Self {
merchant_id,
@@ -918,14 +916,14 @@ impl UserFromStorage {
Ok(days_left_for_password_rotate.whole_days() < 0)
}
- pub fn get_preferred_merchant_id(&self) -> Option<String> {
+ pub fn get_preferred_merchant_id(&self) -> Option<id_type::MerchantId> {
self.0.preferred_merchant_id.clone()
}
pub async fn get_role_from_db_by_merchant_id(
&self,
state: &SessionState,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> CustomResult<UserRole, errors::StorageError> {
state
.store
diff --git a/crates/router/src/types/domain/user_key_store.rs b/crates/router/src/types/domain/user_key_store.rs
index 40c8acd5695..b0b57732cc8 100644
--- a/crates/router/src/types/domain/user_key_store.rs
+++ b/crates/router/src/types/domain/user_key_store.rs
@@ -34,7 +34,7 @@ impl super::behaviour::Conversion for UserKeyStore {
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
- _key_store_ref_id: String,
+ _key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
diff --git a/crates/router/src/types/fraud_check.rs b/crates/router/src/types/fraud_check.rs
index da9e961031a..4995cc59cda 100644
--- a/crates/router/src/types/fraud_check.rs
+++ b/crates/router/src/types/fraud_check.rs
@@ -18,7 +18,7 @@ pub type FrmSaleType =
#[derive(Debug, Clone)]
pub struct FrmRouterData {
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
pub connector: String,
pub payment_id: String,
pub attempt_id: String,
diff --git a/crates/router/src/types/storage/dispute.rs b/crates/router/src/types/storage/dispute.rs
index b76325acfc1..2728b29bc07 100644
--- a/crates/router/src/types/storage/dispute.rs
+++ b/crates/router/src/types/storage/dispute.rs
@@ -11,7 +11,7 @@ use crate::{connection::PgPooledConn, logger};
pub trait DisputeDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: api_models::disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
}
@@ -20,7 +20,7 @@ pub trait DisputeDbExt: Sized {
impl DisputeDbExt for Dispute {
async fn filter_by_constraints(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
dispute_list_constraints: api_models::disputes::DisputeListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
diff --git a/crates/router/src/types/storage/mandate.rs b/crates/router/src/types/storage/mandate.rs
index 648011ade31..c575e433e59 100644
--- a/crates/router/src/types/storage/mandate.rs
+++ b/crates/router/src/types/storage/mandate.rs
@@ -13,7 +13,7 @@ use crate::{connection::PgPooledConn, logger};
pub trait MandateDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
mandate_list_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
}
@@ -22,7 +22,7 @@ pub trait MandateDbExt: Sized {
impl MandateDbExt for Mandate {
async fn filter_by_constraints(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
mandate_list_constraints: api_models::mandates::MandateListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rs
index 0478e423b7a..18560837bc5 100644
--- a/crates/router/src/types/storage/payment_attempt.rs
+++ b/crates/router/src/types/storage/payment_attempt.rs
@@ -153,7 +153,7 @@ mod tests {
let current_time = common_utils::date_time::now();
let payment_id = Uuid::new_v4().to_string();
let attempt_id = Uuid::new_v4().to_string();
- let merchant_id = Uuid::new_v4().to_string();
+ let merchant_id = common_utils::id_type::MerchantId::new_from_unix_timestamp();
let connector = types::Connector::DummyConnector1.to_string();
let payment_attempt = PaymentAttemptNew {
@@ -195,12 +195,13 @@ mod tests {
async fn test_payment_attempt_mandate_field() {
let state = create_single_connection_test_transaction_pool().await;
let uuid = Uuid::new_v4().to_string();
+ let merchant_id = common_utils::id_type::MerchantId::from("merchant1".into()).unwrap();
let current_time = common_utils::date_time::now();
let connector = types::Connector::DummyConnector1.to_string();
let payment_attempt = PaymentAttemptNew {
payment_id: uuid.clone(),
- merchant_id: "1".to_string(),
+ merchant_id: merchant_id.clone(),
connector: Some(connector),
created_at: current_time.into(),
modified_at: current_time.into(),
@@ -221,7 +222,7 @@ mod tests {
let response = store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&uuid,
- "1",
+ &merchant_id,
&uuid,
enums::MerchantStorageScheme::PostgresOnly,
)
diff --git a/crates/router/src/types/storage/payment_link.rs b/crates/router/src/types/storage/payment_link.rs
index 6b4869817cc..9a251d760bd 100644
--- a/crates/router/src/types/storage/payment_link.rs
+++ b/crates/router/src/types/storage/payment_link.rs
@@ -16,7 +16,7 @@ use crate::{
pub trait PaymentLinkDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError>;
}
@@ -25,7 +25,7 @@ pub trait PaymentLinkDbExt: Sized {
impl PaymentLinkDbExt for PaymentLink {
async fn filter_by_constraints(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_link_list_constraints: api_models::payments::PaymentLinkListConstraints,
) -> CustomResult<Vec<Self>, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
diff --git a/crates/router/src/types/storage/payment_method.rs b/crates/router/src/types/storage/payment_method.rs
index 308aa362562..8a8f89f9017 100644
--- a/crates/router/src/types/storage/payment_method.rs
+++ b/crates/router/src/types/storage/payment_method.rs
@@ -116,5 +116,5 @@ pub struct PaymentMethodStatusTrackingData {
pub payment_method_id: String,
pub prev_status: enums::PaymentMethodStatus,
pub curr_status: enums::PaymentMethodStatus,
- pub merchant_id: String,
+ pub merchant_id: common_utils::id_type::MerchantId,
}
diff --git a/crates/router/src/types/storage/refund.rs b/crates/router/src/types/storage/refund.rs
index 75030721ec5..1860771d026 100644
--- a/crates/router/src/types/storage/refund.rs
+++ b/crates/router/src/types/storage/refund.rs
@@ -19,7 +19,7 @@ use crate::{connection::PgPooledConn, logger};
pub trait RefundDbExt: Sized {
async fn filter_by_constraints(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &api_models::refunds::RefundListRequest,
limit: i64,
offset: i64,
@@ -27,13 +27,13 @@ pub trait RefundDbExt: Sized {
async fn filter_by_meta_constraints(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &api_models::payments::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError>;
async fn get_refunds_count(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &api_models::refunds::RefundListRequest,
) -> CustomResult<i64, errors::DatabaseError>;
}
@@ -42,7 +42,7 @@ pub trait RefundDbExt: Sized {
impl RefundDbExt for Refund {
async fn filter_by_constraints(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &api_models::refunds::RefundListRequest,
limit: i64,
offset: i64,
@@ -150,7 +150,7 @@ impl RefundDbExt for Refund {
async fn filter_by_meta_constraints(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &api_models::payments::TimeRange,
) -> CustomResult<api_models::refunds::RefundListMetaData, errors::DatabaseError> {
let start_time = refund_list_details.start_time;
@@ -205,7 +205,7 @@ impl RefundDbExt for Refund {
async fn get_refunds_count(
conn: &PgPooledConn,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
refund_list_details: &api_models::refunds::RefundListRequest,
) -> CustomResult<i64, errors::DatabaseError> {
let mut filter = <Self as HasTable>::table()
diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rs
index cd1019f4a05..ea3a36b518a 100644
--- a/crates/router/src/utils.rs
+++ b/crates/router/src/utils.rs
@@ -210,7 +210,7 @@ pub async fn find_payment_intent_from_payment_id_type(
.find_payment_intent_by_payment_id_merchant_id(
&key_manager_state,
&payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
@@ -219,7 +219,7 @@ pub async fn find_payment_intent_from_payment_id_type(
payments::PaymentIdType::ConnectorTransactionId(connector_transaction_id) => {
let attempt = db
.find_payment_attempt_by_merchant_id_connector_txn_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&connector_transaction_id,
merchant_account.storage_scheme,
)
@@ -228,7 +228,7 @@ pub async fn find_payment_intent_from_payment_id_type(
db.find_payment_intent_by_payment_id_merchant_id(
&key_manager_state,
&attempt.payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
@@ -239,7 +239,7 @@ pub async fn find_payment_intent_from_payment_id_type(
let attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&attempt_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
@@ -247,7 +247,7 @@ pub async fn find_payment_intent_from_payment_id_type(
db.find_payment_intent_by_payment_id_merchant_id(
&key_manager_state,
&attempt.payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
@@ -271,7 +271,7 @@ pub async fn find_payment_intent_from_refund_id_type(
let refund = match refund_id_type {
webhooks::RefundIdType::RefundId(id) => db
.find_refund_by_merchant_id_refund_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&id,
merchant_account.storage_scheme,
)
@@ -279,7 +279,7 @@ pub async fn find_payment_intent_from_refund_id_type(
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?,
webhooks::RefundIdType::ConnectorRefundId(id) => db
.find_refund_by_merchant_id_connector_refund_id_connector(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&id,
connector_name,
merchant_account.storage_scheme,
@@ -290,7 +290,7 @@ pub async fn find_payment_intent_from_refund_id_type(
let attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&refund.attempt_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
@@ -298,7 +298,7 @@ pub async fn find_payment_intent_from_refund_id_type(
db.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
&attempt.payment_id,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
@@ -316,7 +316,7 @@ pub async fn find_payment_intent_from_mandate_id_type(
let mandate = match mandate_id_type {
webhooks::MandateIdType::MandateId(mandate_id) => db
.find_mandate_by_merchant_id_mandate_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
mandate_id.as_str(),
merchant_account.storage_scheme,
)
@@ -324,7 +324,7 @@ pub async fn find_payment_intent_from_mandate_id_type(
.to_not_found_response(errors::ApiErrorResponse::MandateNotFound)?,
webhooks::MandateIdType::ConnectorMandateId(connector_mandate_id) => db
.find_mandate_by_merchant_id_connector_mandate_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
connector_mandate_id.as_str(),
merchant_account.storage_scheme,
)
@@ -337,7 +337,7 @@ pub async fn find_payment_intent_from_mandate_id_type(
.original_payment_id
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("original_payment_id not present in mandate record")?,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
key_store,
merchant_account.storage_scheme,
)
@@ -355,14 +355,14 @@ pub async fn find_mca_from_authentication_id_type(
let authentication = match authentication_id_type {
webhooks::AuthenticationIdType::AuthenticationId(authentication_id) => db
.find_authentication_by_merchant_id_authentication_id(
- merchant_account.merchant_id.clone(),
+ merchant_account.get_id(),
authentication_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?,
webhooks::AuthenticationIdType::ConnectorAuthenticationId(connector_authentication_id) => {
db.find_authentication_by_merchant_id_connector_authentication_id(
- merchant_account.merchant_id.clone(),
+ merchant_account.get_id().clone(),
connector_authentication_id,
)
.await
@@ -371,7 +371,7 @@ pub async fn find_mca_from_authentication_id_type(
};
db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&state.into(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&authentication.merchant_connector_id,
key_store,
)
@@ -392,7 +392,7 @@ pub async fn get_mca_from_payment_intent(
let payment_attempt = db
.find_payment_attempt_by_attempt_id_merchant_id(
&payment_intent.active_attempt.get_id(),
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
merchant_account.storage_scheme,
)
.await
@@ -402,7 +402,7 @@ pub async fn get_mca_from_payment_intent(
Some(merchant_connector_id) => db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&merchant_connector_id,
key_store,
)
@@ -454,7 +454,7 @@ pub async fn get_mca_from_payout_attempt(
let payout = match payout_id_type {
webhooks::PayoutIdType::PayoutAttemptId(payout_attempt_id) => db
.find_payout_attempt_by_merchant_id_payout_attempt_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&payout_attempt_id,
merchant_account.storage_scheme,
)
@@ -462,7 +462,7 @@ pub async fn get_mca_from_payout_attempt(
.to_not_found_response(errors::ApiErrorResponse::PayoutNotFound)?,
webhooks::PayoutIdType::ConnectorPayoutId(connector_payout_id) => db
.find_payout_attempt_by_merchant_id_connector_payout_id(
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&connector_payout_id,
merchant_account.storage_scheme,
)
@@ -474,7 +474,7 @@ pub async fn get_mca_from_payout_attempt(
Some(merchant_connector_id) => db
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
- &merchant_account.merchant_id,
+ merchant_account.get_id(),
&merchant_connector_id,
key_store,
)
@@ -677,14 +677,14 @@ pub trait CustomerAddress {
address_details: payments::AddressDetails,
key: &[u8],
storage_scheme: storage::enums::MerchantStorageScheme,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError>;
async fn get_domain_address(
&self,
state: &SessionState,
address_details: payments::AddressDetails,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
key: &[u8],
storage_scheme: storage::enums::MerchantStorageScheme,
@@ -700,7 +700,7 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
address_details: payments::AddressDetails,
key: &[u8],
storage_scheme: storage::enums::MerchantStorageScheme,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) -> CustomResult<storage::AddressUpdate, common_utils::errors::CryptoError> {
let encrypted_data = batch_encrypt(
&state.into(),
@@ -736,7 +736,7 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
&self,
state: &SessionState,
address_details: payments::AddressDetails,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
customer_id: &id_type::CustomerId,
key: &[u8],
storage_scheme: storage::enums::MerchantStorageScheme,
@@ -748,7 +748,7 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
phone_number: self.phone.clone(),
email: self.email.clone(),
}),
- Identifier::Merchant(merchant_id.to_string()),
+ Identifier::Merchant(merchant_id.to_owned()),
key,
)
.await?;
@@ -767,7 +767,7 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
last_name: encryptable_address.last_name,
phone_number: encryptable_address.phone_number,
country_code: self.phone_country_code.clone(),
- merchant_id: merchant_id.to_string(),
+ merchant_id: merchant_id.to_owned(),
address_id: generate_id(consts::ID_LENGTH, "add"),
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
@@ -785,7 +785,7 @@ impl CustomerAddress for api_models::customers::CustomerRequest {
pub fn add_apple_pay_flow_metrics(
apple_pay_flow: &Option<domain::ApplePayFlow>,
connector: Option<String>,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) {
if let Some(flow) = apple_pay_flow {
match flow {
@@ -797,7 +797,7 @@ pub fn add_apple_pay_flow_metrics(
"connector",
connector.to_owned().unwrap_or("null".to_string()),
),
- ("merchant_id", merchant_id.to_owned()),
+ ("merchant_id", merchant_id.get_string_repr().to_owned()),
]),
),
domain::ApplePayFlow::Manual => metrics::APPLE_PAY_MANUAL_FLOW.add(
@@ -808,7 +808,7 @@ pub fn add_apple_pay_flow_metrics(
"connector",
connector.to_owned().unwrap_or("null".to_string()),
),
- ("merchant_id", merchant_id.to_owned()),
+ ("merchant_id", merchant_id.get_string_repr().to_owned()),
]),
),
}
@@ -819,7 +819,7 @@ pub fn add_apple_pay_payment_status_metrics(
payment_attempt_status: enums::AttemptStatus,
apple_pay_flow: Option<domain::ApplePayFlow>,
connector: Option<String>,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
) {
if payment_attempt_status == enums::AttemptStatus::Charged {
if let Some(flow) = apple_pay_flow {
@@ -833,7 +833,7 @@ pub fn add_apple_pay_payment_status_metrics(
"connector",
connector.to_owned().unwrap_or("null".to_string()),
),
- ("merchant_id", merchant_id.to_owned()),
+ ("merchant_id", merchant_id.get_string_repr().to_owned()),
]),
)
}
@@ -846,7 +846,7 @@ pub fn add_apple_pay_payment_status_metrics(
"connector",
connector.to_owned().unwrap_or("null".to_string()),
),
- ("merchant_id", merchant_id.to_owned()),
+ ("merchant_id", merchant_id.get_string_repr().to_owned()),
]),
),
}
@@ -863,7 +863,7 @@ pub fn add_apple_pay_payment_status_metrics(
"connector",
connector.to_owned().unwrap_or("null".to_string()),
),
- ("merchant_id", merchant_id.to_owned()),
+ ("merchant_id", merchant_id.get_string_repr().to_owned()),
]),
)
}
@@ -875,7 +875,7 @@ pub fn add_apple_pay_payment_status_metrics(
"connector",
connector.to_owned().unwrap_or("null".to_string()),
),
- ("merchant_id", merchant_id.to_owned()),
+ ("merchant_id", merchant_id.get_string_repr().to_owned()),
]),
),
}
@@ -998,10 +998,6 @@ pub async fn flatten_join_error<T>(handle: Handle<T>) -> RouterResult<T> {
}
}
-pub(crate) fn get_merchant_fingerprint_secret_key(merchant_id: impl AsRef<str>) -> String {
- format!("fingerprint_secret_{}", merchant_id.as_ref())
-}
-
#[cfg(test)]
mod tests {
use crate::utils;
diff --git a/crates/router/src/utils/connector_onboarding.rs b/crates/router/src/utils/connector_onboarding.rs
index 0bc8e58fcc4..b66190f450f 100644
--- a/crates/router/src/utils/connector_onboarding.rs
+++ b/crates/router/src/utils/connector_onboarding.rs
@@ -43,7 +43,7 @@ pub fn is_enabled(
pub async fn check_if_connector_exists(
state: &SessionState,
connector_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
) -> RouterResult<()> {
let key_manager_state = &state.into();
let key_store = state
diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rs
index 6c52ecda4cb..58215bf1bce 100644
--- a/crates/router/src/utils/user.rs
+++ b/crates/router/src/utils/user.rs
@@ -100,7 +100,7 @@ pub async fn generate_jwt_auth_token(
pub async fn generate_jwt_auth_token_with_custom_role_attributes(
state: &SessionState,
user: &UserFromStorage,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
role_id: String,
) -> UserResult<Secret<String>> {
@@ -152,7 +152,7 @@ pub fn get_multiple_merchant_details_with_status(
) -> UserResult<Vec<user_api::UserMerchantAccount>> {
let merchant_account_map = merchant_accounts
.into_iter()
- .map(|merchant_account| (merchant_account.merchant_id.clone(), merchant_account))
+ .map(|merchant_account| (merchant_account.get_id().clone(), merchant_account))
.collect::<HashMap<_, _>>();
let role_map = roles
diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rs
index 225dc81765c..5814f64f759 100644
--- a/crates/router/src/utils/user/dashboard_metadata.rs
+++ b/crates/router/src/utils/user/dashboard_metadata.rs
@@ -20,7 +20,7 @@ use crate::{
pub async fn insert_merchant_scoped_metadata_to_db(
state: &SessionState,
user_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_key: DBEnum,
metadata_value: impl serde::Serialize,
@@ -53,7 +53,7 @@ pub async fn insert_merchant_scoped_metadata_to_db(
pub async fn insert_user_scoped_metadata_to_db(
state: &SessionState,
user_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_key: DBEnum,
metadata_value: impl serde::Serialize,
@@ -86,7 +86,7 @@ pub async fn insert_user_scoped_metadata_to_db(
pub async fn get_merchant_scoped_metadata_from_db(
state: &SessionState,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_keys: Vec<DBEnum>,
) -> UserResult<Vec<DashboardMetadata>> {
@@ -100,7 +100,7 @@ pub async fn get_merchant_scoped_metadata_from_db(
pub async fn get_user_scoped_metadata_from_db(
state: &SessionState,
user_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_keys: Vec<DBEnum>,
) -> UserResult<Vec<DashboardMetadata>> {
@@ -124,7 +124,7 @@ pub async fn get_user_scoped_metadata_from_db(
pub async fn update_merchant_scoped_metadata(
state: &SessionState,
user_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_key: DBEnum,
metadata_value: impl serde::Serialize,
@@ -152,7 +152,7 @@ pub async fn update_merchant_scoped_metadata(
pub async fn update_user_scoped_metadata(
state: &SessionState,
user_id: String,
- merchant_id: String,
+ merchant_id: id_type::MerchantId,
org_id: id_type::OrganizationId,
metadata_key: DBEnum,
metadata_value: impl serde::Serialize,
diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rs
index 0909f4ffbeb..b1ab16ac03f 100644
--- a/crates/router/src/utils/user/sample_data.rs
+++ b/crates/router/src/utils/user/sample_data.rs
@@ -19,9 +19,8 @@ use crate::{
pub async fn generate_sample_data(
state: &SessionState,
req: SampleDataRequest,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
) -> SampleDataResult<Vec<(PaymentIntent, PaymentAttemptBatchNew, Option<RefundNew>)>> {
- let merchant_id = merchant_id.to_string();
let sample_data_size: usize = req.record.unwrap_or(100);
let key_manager_state = &state.into();
if !(10..=100).contains(&sample_data_size) {
@@ -32,7 +31,7 @@ pub async fn generate_sample_data(
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- merchant_id.as_str(),
+ merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
@@ -40,7 +39,7 @@ pub async fn generate_sample_data(
let merchant_from_db = state
.store
- .find_merchant_account_by_merchant_id(key_manager_state, merchant_id.as_str(), &key_store)
+ .find_merchant_account_by_merchant_id(key_manager_state, merchant_id, &key_store)
.await
.change_context::<SampleDataError>(SampleDataError::DataDoesNotExist)?;
@@ -71,7 +70,7 @@ pub async fn generate_sample_data(
state
.store
- .list_business_profile_by_merchant_id(&merchant_id)
+ .list_business_profile_by_merchant_id(merchant_id)
.await
.change_context(SampleDataError::InternalServerError)
.attach_printable("Failed to get business profile")?
diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rs
index d304c31c1c9..99c020e0ee1 100644
--- a/crates/router/src/utils/user_role.rs
+++ b/crates/router/src/utils/user_role.rs
@@ -77,7 +77,7 @@ pub fn validate_role_groups(groups: &[PermissionGroup]) -> UserResult<()> {
pub async fn validate_role_name(
state: &SessionState,
role_name: &domain::RoleName,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> UserResult<()> {
let role_name_str = role_name.clone().get_role_name();
@@ -109,7 +109,7 @@ pub async fn set_role_permissions_in_cache_by_user_role(
set_role_permissions_in_cache_if_required(
state,
user_role.role_id.as_str(),
- user_role.merchant_id.as_str(),
+ &user_role.merchant_id,
&user_role.org_id,
)
.await
@@ -120,7 +120,7 @@ pub async fn set_role_permissions_in_cache_by_user_role(
pub async fn set_role_permissions_in_cache_if_required(
state: &SessionState,
role_id: &str,
- merchant_id: &str,
+ merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
) -> UserResult<()> {
if roles::predefined_roles::PREDEFINED_ROLES.contains_key(role_id) {
diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs
index e49a5f86c3c..b26e9862e81 100644
--- a/crates/router/src/workflows/api_key_expiry.rs
+++ b/crates/router/src/workflows/api_key_expiry.rs
@@ -33,7 +33,7 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow {
.store
.get_merchant_key_store_by_merchant_id(
key_manager_satte,
- tracking_data.merchant_id.as_str(),
+ &tracking_data.merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await?;
@@ -41,7 +41,7 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow {
let merchant_account = db
.find_merchant_account_by_merchant_id(
key_manager_satte,
- tracking_data.merchant_id.as_str(),
+ &tracking_data.merchant_id,
&key_store,
)
.await?;
diff --git a/crates/router/src/workflows/attach_payout_account_workflow.rs b/crates/router/src/workflows/attach_payout_account_workflow.rs
index 7ff0faefa68..37de784d5e9 100644
--- a/crates/router/src/workflows/attach_payout_account_workflow.rs
+++ b/crates/router/src/workflows/attach_payout_account_workflow.rs
@@ -35,7 +35,7 @@ impl ProcessTrackerWorkflow<SessionState> for AttachPayoutAccountWorkflow {
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- merchant_id.as_ref(),
+ &merchant_id,
&db.get_master_key().to_vec().into(),
)
.await?;
diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rs
index d181aedd18f..5334e4e93a9 100644
--- a/crates/router/src/workflows/outgoing_webhook_retry.rs
+++ b/crates/router/src/workflows/outgoing_webhook_retry.rs
@@ -263,7 +263,7 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {
#[instrument(skip_all)]
pub(crate) async fn get_webhook_delivery_retry_schedule_time(
db: &dyn StorageInterface,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Option<time::PrimitiveDateTime> {
let key = "pt_mapping_outgoing_webhooks";
@@ -308,7 +308,7 @@ pub(crate) async fn get_webhook_delivery_retry_schedule_time(
#[instrument(skip_all)]
pub(crate) async fn retry_webhook_delivery_task(
db: &dyn StorageInterface,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
process: storage::ProcessTracker,
) -> errors::CustomResult<(), errors::StorageError> {
let schedule_time =
diff --git a/crates/router/src/workflows/payment_method_status_update.rs b/crates/router/src/workflows/payment_method_status_update.rs
index fa0631cc5c2..5120f1ba197 100644
--- a/crates/router/src/workflows/payment_method_status_update.rs
+++ b/crates/router/src/workflows/payment_method_status_update.rs
@@ -35,7 +35,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflow
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- merchant_id.as_str(),
+ &merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await?;
diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rs
index 2bc7b183ec1..d626241e327 100644
--- a/crates/router/src/workflows/payment_sync.rs
+++ b/crates/router/src/workflows/payment_sync.rs
@@ -229,7 +229,7 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow {
pub async fn get_sync_process_schedule_time(
db: &dyn StorageInterface,
connector: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let mapping: common_utils::errors::CustomResult<
@@ -262,7 +262,7 @@ pub async fn get_sync_process_schedule_time(
pub async fn retry_sync_task(
db: &dyn StorageInterface,
connector: String,
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
pt: storage::ProcessTracker,
) -> Result<bool, sch_errors::ProcessTrackerError> {
let schedule_time =
@@ -289,12 +289,19 @@ mod tests {
#[test]
fn test_get_default_schedule_time() {
- let schedule_time_delta =
- scheduler_utils::get_schedule_time(process_data::ConnectorPTMapping::default(), "-", 0)
- .unwrap();
- let first_retry_time_delta =
- scheduler_utils::get_schedule_time(process_data::ConnectorPTMapping::default(), "-", 1)
- .unwrap();
+ let merchant_id = common_utils::id_type::MerchantId::from("-".into()).unwrap();
+ let schedule_time_delta = scheduler_utils::get_schedule_time(
+ process_data::ConnectorPTMapping::default(),
+ &merchant_id,
+ 0,
+ )
+ .unwrap();
+ let first_retry_time_delta = scheduler_utils::get_schedule_time(
+ process_data::ConnectorPTMapping::default(),
+ &merchant_id,
+ 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/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index d7eda4db835..72663079f2d 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -20,9 +20,11 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {
.aci
.expect("Missing ACI connector authentication configuration");
+ let merchant_id = id_type::MerchantId::from("aci".into()).unwrap();
+
types::RouterData {
flow: PhantomData,
- merchant_id: String::from("aci"),
+ merchant_id,
customer_id: Some(id_type::CustomerId::from("aci".into()).unwrap()),
connector: "aci".to_string(),
payment_id: uuid::Uuid::new_v4().to_string(),
@@ -131,9 +133,11 @@ fn construct_refund_router_data<F>() -> types::RefundsRouterData<F> {
.aci
.expect("Missing ACI connector authentication configuration");
+ let merchant_id = id_type::MerchantId::from("aci".into()).unwrap();
+
types::RouterData {
flow: PhantomData,
- merchant_id: String::from("aci"),
+ merchant_id,
customer_id: Some(id_type::CustomerId::from("aci".into()).unwrap()),
connector: "aci".to_string(),
payment_id: uuid::Uuid::new_v4().to_string(),
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index c3d9b6e0c3f..612d2863e5d 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -481,9 +481,11 @@ pub trait ConnectorActions: Connector {
req: Req,
info: Option<PaymentInfo>,
) -> RouterData<Flow, Req, Res> {
+ let merchant_id = common_utils::id_type::MerchantId::from(self.get_name().into()).unwrap();
+
RouterData {
flow: PhantomData,
- merchant_id: self.get_name(),
+ merchant_id,
customer_id: Some(common_utils::generate_customer_id_of_default_length()),
connector: self.get_name(),
payment_id: uuid::Uuid::new_v4().to_string(),
diff --git a/crates/router/tests/integration_demo.rs b/crates/router/tests/integration_demo.rs
index 777e0a68298..773f3c3ab74 100644
--- a/crates/router/tests/integration_demo.rs
+++ b/crates/router/tests/integration_demo.rs
@@ -15,11 +15,14 @@ async fn create_merchant_account() {
let admin_client = client.admin("test_admin");
let expected = "merchant_12345";
+ let expected_merchant_id_type =
+ common_utils::id_type::MerchantId::from("merchant_12345".into()).unwrap();
+
let hlist_pat![merchant_id, _api_key]: HList![MerchantId, ApiKey] = admin_client
.create_merchant_account(&server, expected.to_owned())
.await;
- assert_eq!(expected, *merchant_id);
+ assert_eq!(expected_merchant_id_type, *merchant_id);
}
/// Example of unit test
diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs
index 997ae51cf31..31d5e52c3c7 100644
--- a/crates/router/tests/payments.rs
+++ b/crates/router/tests/payments.rs
@@ -285,6 +285,9 @@ async fn payments_create_core() {
Box::new(services::MockApiClient),
))
.await;
+
+ let merchant_id = id_type::MerchantId::from("juspay_merchant".into()).unwrap();
+
let state = Arc::new(app_state)
.get_session_state("public", || {})
.unwrap();
@@ -293,7 +296,7 @@ async fn payments_create_core() {
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- "juspay_merchant",
+ &merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
@@ -301,7 +304,7 @@ async fn payments_create_core() {
let merchant_account = state
.store
- .find_merchant_account_by_merchant_id(key_manager_state, "juspay_merchant", &key_store)
+ .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.unwrap();
@@ -309,7 +312,7 @@ async fn payments_create_core() {
payment_id: Some(api::PaymentIdType::PaymentIntentId(
"pay_mbabizu24mvu3mela5njyhpit10".to_string(),
)),
- merchant_id: Some("jarnura".to_string()),
+ merchant_id: Some(merchant_id),
amount: Some(MinorUnit::new(6540).into()),
currency: Some(api_enums::Currency::USD),
capture_method: Some(api_enums::CaptureMethod::Automatic),
@@ -475,14 +478,14 @@ async fn payments_create_core_adyen_no_redirect() {
.unwrap();
let customer_id = format!("cust_{}", Uuid::new_v4());
- let merchant_id = "arunraj".to_string();
+ let merchant_id = id_type::MerchantId::from("juspay_merchant".into()).unwrap();
let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string();
let key_manager_state = &(&state).into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- "juspay_merchant",
+ &merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
@@ -490,7 +493,7 @@ async fn payments_create_core_adyen_no_redirect() {
let merchant_account = state
.store
- .find_merchant_account_by_merchant_id(key_manager_state, "juspay_merchant", &key_store)
+ .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.unwrap();
diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs
index fcf106a9efc..20bf10da723 100644
--- a/crates/router/tests/payments2.rs
+++ b/crates/router/tests/payments2.rs
@@ -45,6 +45,9 @@ async fn payments_create_core() {
Box::new(services::MockApiClient),
))
.await;
+
+ let merchant_id = id_type::MerchantId::from("juspay_merchant".into()).unwrap();
+
let state = Arc::new(app_state)
.get_session_state("public", || {})
.unwrap();
@@ -53,7 +56,7 @@ async fn payments_create_core() {
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- "juspay_merchant",
+ &merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
@@ -61,7 +64,7 @@ async fn payments_create_core() {
let merchant_account = state
.store
- .find_merchant_account_by_merchant_id(key_manager_state, "juspay_merchant", &key_store)
+ .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.unwrap();
@@ -69,7 +72,7 @@ async fn payments_create_core() {
payment_id: Some(api::PaymentIdType::PaymentIntentId(
"pay_mbabizu24mvu3mela5njyhpit10".to_string(),
)),
- merchant_id: Some("jarnura".to_string()),
+ merchant_id: Some(merchant_id),
amount: Some(MinorUnit::new(6540).into()),
currency: Some(api_enums::Currency::USD),
capture_method: Some(api_enums::CaptureMethod::Automatic),
@@ -242,14 +245,14 @@ async fn payments_create_core_adyen_no_redirect() {
.unwrap();
let customer_id = format!("cust_{}", Uuid::new_v4());
- let merchant_id = "arunraj".to_string();
+ let merchant_id = id_type::MerchantId::from("juspay_merchant".into()).unwrap();
let payment_id = "pay_mbabizu24mvu3mela5njyhpit10".to_string();
let key_manager_state = &(&state).into();
let key_store = state
.store
.get_merchant_key_store_by_merchant_id(
key_manager_state,
- "juspay_merchant",
+ &merchant_id,
&state.store.get_master_key().to_vec().into(),
)
.await
@@ -257,7 +260,7 @@ async fn payments_create_core_adyen_no_redirect() {
let merchant_account = state
.store
- .find_merchant_account_by_merchant_id(key_manager_state, "juspay_merchant", &key_store)
+ .find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.unwrap();
diff --git a/crates/router/tests/utils.rs b/crates/router/tests/utils.rs
index 5d48d6e8ad0..96ea3c7d028 100644
--- a/crates/router/tests/utils.rs
+++ b/crates/router/tests/utils.rs
@@ -103,7 +103,7 @@ impl AppClient<Admin> {
pub async fn create_connector<T: DeserializeOwned, S, B>(
&self,
app: &S,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
api_key: &str,
) -> T
@@ -384,7 +384,7 @@ macro_rules! hlist_pat {
#[derive(Deserialize, Deref)]
pub struct MerchantId {
- merchant_id: String,
+ merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Deserialize, Deref)]
diff --git a/crates/scheduler/src/consumer/types/process_data.rs b/crates/scheduler/src/consumer/types/process_data.rs
index 98d0fe530e2..f68ad4795df 100644
--- a/crates/scheduler/src/consumer/types/process_data.rs
+++ b/crates/scheduler/src/consumer/types/process_data.rs
@@ -12,7 +12,7 @@ pub struct RetryMapping {
#[derive(Serialize, Deserialize)]
pub struct ConnectorPTMapping {
pub default_mapping: RetryMapping,
- pub custom_merchant_mapping: HashMap<String, RetryMapping>,
+ pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>,
pub max_retries_count: i32,
}
@@ -57,7 +57,7 @@ pub struct OutgoingWebhookRetryProcessTrackerMapping {
pub default_mapping: RetryMapping,
/// Merchant-specific retry configuration.
- pub custom_merchant_mapping: HashMap<String, RetryMapping>,
+ pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>,
}
impl Default for OutgoingWebhookRetryProcessTrackerMapping {
diff --git a/crates/scheduler/src/utils.rs b/crates/scheduler/src/utils.rs
index f4f3a7c1bb1..8c2424d5017 100644
--- a/crates/scheduler/src/utils.rs
+++ b/crates/scheduler/src/utils.rs
@@ -251,9 +251,12 @@ pub fn get_process_tracker_id<'a>(
runner: storage::ProcessTrackerRunner,
task_name: &'a str,
txn_id: &'a str,
- merchant_id: &'a str,
+ merchant_id: &'a common_utils::id_type::MerchantId,
) -> String {
- format!("{runner}_{task_name}_{txn_id}_{merchant_id}")
+ format!(
+ "{runner}_{task_name}_{txn_id}_{}",
+ merchant_id.get_string_repr()
+ )
}
pub fn get_time_from_delta(delta: Option<i32>) -> Option<time::PrimitiveDateTime> {
@@ -300,10 +303,10 @@ pub fn add_histogram_metrics(
pub fn get_schedule_time(
mapping: process_data::ConnectorPTMapping,
- merchant_name: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Option<i32> {
- let mapping = match mapping.custom_merchant_mapping.get(merchant_name) {
+ let mapping = match mapping.custom_merchant_mapping.get(merchant_id) {
Some(map) => map.clone(),
None => mapping.default_mapping,
};
@@ -335,10 +338,10 @@ pub fn get_pm_schedule_time(
pub fn get_outgoing_webhook_retry_schedule_time(
mapping: process_data::OutgoingWebhookRetryProcessTrackerMapping,
- merchant_name: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
retry_count: i32,
) -> Option<i32> {
- let retry_mapping = match mapping.custom_merchant_mapping.get(merchant_name) {
+ let retry_mapping = match mapping.custom_merchant_mapping.get(merchant_id) {
Some(map) => map.clone(),
None => mapping.default_mapping,
};
diff --git a/crates/storage_impl/src/lib.rs b/crates/storage_impl/src/lib.rs
index d55f812c5a2..7bb0c700d7a 100644
--- a/crates/storage_impl/src/lib.rs
+++ b/crates/storage_impl/src/lib.rs
@@ -330,7 +330,11 @@ impl UniqueConstraints for diesel_models::Address {
impl UniqueConstraints for diesel_models::PaymentIntent {
fn unique_constraints(&self) -> Vec<String> {
- vec![format!("pi_{}_{}", self.merchant_id, self.payment_id)]
+ vec![format!(
+ "pi_{}_{}",
+ self.merchant_id.get_string_repr(),
+ self.payment_id
+ )]
}
fn table_name(&self) -> &str {
"PaymentIntent"
@@ -341,7 +345,9 @@ impl UniqueConstraints for diesel_models::PaymentAttempt {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"pa_{}_{}_{}",
- self.merchant_id, self.payment_id, self.attempt_id
+ self.merchant_id.get_string_repr(),
+ self.payment_id,
+ self.attempt_id
)]
}
fn table_name(&self) -> &str {
@@ -351,7 +357,11 @@ impl UniqueConstraints for diesel_models::PaymentAttempt {
impl UniqueConstraints for diesel_models::Refund {
fn unique_constraints(&self) -> Vec<String> {
- vec![format!("refund_{}_{}", self.merchant_id, self.refund_id)]
+ vec![format!(
+ "refund_{}_{}",
+ self.merchant_id.get_string_repr(),
+ self.refund_id
+ )]
}
fn table_name(&self) -> &str {
"Refund"
@@ -370,7 +380,11 @@ impl UniqueConstraints for diesel_models::ReverseLookup {
#[cfg(feature = "payouts")]
impl UniqueConstraints for diesel_models::Payouts {
fn unique_constraints(&self) -> Vec<String> {
- vec![format!("po_{}_{}", self.merchant_id, self.payout_id)]
+ vec![format!(
+ "po_{}_{}",
+ self.merchant_id.get_string_repr(),
+ self.payout_id
+ )]
}
fn table_name(&self) -> &str {
"Payouts"
@@ -382,7 +396,8 @@ impl UniqueConstraints for diesel_models::PayoutAttempt {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"poa_{}_{}",
- self.merchant_id, self.payout_attempt_id
+ self.merchant_id.get_string_repr(),
+ self.payout_attempt_id
)]
}
fn table_name(&self) -> &str {
@@ -401,7 +416,11 @@ impl UniqueConstraints for diesel_models::PaymentMethod {
impl UniqueConstraints for diesel_models::Mandate {
fn unique_constraints(&self) -> Vec<String> {
- vec![format!("mand_{}_{}", self.merchant_id, self.mandate_id)]
+ vec![format!(
+ "mand_{}_{}",
+ self.merchant_id.get_string_repr(),
+ self.mandate_id
+ )]
}
fn table_name(&self) -> &str {
"Mandate"
@@ -413,7 +432,7 @@ impl UniqueConstraints for diesel_models::Customer {
vec![format!(
"customer_{}_{}",
self.customer_id.get_string_repr(),
- self.merchant_id
+ self.merchant_id.get_string_repr(),
)]
}
fn table_name(&self) -> &str {
diff --git a/crates/storage_impl/src/mock_db/payment_attempt.rs b/crates/storage_impl/src/mock_db/payment_attempt.rs
index ee183968e2d..ed3c47b9c96 100644
--- a/crates/storage_impl/src/mock_db/payment_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payment_attempt.rs
@@ -16,7 +16,7 @@ impl PaymentAttemptInterface for MockDb {
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&self,
_payment_id: &str,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_attempt_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
@@ -27,7 +27,7 @@ impl PaymentAttemptInterface for MockDb {
async fn get_filters_for_payments(
&self,
_pi: &[hyperswitch_domain_models::payments::PaymentIntent],
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<
hyperswitch_domain_models::payments::payment_attempt::PaymentListFilters,
@@ -38,7 +38,7 @@ impl PaymentAttemptInterface for MockDb {
async fn get_total_count_of_filtered_payment_attempts(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_active_attempt_ids: &[String],
_connector: Option<Vec<Connector>>,
_payment_method: Option<Vec<PaymentMethod>>,
@@ -53,7 +53,7 @@ impl PaymentAttemptInterface for MockDb {
async fn find_payment_attempt_by_attempt_id_merchant_id(
&self,
_attempt_id: &str,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
@@ -63,7 +63,7 @@ impl PaymentAttemptInterface for MockDb {
async fn find_payment_attempt_by_preprocessing_id_merchant_id(
&self,
_preprocessing_id: &str,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
@@ -72,7 +72,7 @@ impl PaymentAttemptInterface for MockDb {
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_txn_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
@@ -82,7 +82,7 @@ impl PaymentAttemptInterface for MockDb {
async fn find_attempts_by_merchant_id_payment_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_payment_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
@@ -191,7 +191,7 @@ impl PaymentAttemptInterface for MockDb {
&self,
_connector_transaction_id: &str,
_payment_id: &str,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
@@ -203,7 +203,7 @@ impl PaymentAttemptInterface for MockDb {
async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
let payment_attempts = self.payment_attempts.lock().await;
@@ -212,7 +212,7 @@ impl PaymentAttemptInterface for MockDb {
.iter()
.find(|payment_attempt| {
payment_attempt.payment_id == payment_id
- && payment_attempt.merchant_id == merchant_id
+ && payment_attempt.merchant_id.eq(merchant_id)
})
.cloned()
.unwrap())
@@ -221,7 +221,7 @@ impl PaymentAttemptInterface for MockDb {
async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
let payment_attempts = self.payment_attempts.lock().await;
@@ -230,7 +230,7 @@ impl PaymentAttemptInterface for MockDb {
.iter()
.find(|payment_attempt| {
payment_attempt.payment_id == payment_id
- && payment_attempt.merchant_id == merchant_id
+ && payment_attempt.merchant_id.eq(merchant_id)
&& (payment_attempt.status == storage_enums::AttemptStatus::PartialCharged
|| payment_attempt.status == storage_enums::AttemptStatus::Charged)
})
diff --git a/crates/storage_impl/src/mock_db/payment_intent.rs b/crates/storage_impl/src/mock_db/payment_intent.rs
index 3e183b94c26..59951045a1b 100644
--- a/crates/storage_impl/src/mock_db/payment_intent.rs
+++ b/crates/storage_impl/src/mock_db/payment_intent.rs
@@ -20,7 +20,7 @@ impl PaymentIntentInterface for MockDb {
async fn filter_payment_intent_by_constraints(
&self,
_state: &KeyManagerState,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
@@ -32,7 +32,7 @@ impl PaymentIntentInterface for MockDb {
async fn filter_payment_intents_by_time_range_constraints(
&self,
_state: &KeyManagerState,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_time_range: &api_models::payments::TimeRange,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
@@ -43,7 +43,7 @@ impl PaymentIntentInterface for MockDb {
#[cfg(feature = "olap")]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, StorageError> {
@@ -54,7 +54,7 @@ impl PaymentIntentInterface for MockDb {
async fn get_filtered_payment_intents_attempt(
&self,
_state: &KeyManagerState,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
@@ -103,7 +103,7 @@ impl PaymentIntentInterface for MockDb {
state,
diesel_payment_intent_update.apply_changeset(diesel_payment_intent),
key_store.key.get_inner(),
- key_store.merchant_id.clone(),
+ key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?;
@@ -117,7 +117,7 @@ impl PaymentIntentInterface for MockDb {
&self,
_state: &KeyManagerState,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, StorageError> {
@@ -126,7 +126,8 @@ impl PaymentIntentInterface for MockDb {
Ok(payment_intents
.iter()
.find(|payment_intent| {
- payment_intent.payment_id == payment_id && payment_intent.merchant_id == merchant_id
+ payment_intent.payment_id == payment_id
+ && payment_intent.merchant_id.eq(merchant_id)
})
.cloned()
.unwrap())
diff --git a/crates/storage_impl/src/mock_db/payout_attempt.rs b/crates/storage_impl/src/mock_db/payout_attempt.rs
index 652dde93a68..efdd2cf631c 100644
--- a/crates/storage_impl/src/mock_db/payout_attempt.rs
+++ b/crates/storage_impl/src/mock_db/payout_attempt.rs
@@ -37,7 +37,7 @@ impl PayoutAttemptInterface for MockDb {
async fn find_payout_attempt_by_merchant_id_payout_attempt_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_payout_attempt_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PayoutAttempt, StorageError> {
@@ -47,7 +47,7 @@ impl PayoutAttemptInterface for MockDb {
async fn find_payout_attempt_by_merchant_id_connector_payout_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_connector_payout_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PayoutAttempt, StorageError> {
@@ -58,7 +58,7 @@ impl PayoutAttemptInterface for MockDb {
async fn get_filters_for_payouts(
&self,
_payouts: &[Payouts],
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<
hyperswitch_domain_models::payouts::payout_attempt::PayoutListFilters,
diff --git a/crates/storage_impl/src/mock_db/payouts.rs b/crates/storage_impl/src/mock_db/payouts.rs
index 04e1321f1eb..53d34a39a28 100644
--- a/crates/storage_impl/src/mock_db/payouts.rs
+++ b/crates/storage_impl/src/mock_db/payouts.rs
@@ -14,7 +14,7 @@ use super::MockDb;
impl PayoutsInterface for MockDb {
async fn find_payout_by_merchant_id_payout_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_payout_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Payouts, StorageError> {
@@ -44,7 +44,7 @@ impl PayoutsInterface for MockDb {
async fn find_optional_payout_by_merchant_id_payout_id(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_payout_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Option<Payouts>, StorageError> {
@@ -55,7 +55,7 @@ impl PayoutsInterface for MockDb {
#[cfg(feature = "olap")]
async fn filter_payouts_by_constraints(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<Payouts>, StorageError> {
@@ -66,7 +66,7 @@ impl PayoutsInterface for MockDb {
#[cfg(feature = "olap")]
async fn filter_payouts_and_attempts(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_filters: &hyperswitch_domain_models::payouts::PayoutFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<(Payouts, PayoutAttempt, diesel_models::Customer)>, StorageError> {
@@ -77,7 +77,7 @@ impl PayoutsInterface for MockDb {
#[cfg(feature = "olap")]
async fn filter_payouts_by_time_range_constraints(
&self,
- _merchant_id: &str,
+ _merchant_id: &common_utils::id_type::MerchantId,
_time_range: &api_models::payments::TimeRange,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<Payouts>, StorageError> {
diff --git a/crates/storage_impl/src/payments/payment_attempt.rs b/crates/storage_impl/src/payments/payment_attempt.rs
index b536ba45523..f5d28f7698d 100644
--- a/crates/storage_impl/src/payments/payment_attempt.rs
+++ b/crates/storage_impl/src/payments/payment_attempt.rs
@@ -80,7 +80,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
&self,
connector_transaction_id: &str,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
@@ -102,7 +102,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
@@ -123,7 +123,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
@@ -143,7 +143,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
#[instrument(skip_all)]
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_txn_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
@@ -165,7 +165,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
@@ -189,7 +189,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
async fn get_filters_for_payments(
&self,
pi: &[PaymentIntent],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentListFilters, errors::StorageError> {
let conn = pg_connection_read(self).await?;
@@ -229,7 +229,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
async fn find_payment_attempt_by_preprocessing_id_merchant_id(
&self,
preprocessing_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
@@ -250,7 +250,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
#[instrument(skip_all)]
async fn find_attempts_by_merchant_id_payment_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<PaymentAttempt>, errors::StorageError> {
@@ -272,7 +272,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
async fn find_payment_attempt_by_attempt_id_merchant_id(
&self,
attempt_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
@@ -289,7 +289,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for RouterStore<T> {
#[instrument(skip_all)]
async fn get_total_count_of_filtered_payment_attempts(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<Connector>>,
payment_method: Option<Vec<PaymentMethod>>,
@@ -435,7 +435,8 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
let reverse_lookup = ReverseLookupNew {
lookup_id: format!(
"pa_{}_{}",
- &created_attempt.merchant_id, &created_attempt.attempt_id,
+ created_attempt.merchant_id.get_string_repr(),
+ &created_attempt.attempt_id,
),
pk_id: key_str.clone(),
sk_id: field.clone(),
@@ -527,7 +528,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
add_connector_txn_id_to_reverse_lookup(
self,
key_str.as_str(),
- this.merchant_id.as_str(),
+ &this.merchant_id,
updated_attempt.attempt_id.as_str(),
connector_transaction_id.as_str(),
storage_scheme,
@@ -539,7 +540,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
add_connector_txn_id_to_reverse_lookup(
self,
key_str.as_str(),
- this.merchant_id.as_str(),
+ &this.merchant_id,
updated_attempt.attempt_id.as_str(),
connector_transaction_id.as_str(),
storage_scheme,
@@ -555,7 +556,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
add_preprocessing_id_to_reverse_lookup(
self,
key_str.as_str(),
- this.merchant_id.as_str(),
+ &this.merchant_id,
updated_attempt.attempt_id.as_str(),
preprocessing_id.as_str(),
storage_scheme,
@@ -567,7 +568,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
add_preprocessing_id_to_reverse_lookup(
self,
key_str.as_str(),
- this.merchant_id.as_str(),
+ &this.merchant_id,
updated_attempt.attempt_id.as_str(),
preprocessing_id.as_str(),
storage_scheme,
@@ -598,7 +599,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
&self,
connector_transaction_id: &str,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme =
@@ -616,7 +617,10 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
}
MerchantStorageScheme::RedisKv => {
// We assume that PaymentAttempt <=> PaymentIntent is a one-to-one relation for now
- let lookup_id = format!("pa_conn_trans_{merchant_id}_{connector_transaction_id}");
+ let lookup_id = format!(
+ "pa_conn_trans_{}_{connector_transaction_id}",
+ merchant_id.get_string_repr()
+ );
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
@@ -649,7 +653,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let database_call = || {
@@ -703,7 +707,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let database_call = || {
@@ -759,7 +763,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
#[instrument(skip_all)]
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_txn_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
@@ -776,7 +780,10 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
.await
}
MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("pa_conn_trans_{merchant_id}_{connector_txn_id}");
+ let lookup_id = format!(
+ "pa_conn_trans_{}_{connector_txn_id}",
+ merchant_id.get_string_repr()
+ );
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
@@ -821,7 +828,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&self,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
attempt_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
@@ -870,7 +877,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
async fn find_payment_attempt_by_attempt_id_merchant_id(
&self,
attempt_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme =
@@ -886,7 +893,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
.await
}
MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("pa_{merchant_id}_{attempt_id}");
+ let lookup_id = format!("pa_{}_{attempt_id}", merchant_id.get_string_repr());
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
@@ -931,7 +938,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
async fn find_payment_attempt_by_preprocessing_id_merchant_id(
&self,
preprocessing_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, errors::StorageError> {
let storage_scheme =
@@ -947,7 +954,10 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
.await
}
MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("pa_preprocessing_{merchant_id}_{preprocessing_id}");
+ let lookup_id = format!(
+ "pa_preprocessing_{}_{preprocessing_id}",
+ merchant_id.get_string_repr()
+ );
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
@@ -991,7 +1001,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
#[instrument(skip_all)]
async fn find_attempts_by_merchant_id_payment_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payment_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentAttempt>, errors::StorageError> {
@@ -1037,7 +1047,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
async fn get_filters_for_payments(
&self,
pi: &[PaymentIntent],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentListFilters, errors::StorageError> {
self.router_store
@@ -1048,7 +1058,7 @@ impl<T: DatabaseStore> PaymentAttemptInterface for KVRouterStore<T> {
#[instrument(skip_all)]
async fn get_total_count_of_filtered_payment_attempts(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<Connector>>,
payment_method: Option<Vec<PaymentMethod>>,
@@ -2276,14 +2286,18 @@ impl DataModelExt for PaymentAttemptUpdate {
async fn add_connector_txn_id_to_reverse_lookup<T: DatabaseStore>(
store: &KVRouterStore<T>,
key: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
updated_attempt_attempt_id: &str,
connector_transaction_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
let field = format!("pa_{}", updated_attempt_attempt_id);
let reverse_lookup_new = ReverseLookupNew {
- lookup_id: format!("pa_conn_trans_{}_{}", merchant_id, connector_transaction_id),
+ lookup_id: format!(
+ "pa_conn_trans_{}_{}",
+ merchant_id.get_string_repr(),
+ connector_transaction_id
+ ),
pk_id: key.to_owned(),
sk_id: field.clone(),
source: "payment_attempt".to_string(),
@@ -2299,14 +2313,18 @@ async fn add_connector_txn_id_to_reverse_lookup<T: DatabaseStore>(
async fn add_preprocessing_id_to_reverse_lookup<T: DatabaseStore>(
store: &KVRouterStore<T>,
key: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
updated_attempt_attempt_id: &str,
preprocessing_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
let field = format!("pa_{}", updated_attempt_attempt_id);
let reverse_lookup_new = ReverseLookupNew {
- lookup_id: format!("pa_preprocessing_{}_{}", merchant_id, preprocessing_id),
+ lookup_id: format!(
+ "pa_preprocessing_{}_{}",
+ merchant_id.get_string_repr(),
+ preprocessing_id
+ ),
pk_id: key.to_owned(),
sk_id: field.clone(),
source: "payment_attempt".to_string(),
diff --git a/crates/storage_impl/src/payments/payment_intent.rs b/crates/storage_impl/src/payments/payment_intent.rs
index a982d0ffdc5..ea91732631d 100644
--- a/crates/storage_impl/src/payments/payment_intent.rs
+++ b/crates/storage_impl/src/payments/payment_intent.rs
@@ -215,7 +215,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
state,
diesel_intent,
merchant_key_store.key.get_inner(),
- merchant_id,
+ merchant_id.into(),
)
.await
.change_context(StorageError::DecryptionError)?;
@@ -230,7 +230,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
&self,
state: &KeyManagerState,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
@@ -274,7 +274,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
- merchant_id.to_string(),
+ merchant_id.to_owned().into(),
)
.await
.change_context(StorageError::DecryptionError)
@@ -291,7 +291,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
let pa = DieselPaymentAttempt::find_by_merchant_id_attempt_id(
&conn,
- payment.merchant_id.as_str(),
+ &payment.merchant_id,
attempt_id.as_str(),
)
.await
@@ -311,7 +311,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
async fn filter_payment_intent_by_constraints(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
@@ -331,7 +331,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
async fn filter_payment_intents_by_time_range_constraints(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
time_range: &api_models::payments::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
@@ -351,7 +351,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
@@ -370,7 +370,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
#[cfg(feature = "olap")]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, StorageError> {
@@ -410,7 +410,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
@@ -443,7 +443,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
@@ -454,7 +454,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
&self,
state: &KeyManagerState,
payment_id: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
@@ -471,7 +471,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
@@ -491,7 +491,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
let pa = DieselPaymentAttempt::find_by_merchant_id_attempt_id(
&conn,
- payment.merchant_id.as_str(),
+ &payment.merchant_id,
attempt_id.as_str(),
)
.await
@@ -512,7 +512,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
async fn filter_payment_intent_by_constraints(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
@@ -619,7 +619,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
- merchant_key_store.merchant_id.clone(),
+ merchant_key_store.merchant_id.clone().into(),
)
}))
.map(|join_result| join_result.change_context(StorageError::DecryptionError))
@@ -638,7 +638,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
async fn filter_payment_intents_by_time_range_constraints(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
time_range: &api_models::payments::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
@@ -660,7 +660,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
@@ -811,7 +811,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
state,
pi,
merchant_key_store.key.get_inner(),
- merchant_id.to_string(),
+ merchant_id.to_owned().into(),
)
.map(|payment_intent| {
payment_intent.map(|payment_intent| {
@@ -834,7 +834,7 @@ impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
#[instrument(skip_all)]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, StorageError> {
diff --git a/crates/storage_impl/src/payouts/payout_attempt.rs b/crates/storage_impl/src/payouts/payout_attempt.rs
index 5f04592596a..b17ba1b6d7f 100644
--- a/crates/storage_impl/src/payouts/payout_attempt.rs
+++ b/crates/storage_impl/src/payouts/payout_attempt.rs
@@ -96,7 +96,8 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
let reverse_lookup = ReverseLookupNew {
lookup_id: format!(
"poa_{}_{}",
- &created_attempt.merchant_id, &created_attempt.payout_attempt_id,
+ &created_attempt.merchant_id.get_string_repr(),
+ &created_attempt.payout_attempt_id,
),
pk_id: key_str.clone(),
sk_id: field.clone(),
@@ -197,7 +198,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
add_connector_payout_id_to_reverse_lookup(
self,
key_str.as_str(),
- this.merchant_id.as_str(),
+ &this.merchant_id,
updated_attempt.payout_attempt_id.as_str(),
new.as_str(),
storage_scheme,
@@ -208,7 +209,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
add_connector_payout_id_to_reverse_lookup(
self,
key_str.as_str(),
- this.merchant_id.as_str(),
+ &this.merchant_id,
updated_attempt.payout_attempt_id.as_str(),
new.as_str(),
storage_scheme,
@@ -236,7 +237,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_payout_attempt_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_attempt_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
@@ -253,7 +254,8 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
.await
}
MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("poa_{merchant_id}_{payout_attempt_id}");
+ let lookup_id =
+ format!("poa_{}_{payout_attempt_id}", merchant_id.get_string_repr());
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
@@ -296,7 +298,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_connector_payout_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
@@ -311,7 +313,10 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
.await
}
MerchantStorageScheme::RedisKv => {
- let lookup_id = format!("po_conn_payout_{merchant_id}_{connector_payout_id}");
+ let lookup_id = format!(
+ "po_conn_payout_{}_{connector_payout_id}",
+ merchant_id.get_string_repr()
+ );
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
@@ -355,7 +360,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
async fn get_filters_for_payouts(
&self,
payouts: &[Payouts],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutListFilters, errors::StorageError> {
self.router_store
@@ -407,7 +412,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> {
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_payout_attempt_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_attempt_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
@@ -428,7 +433,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> {
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_connector_payout_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
connector_payout_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
@@ -450,7 +455,7 @@ impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> {
async fn get_filters_for_payouts(
&self,
payouts: &[Payouts],
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PayoutListFilters, errors::StorageError> {
let conn = pg_connection_read(self).await?;
@@ -639,14 +644,18 @@ impl DataModelExt for PayoutAttemptUpdate {
async fn add_connector_payout_id_to_reverse_lookup<T: DatabaseStore>(
store: &KVRouterStore<T>,
key: &str,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
updated_attempt_attempt_id: &str,
connector_payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
let field = format!("poa_{}", updated_attempt_attempt_id);
let reverse_lookup_new = ReverseLookupNew {
- lookup_id: format!("po_conn_payout_{}_{}", merchant_id, connector_payout_id),
+ lookup_id: format!(
+ "po_conn_payout_{}_{}",
+ merchant_id.get_string_repr(),
+ connector_payout_id
+ ),
pk_id: key.to_owned(),
sk_id: field.clone(),
source: "payout_attempt".to_string(),
diff --git a/crates/storage_impl/src/payouts/payouts.rs b/crates/storage_impl/src/payouts/payouts.rs
index 7a9dba0f20b..eabe8f5db88 100644
--- a/crates/storage_impl/src/payouts/payouts.rs
+++ b/crates/storage_impl/src/payouts/payouts.rs
@@ -192,7 +192,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
#[instrument(skip_all)]
async fn find_payout_by_merchant_id_payout_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
@@ -236,7 +236,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
#[instrument(skip_all)]
async fn find_optional_payout_by_merchant_id_payout_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Option<Payouts>, StorageError> {
@@ -291,7 +291,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
#[instrument(skip_all)]
async fn filter_payouts_by_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
@@ -304,7 +304,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
#[instrument(skip_all)]
async fn filter_payouts_and_attempts(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(Payouts, PayoutAttempt, diesel_models::Customer)>, StorageError>
@@ -318,7 +318,7 @@ impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
#[instrument[skip_all]]
async fn filter_payouts_by_time_range_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
time_range: &api_models::payments::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
@@ -370,7 +370,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
#[instrument(skip_all)]
async fn find_payout_by_merchant_id_payout_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
@@ -387,7 +387,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
#[instrument(skip_all)]
async fn find_optional_payout_by_merchant_id_payout_id(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
payout_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Option<Payouts>, StorageError> {
@@ -405,7 +405,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
#[instrument(skip_all)]
async fn filter_payouts_by_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
@@ -521,7 +521,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
#[instrument(skip_all)]
async fn filter_payouts_and_attempts(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(Payouts, PayoutAttempt, DieselCustomer)>, StorageError> {
@@ -655,7 +655,7 @@ impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
#[instrument(skip_all)]
async fn filter_payouts_by_time_range_constraints(
&self,
- merchant_id: &str,
+ merchant_id: &common_utils::id_type::MerchantId,
time_range: &api_models::payments::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
diff --git a/crates/storage_impl/src/redis/kv_store.rs b/crates/storage_impl/src/redis/kv_store.rs
index c39e67eb841..b33deffda7b 100644
--- a/crates/storage_impl/src/redis/kv_store.rs
+++ b/crates/storage_impl/src/redis/kv_store.rs
@@ -24,26 +24,26 @@ pub trait KvStorePartition {
#[derive(Clone)]
pub enum PartitionKey<'a> {
MerchantIdPaymentId {
- merchant_id: &'a str,
+ merchant_id: &'a common_utils::id_type::MerchantId,
payment_id: &'a str,
},
CombinationKey {
combination: &'a str,
},
MerchantIdCustomerId {
- merchant_id: &'a str,
+ merchant_id: &'a common_utils::id_type::MerchantId,
customer_id: &'a str,
},
MerchantIdPayoutId {
- merchant_id: &'a str,
+ merchant_id: &'a common_utils::id_type::MerchantId,
payout_id: &'a str,
},
MerchantIdPayoutAttemptId {
- merchant_id: &'a str,
+ merchant_id: &'a common_utils::id_type::MerchantId,
payout_attempt_id: &'a str,
},
MerchantIdMandateId {
- merchant_id: &'a str,
+ merchant_id: &'a common_utils::id_type::MerchantId,
mandate_id: &'a str,
},
}
@@ -54,24 +54,39 @@ impl<'a> std::fmt::Display for PartitionKey<'a> {
PartitionKey::MerchantIdPaymentId {
merchant_id,
payment_id,
- } => f.write_str(&format!("mid_{merchant_id}_pid_{payment_id}")),
+ } => f.write_str(&format!(
+ "mid_{}_pid_{payment_id}",
+ merchant_id.get_string_repr()
+ )),
PartitionKey::CombinationKey { combination } => f.write_str(combination),
PartitionKey::MerchantIdCustomerId {
merchant_id,
customer_id,
- } => f.write_str(&format!("mid_{merchant_id}_cust_{customer_id}")),
+ } => f.write_str(&format!(
+ "mid_{}_cust_{customer_id}",
+ merchant_id.get_string_repr()
+ )),
PartitionKey::MerchantIdPayoutId {
merchant_id,
payout_id,
- } => f.write_str(&format!("mid_{merchant_id}_po_{payout_id}")),
+ } => f.write_str(&format!(
+ "mid_{}_po_{payout_id}",
+ merchant_id.get_string_repr()
+ )),
PartitionKey::MerchantIdPayoutAttemptId {
merchant_id,
payout_attempt_id,
- } => f.write_str(&format!("mid_{merchant_id}_poa_{payout_attempt_id}")),
+ } => f.write_str(&format!(
+ "mid_{}_poa_{payout_attempt_id}",
+ merchant_id.get_string_repr()
+ )),
PartitionKey::MerchantIdMandateId {
merchant_id,
mandate_id,
- } => f.write_str(&format!("mid_{merchant_id}_mandate_{mandate_id}")),
+ } => f.write_str(&format!(
+ "mid_{}_mandate_{mandate_id}",
+ merchant_id.get_string_repr()
+ )),
}
}
}
diff --git a/justfile b/justfile
index 9b9ad5a8546..bc63a81b833 100644
--- a/justfile
+++ b/justfile
@@ -10,10 +10,6 @@ fmt *FLAGS:
check_flags := '--all-targets'
-# Check compilation of Rust code
-check *FLAGS:
- cargo check {{ check_flags }} {{ FLAGS }}
-
alias c := check
# Check compilation of Rust code and catch common mistakes
@@ -27,7 +23,7 @@ clippy *FLAGS:
jq -r '
[ ( .workspace_members | sort ) as $package_ids # Store workspace crate package IDs in `package_ids` array
| .packages[] | select( IN(.id; $package_ids[]) ) | .features | keys[] ] | unique # Select all unique features from all workspace crates
- | del( .[] | select( any( . ; . == ("v2", "merchant_account_v2", "payment_v2", "customer_v2") ) ) ) # Exclude some features from features list
+ | del( .[] | select( any( . ; test("(([a-z_]+)_)?v2") ) ) ) # Exclude some features from features list
| join(",") # Construct a comma-separated string of features for passing to `cargo`
')"
@@ -67,6 +63,22 @@ check_v2 *FLAGS:
cargo clippy {{ check_flags }} --features "${FEATURES}" {{ FLAGS }}
set +x
+check *FLAGS:
+ #! /usr/bin/env bash
+ set -euo pipefail
+
+ FEATURES="$(cargo metadata --all-features --format-version 1 | \
+ jq -r '
+ [ ( .workspace_members | sort ) as $package_ids # Store workspace crate package IDs in `package_ids` array
+ | .packages[] | select( IN(.id; $package_ids[]) ) | .features | keys[] ] | unique # Select all unique features from all workspace crates
+ | del( .[] | select( any( . ; test("(([a-z_]+)_)?v2") ) ) ) # Exclude some features from features list
+ | join(",") # Construct a comma-separated string of features for passing to `cargo`
+ ')"
+
+ set -x
+ cargo clippy {{ check_flags }} --features "${FEATURES}" {{ FLAGS }}
+ set +x
+
alias cl := clippy
# Build binaries
|
refactor
|
create domain type for `merchant_id` (#5408)
|
e003958ff31ea0f1e0cddb3d2369945e8d2a2353
|
2024-02-29 20:04:51
|
Swangi Kumari
|
refactor(connector): CANCEL button after redirection is enabled for card 3ds (#3829)
| false
|
diff --git a/crates/router/src/connector/nmi.rs b/crates/router/src/connector/nmi.rs
index e7b7e0e9022..527403736aa 100644
--- a/crates/router/src/connector/nmi.rs
+++ b/crates/router/src/connector/nmi.rs
@@ -8,10 +8,13 @@ use error_stack::{IntoReport, ResultExt};
use regex::Regex;
use transformers as nmi;
-use super::utils as connector_utils;
+use super::utils::{self as connector_utils};
use crate::{
configs::settings,
- core::errors::{self, CustomResult},
+ core::{
+ errors::{self, CustomResult},
+ payments,
+ },
events::connector_api_logs::ConnectorEvent,
services::{self, request, ConnectorIntegration, ConnectorValidation},
types::{
@@ -980,3 +983,41 @@ impl api::IncomingWebhook for Nmi {
}
}
}
+
+impl services::ConnectorRedirectResponse for Nmi {
+ fn get_flow_type(
+ &self,
+ _query_params: &str,
+ json_payload: Option<serde_json::Value>,
+ action: services::PaymentAction,
+ ) -> CustomResult<payments::CallConnectorAction, errors::ConnectorError> {
+ match action {
+ services::PaymentAction::CompleteAuthorize => {
+ let payload_data =
+ json_payload.ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "connector_metadata",
+ })?;
+
+ let redirect_res: nmi::NmiRedirectResponse = serde_json::from_value(payload_data)
+ .into_report()
+ .change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
+ field_name: "redirect_res",
+ })?;
+
+ match redirect_res {
+ transformers::NmiRedirectResponse::NmiRedirectResponseData(_) => {
+ Ok(payments::CallConnectorAction::Trigger)
+ }
+ transformers::NmiRedirectResponse::NmiErrorResponseData(error_res) => {
+ Ok(payments::CallConnectorAction::StatusUpdate {
+ status: enums::AttemptStatus::Failure,
+ error_code: Some(error_res.code),
+ error_message: Some(error_res.message),
+ })
+ }
+ }
+ }
+ services::PaymentAction::PSync => Ok(payments::CallConnectorAction::Trigger),
+ }
+ }
+}
diff --git a/crates/router/src/connector/nmi/transformers.rs b/crates/router/src/connector/nmi/transformers.rs
index e83142f8efd..2f8505522b2 100644
--- a/crates/router/src/connector/nmi/transformers.rs
+++ b/crates/router/src/connector/nmi/transformers.rs
@@ -268,6 +268,20 @@ pub struct NmiCompleteRequest {
three_ds_version: Option<String>,
directory_server_id: Option<String>,
}
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+#[serde(untagged)]
+pub enum NmiRedirectResponse {
+ NmiRedirectResponseData(NmiRedirectResponseData),
+ NmiErrorResponseData(NmiErrorResponseData),
+}
+
+#[derive(Debug, Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub struct NmiErrorResponseData {
+ pub code: String,
+ pub message: String,
+}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
@@ -279,7 +293,7 @@ pub struct NmiRedirectResponseData {
three_ds_version: Option<String>,
order_id: Option<String>,
directory_server_id: Option<String>,
- customer_vault_id: Option<String>,
+ customer_vault_id: String,
}
impl TryFrom<&NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for NmiCompleteRequest {
@@ -311,11 +325,7 @@ impl TryFrom<&NmiRouterData<&types::PaymentsCompleteAuthorizeRouterData>> for Nm
transaction_type,
security_key: auth_type.api_key,
orderid: three_ds_data.order_id,
- customer_vault_id: three_ds_data.customer_vault_id.ok_or(
- errors::ConnectorError::MissingRequiredField {
- field_name: "customer_vault_id",
- },
- )?,
+ customer_vault_id: three_ds_data.customer_vault_id,
email: item.router_data.request.email.clone(),
cvv,
cardholder_auth: three_ds_data.card_holder_auth,
diff --git a/crates/router/src/core/payments/flows.rs b/crates/router/src/core/payments/flows.rs
index ebc0cf3664a..d69f668bf9e 100644
--- a/crates/router/src/core/payments/flows.rs
+++ b/crates/router/src/core/payments/flows.rs
@@ -393,7 +393,6 @@ default_imp_for_connector_redirect_response!(
connector::Klarna,
connector::Multisafepay,
connector::Nexinets,
- connector::Nmi,
connector::Opayo,
connector::Opennode,
connector::Payeezy,
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index bfba31c3446..10239834669 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -1821,18 +1821,16 @@ pub fn build_redirection_form(
amount: '{amount}'
}};
- var responseForm = document.createElement('form');
- responseForm.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/nmi\");
- responseForm.method='POST';
-
const threeDSsecureInterface = threeDS.createUI(options);
threeDSsecureInterface.on('challenge', function(e) {{
- console.log('Challenged');
document.getElementById('loader-wrapper').style.display = 'none';
}});
threeDSsecureInterface.on('complete', function(e) {{
+ var responseForm = document.createElement('form');
+ responseForm.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/nmi\");
+ responseForm.method='POST';
var item1=document.createElement('input');
item1.type='hidden';
@@ -1887,6 +1885,23 @@ pub fn build_redirection_form(
}});
threeDSsecureInterface.on('failure', function(e) {{
+ var responseForm = document.createElement('form');
+ responseForm.action=window.location.pathname.replace(/payments\\/redirect\\/(\\w+)\\/(\\w+)\\/\\w+/, \"payments/$1/$2/redirect/complete/nmi\");
+ responseForm.method='POST';
+
+ var error_code=document.createElement('input');
+ error_code.type='hidden';
+ error_code.name='code';
+ error_code.value= e.code;
+ responseForm.appendChild(error_code);
+
+ var error_message=document.createElement('input');
+ error_message.type='hidden';
+ error_message.name='message';
+ error_message.value= e.message;
+ responseForm.appendChild(error_message);
+
+ document.body.appendChild(responseForm);
responseForm.submit();
}});
|
refactor
|
CANCEL button after redirection is enabled for card 3ds (#3829)
|
d8d8c400bbda49b9a0cd5edbe37e929ae6d38eb4
|
2025-01-09 15:02:36
|
sumitdahiya125
|
test(cypress): add test for In Memory Cache (#6961)
| false
|
diff --git a/cypress-tests/cypress/e2e/PaymentTest/00025-ConfigTest.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00025-BusinessProfileConfigs.cy.js
similarity index 100%
rename from cypress-tests/cypress/e2e/PaymentTest/00025-ConfigTest.cy.js
rename to cypress-tests/cypress/e2e/PaymentTest/00025-BusinessProfileConfigs.cy.js
diff --git a/cypress-tests/cypress/e2e/PaymentTest/00028-MemoryCacheConfigs.cy.js b/cypress-tests/cypress/e2e/PaymentTest/00028-MemoryCacheConfigs.cy.js
new file mode 100644
index 00000000000..afa7ceda0d1
--- /dev/null
+++ b/cypress-tests/cypress/e2e/PaymentTest/00028-MemoryCacheConfigs.cy.js
@@ -0,0 +1,35 @@
+import State from "../../utils/State";
+
+let globalState;
+
+describe("In Memory Cache Test", () => {
+ before("seed global state", () => {
+ cy.task("getGlobalState").then((state) => {
+ globalState = new State(state);
+ });
+ });
+
+ after("flush global state", () => {
+ cy.task("setGlobalState", globalState.data);
+ });
+
+ context("Config flows", () => {
+ const key = "test-key";
+ const value = "test value";
+ const newValue = "new test value";
+
+ it("Create Configs", () => {
+ cy.createConfigs(globalState, key, value);
+ cy.fetchConfigs(globalState, key, value);
+ });
+
+ it("Update Configs", () => {
+ cy.updateConfigs(globalState, key, newValue);
+ cy.fetchConfigs(globalState, key, newValue);
+ });
+
+ it("delete configs", () => {
+ cy.deleteConfigs(globalState, key, newValue);
+ });
+ });
+});
diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js
index e2e83edaf0c..1b7b41a035d 100644
--- a/cypress-tests/cypress/support/commands.js
+++ b/cypress-tests/cypress/support/commands.js
@@ -3369,3 +3369,95 @@ Cypress.Commands.add("incrementalAuth", (globalState, data) => {
}
});
});
+
+Cypress.Commands.add("createConfigs", (globalState, key, value) => {
+ const base_url = globalState.get("baseUrl");
+ const api_key = globalState.get("adminApiKey");
+
+ cy.request({
+ method: "POST",
+ url: `${base_url}/configs/`,
+ headers: {
+ "Content-Type": "application/json",
+ "api-key": api_key,
+ },
+ body: {
+ key: key,
+ value: value,
+ },
+ failOnStatusCode: false,
+ }).then((response) => {
+ logRequestId(response.headers["x-request-id"]);
+
+ expect(response.status).to.equal(200);
+ expect(response.body).to.have.property("key").to.equal(key);
+ expect(response.body).to.have.property("value").to.equal(value);
+ });
+});
+
+Cypress.Commands.add("fetchConfigs", (globalState, key, value) => {
+ const base_url = globalState.get("baseUrl");
+ const api_key = globalState.get("adminApiKey");
+
+ cy.request({
+ method: "GET",
+ url: `${base_url}/configs/${key}`,
+ headers: {
+ "Content-Type": "application/json",
+ "api-key": api_key,
+ },
+ failOnStatusCode: false,
+ }).then((response) => {
+ logRequestId(response.headers["x-request-id"]);
+
+ expect(response.status).to.equal(200);
+ expect(response.body).to.have.property("key").to.equal(key);
+ expect(response.body).to.have.property("value").to.equal(value);
+ });
+});
+
+Cypress.Commands.add("updateConfigs", (globalState, key, value) => {
+ const base_url = globalState.get("baseUrl");
+ const api_key = globalState.get("adminApiKey");
+
+ cy.request({
+ method: "POST",
+ url: `${base_url}/configs/${key}`,
+ headers: {
+ "Content-Type": "application/json",
+ "api-key": api_key,
+ },
+ body: {
+ key: key,
+ value: value,
+ },
+ failOnStatusCode: false,
+ }).then((response) => {
+ logRequestId(response.headers["x-request-id"]);
+
+ expect(response.status).to.equal(200);
+ expect(response.body).to.have.property("key").to.equal(key);
+ expect(response.body).to.have.property("value").to.equal(value);
+ });
+});
+
+Cypress.Commands.add("deleteConfigs", (globalState, key, value) => {
+ const base_url = globalState.get("baseUrl");
+ const api_key = globalState.get("adminApiKey");
+
+ cy.request({
+ method: "DELETE",
+ url: `${base_url}/configs/${key}`,
+ headers: {
+ "Content-Type": "application/json",
+ "api-key": api_key,
+ },
+ failOnStatusCode: false,
+ }).then((response) => {
+ logRequestId(response.headers["x-request-id"]);
+
+ expect(response.status).to.equal(200);
+ expect(response.body).to.have.property("key").to.equal(key);
+ expect(response.body).to.have.property("value").to.equal(value);
+ });
+});
|
test
|
add test for In Memory Cache (#6961)
|
75eea7e81787f2e0697b930b82a8188193f8d51f
|
2023-11-23 13:03:42
|
Hrithikesh
|
fix: amount_captured goes to 0 for 3ds payments (#2954)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 508eeb8d731..a997960edc7 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -312,6 +312,18 @@ pub struct PaymentsRequest {
pub payment_type: Option<api_enums::PaymentType>,
}
+impl PaymentsRequest {
+ pub fn get_total_capturable_amount(&self) -> Option<i64> {
+ let surcharge_amount = self
+ .surcharge_details
+ .map(|surcharge_details| {
+ surcharge_details.surcharge_amount + surcharge_details.tax_amount.unwrap_or(0)
+ })
+ .unwrap_or(0);
+ self.amount
+ .map(|amount| i64::from(amount) + surcharge_amount)
+ }
+}
#[derive(
Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq,
)]
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index a098cef5b77..e096f1878a9 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -111,14 +111,8 @@ where
}
}
enums::AttemptStatus::Charged => {
- let captured_amount = if self.request.is_psync() {
- payment_data
- .payment_attempt
- .amount_to_capture
- .or(Some(payment_data.payment_attempt.get_total_amount()))
- } else {
- types::Capturable::get_capture_amount(&self.request)
- };
+ let captured_amount =
+ types::Capturable::get_capture_amount(&self.request, payment_data);
if Some(payment_data.payment_attempt.get_total_amount()) == captured_amount {
enums::AttemptStatus::Charged
} else if captured_amount.is_some() {
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 4d8daa1fe69..d813c96ce94 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -601,19 +601,19 @@ pub fn validate_request_amount_and_amount_to_capture(
}
}
-/// if confirm = true and capture method = automatic, amount_to_capture(if provided) must be equal to amount
+/// if capture method = automatic, amount_to_capture(if provided) must be equal to amount
#[instrument(skip_all)]
pub fn validate_amount_to_capture_in_create_call_request(
request: &api_models::payments::PaymentsRequest,
) -> CustomResult<(), errors::ApiErrorResponse> {
- if request.capture_method.unwrap_or_default() == api_enums::CaptureMethod::Automatic
- && request.confirm.unwrap_or(false)
- {
- if let Some((amount_to_capture, amount)) = request.amount_to_capture.zip(request.amount) {
- let amount_int: i64 = amount.into();
- utils::when(amount_to_capture != amount_int, || {
+ if request.capture_method.unwrap_or_default() == api_enums::CaptureMethod::Automatic {
+ let total_capturable_amount = request.get_total_capturable_amount();
+ if let Some((amount_to_capture, total_capturable_amount)) =
+ request.amount_to_capture.zip(total_capturable_amount)
+ {
+ utils::when(amount_to_capture != total_capturable_amount, || {
Err(report!(errors::ApiErrorResponse::PreconditionFailed {
- message: "amount_to_capture must be equal to amount when confirm = true and capture_method = automatic".into()
+ message: "amount_to_capture must be equal to total_capturable_amount when capture_method = automatic".into()
}))
})
} else {
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index 3734abfc6ab..1fff2fce69a 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -751,7 +751,7 @@ fn get_total_amount_captured<F: Clone, T: types::Capturable>(
}
None => {
//Non multiple capture
- let amount = request.get_capture_amount();
+ let amount = request.get_capture_amount(payment_data);
amount_captured.or_else(|| {
if router_data_status == enums::AttemptStatus::Charged {
amount
diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rs
index a42e46ca62d..b2f73c0b7ce 100644
--- a/crates/router/src/core/refunds.rs
+++ b/crates/router/src/core/refunds.rs
@@ -58,13 +58,12 @@ pub async fn refund_create_core(
)?;
// Amount is not passed in request refer from payment intent.
- amount = req.amount.unwrap_or(
- payment_intent
- .amount_captured
- .ok_or(errors::ApiErrorResponse::InternalServerError)
- .into_report()
- .attach_printable("amount captured is none in a successful payment")?,
- );
+ amount = req
+ .amount
+ .or(payment_intent.amount_captured)
+ .ok_or(errors::ApiErrorResponse::InternalServerError)
+ .into_report()
+ .attach_printable("amount captured is none in a successful payment")?;
//[#299]: Can we change the flow based on some workflow idea
utils::when(amount <= 0, || {
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index a03e4165040..9fdb96efe55 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -30,9 +30,10 @@ use crate::core::utils::IRRELEVANT_CONNECTOR_REQUEST_REFERENCE_ID_IN_DISPUTE_FLO
use crate::{
core::{
errors::{self, RouterResult},
- payments::RecurringMandatePaymentData,
+ payments::{PaymentData, RecurringMandatePaymentData},
},
services,
+ types::storage::payment_attempt::PaymentAttemptExt,
utils::OptionExt,
};
@@ -544,7 +545,10 @@ pub struct AccessTokenRequestData {
}
pub trait Capturable {
- fn get_capture_amount(&self) -> Option<i64> {
+ fn get_capture_amount<F>(&self, _payment_data: &PaymentData<F>) -> Option<i64>
+ where
+ F: Clone,
+ {
None
}
fn get_surcharge_amount(&self) -> Option<i64> {
@@ -553,13 +557,13 @@ pub trait Capturable {
fn get_tax_on_surcharge_amount(&self) -> Option<i64> {
None
}
- fn is_psync(&self) -> bool {
- false
- }
}
impl Capturable for PaymentsAuthorizeData {
- fn get_capture_amount(&self) -> Option<i64> {
+ fn get_capture_amount<F>(&self, _payment_data: &PaymentData<F>) -> Option<i64>
+ where
+ F: Clone,
+ {
let final_amount = self
.surcharge_details
.as_ref()
@@ -579,24 +583,44 @@ impl Capturable for PaymentsAuthorizeData {
}
impl Capturable for PaymentsCaptureData {
- fn get_capture_amount(&self) -> Option<i64> {
+ fn get_capture_amount<F>(&self, _payment_data: &PaymentData<F>) -> Option<i64>
+ where
+ F: Clone,
+ {
Some(self.amount_to_capture)
}
}
impl Capturable for CompleteAuthorizeData {
- fn get_capture_amount(&self) -> Option<i64> {
+ fn get_capture_amount<F>(&self, _payment_data: &PaymentData<F>) -> Option<i64>
+ where
+ F: Clone,
+ {
Some(self.amount)
}
}
impl Capturable for SetupMandateRequestData {}
-impl Capturable for PaymentsCancelData {}
+impl Capturable for PaymentsCancelData {
+ fn get_capture_amount<F>(&self, payment_data: &PaymentData<F>) -> Option<i64>
+ where
+ F: Clone,
+ {
+ // return previously captured amount
+ payment_data.payment_intent.amount_captured
+ }
+}
impl Capturable for PaymentsApproveData {}
impl Capturable for PaymentsRejectData {}
impl Capturable for PaymentsSessionData {}
impl Capturable for PaymentsSyncData {
- fn is_psync(&self) -> bool {
- true
+ fn get_capture_amount<F>(&self, payment_data: &PaymentData<F>) -> Option<i64>
+ where
+ F: Clone,
+ {
+ payment_data
+ .payment_attempt
+ .amount_to_capture
+ .or(Some(payment_data.payment_attempt.get_total_amount()))
}
}
diff --git a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario12-BNPL-klarna/Payments - Create/request.json b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario12-BNPL-klarna/Payments - Create/request.json
index b0bc12a6ac8..f621bd52f00 100644
--- a/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario12-BNPL-klarna/Payments - Create/request.json
+++ b/postman/collection-dir/stripe/Flow Testcases/Happy Cases/Scenario12-BNPL-klarna/Payments - Create/request.json
@@ -23,7 +23,7 @@
"confirm": false,
"capture_method": "automatic",
"capture_on": "2022-09-10T10:11:12Z",
- "amount_to_capture": 6540,
+ "amount_to_capture": 8000,
"customer_id": "StripeCustomer",
"email": "[email protected]",
"name": "John Doe",
|
fix
|
amount_captured goes to 0 for 3ds payments (#2954)
|
f4072d390d2a70749d622ba992590a0d0db35790
|
2023-01-18 18:51:07
|
Sanchith Hegde
|
fix(redis_interface): add missing `#[serde(default)]` annotation to `RedisSettings` (#409)
| false
|
diff --git a/crates/redis_interface/src/types.rs b/crates/redis_interface/src/types.rs
index 28fa49649fe..439e31f258e 100644
--- a/crates/redis_interface/src/types.rs
+++ b/crates/redis_interface/src/types.rs
@@ -9,6 +9,7 @@ use error_stack::IntoReport;
use crate::errors;
#[derive(Debug, serde::Deserialize, Clone)]
+#[serde(default)]
pub struct RedisSettings {
pub host: String,
pub port: u16,
|
fix
|
add missing `#[serde(default)]` annotation to `RedisSettings` (#409)
|
894560f07bbc820152941ea8ad4005dbc9fb3477
|
2024-06-11 00:24:44
|
Shankar Singh C
|
refactor(business_profile): add `is_connector_agnostic_mit_enabled` in the business profile APIs (#4925)
| false
|
diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 0d693808db7..011ee6d15c2 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -18,7 +18,7 @@ crates/router/src/services/ @juspay/hyperswitch-framework
crates/router/src/db/ @juspay/hyperswitch-framework
crates/router/src/routes/ @juspay/hyperswitch-framework
migrations/ @juspay/hyperswitch-framework
-openapi/ @juspay/hyperswitch-framework
+api-reference/ @juspay/hyperswitch-framework
postman/ @juspay/hyperswitch-framework
cypress-tests/ @juspay/hyperswitch-framework @juspay/hyperswitch-qa
Cargo.toml @juspay/hyperswitch-framework
diff --git a/api-reference/openapi_spec.json b/api-reference/openapi_spec.json
index 2ad48805e51..c303f192cd7 100644
--- a/api-reference/openapi_spec.json
+++ b/api-reference/openapi_spec.json
@@ -6826,6 +6826,11 @@
"type": "boolean",
"description": "A boolean value to indicate if customer shipping details needs to be sent for wallets payments",
"nullable": true
+ },
+ "is_connector_agnostic_mit_enabled": {
+ "type": "boolean",
+ "description": "Indicates if the MIT (merchant initiated transaction) payments can be made connector\nagnostic, i.e., MITs may be processed through different connector than CIT (customer\ninitiated transaction) based on the routing rules.\nIf set to `false`, MIT will go through the same connector as the CIT.",
+ "nullable": true
}
},
"additionalProperties": false
@@ -6962,6 +6967,11 @@
"type": "boolean",
"description": "A boolean value to indicate if customer shipping details needs to be sent for wallets payments",
"nullable": true
+ },
+ "is_connector_agnostic_mit_enabled": {
+ "type": "boolean",
+ "description": "Indicates if the MIT (merchant initiated transaction) payments can be made connector\nagnostic, i.e., MITs may be processed through different connector than CIT (customer\ninitiated transaction) based on the routing rules.\nIf set to `false`, MIT will go through the same connector as the CIT.",
+ "nullable": true
}
}
},
diff --git a/crates/api_models/src/admin.rs b/crates/api_models/src/admin.rs
index 58cb6fbf3e2..bd569b1febb 100644
--- a/crates/api_models/src/admin.rs
+++ b/crates/api_models/src/admin.rs
@@ -938,6 +938,12 @@ pub struct BusinessProfileCreate {
/// A boolean value to indicate if customer shipping details needs to be sent for wallets payments
pub collect_shipping_details_from_wallet_connector: Option<bool>,
+
+ /// Indicates if the MIT (merchant initiated transaction) payments can be made connector
+ /// agnostic, i.e., MITs may be processed through different connector than CIT (customer
+ /// initiated transaction) based on the routing rules.
+ /// If set to `false`, MIT will go through the same connector as the CIT.
+ pub is_connector_agnostic_mit_enabled: Option<bool>,
}
#[derive(Clone, Debug, ToSchema, Serialize)]
@@ -1016,6 +1022,12 @@ pub struct BusinessProfileResponse {
/// A boolean value to indicate if customer shipping details needs to be sent for wallets payments
pub collect_shipping_details_from_wallet_connector: Option<bool>,
+
+ /// Indicates if the MIT (merchant initiated transaction) payments can be made connector
+ /// agnostic, i.e., MITs may be processed through different connector than CIT (customer
+ /// initiated transaction) based on the routing rules.
+ /// If set to `false`, MIT will go through the same connector as the CIT.
+ pub is_connector_agnostic_mit_enabled: Option<bool>,
}
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
@@ -1086,6 +1098,12 @@ pub struct BusinessProfileUpdate {
/// A boolean value to indicate if customer shipping details needs to be sent for wallets payments
pub collect_shipping_details_from_wallet_connector: Option<bool>,
+
+ /// Indicates if the MIT (merchant initiated transaction) payments can be made connector
+ /// agnostic, i.e., MITs may be processed through different connector than CIT (customer
+ /// initiated transaction) based on the routing rules.
+ /// If set to `false`, MIT will go through the same connector as the CIT.
+ pub is_connector_agnostic_mit_enabled: Option<bool>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
diff --git a/crates/diesel_models/src/business_profile.rs b/crates/diesel_models/src/business_profile.rs
index fb1b62e5436..872bb0c09d6 100644
--- a/crates/diesel_models/src/business_profile.rs
+++ b/crates/diesel_models/src/business_profile.rs
@@ -124,6 +124,7 @@ pub enum BusinessProfileUpdate {
extended_card_info_config: Option<pii::SecretSerdeValue>,
use_billing_as_payment_method_billing: Option<bool>,
collect_shipping_details_from_wallet_connector: Option<bool>,
+ is_connector_agnostic_mit_enabled: Option<bool>,
},
ExtendedCardInfoUpdate {
is_extended_card_info_enabled: Option<bool>,
@@ -157,6 +158,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
extended_card_info_config,
use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector,
+ is_connector_agnostic_mit_enabled,
} => Self {
profile_name,
modified_at,
@@ -178,6 +180,7 @@ impl From<BusinessProfileUpdate> for BusinessProfileUpdateInternal {
extended_card_info_config,
use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector,
+ is_connector_agnostic_mit_enabled,
..Default::default()
},
BusinessProfileUpdate::ExtendedCardInfoUpdate {
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index f9da9908d95..bd1b122f57c 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -442,6 +442,7 @@ pub async fn update_business_profile_cascade(
extended_card_info_config: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
+ is_connector_agnostic_mit_enabled: None,
};
let update_futures = business_profiles.iter().map(|business_profile| async {
@@ -1728,6 +1729,7 @@ pub async fn update_business_profile(
use_billing_as_payment_method_billing: request.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: request
.collect_shipping_details_from_wallet_connector,
+ is_connector_agnostic_mit_enabled: request.is_connector_agnostic_mit_enabled,
};
let updated_business_profile = db
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 2e1032e8e4c..c77802a1503 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -277,6 +277,7 @@ pub async fn update_business_profile_active_algorithm_ref(
extended_card_info_config: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
+ is_connector_agnostic_mit_enabled: None,
};
db.update_business_profile_by_profile_id(current_business_profile, business_profile_update)
diff --git a/crates/router/src/types/api/admin.rs b/crates/router/src/types/api/admin.rs
index b79819ed634..09c362c1164 100644
--- a/crates/router/src/types/api/admin.rs
+++ b/crates/router/src/types/api/admin.rs
@@ -87,6 +87,7 @@ impl ForeignTryFrom<storage::business_profile::BusinessProfile> for BusinessProf
.transpose()?,
collect_shipping_details_from_wallet_connector: item
.collect_shipping_details_from_wallet_connector,
+ is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
})
}
}
@@ -183,7 +184,7 @@ impl ForeignTryFrom<(domain::MerchantAccount, BusinessProfileCreate)>
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "authentication_connector_details",
})?,
- is_connector_agnostic_mit_enabled: None,
+ is_connector_agnostic_mit_enabled: request.is_connector_agnostic_mit_enabled,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
use_billing_as_payment_method_billing: request
|
refactor
|
add `is_connector_agnostic_mit_enabled` in the business profile APIs (#4925)
|
3d7d89172c9ef1af99ec1e0d5c72b0d5546cce1f
|
2022-12-09 17:58:04
|
Kartikeya Hegde
|
customers: Added ephemeral key authentication for customer retrieve (#89)
| false
|
diff --git a/crates/router/src/compatibility/stripe/errors.rs b/crates/router/src/compatibility/stripe/errors.rs
index f0dbe281929..22dbcb1af18 100644
--- a/crates/router/src/compatibility/stripe/errors.rs
+++ b/crates/router/src/compatibility/stripe/errors.rs
@@ -303,7 +303,9 @@ pub(crate) enum StripeErrorType {
impl From<ApiErrorResponse> for ErrorCode {
fn from(value: ApiErrorResponse) -> Self {
match value {
- ApiErrorResponse::Unauthorized => ErrorCode::Unauthorized,
+ ApiErrorResponse::Unauthorized | ApiErrorResponse::InvalidEphermeralKey => {
+ ErrorCode::Unauthorized
+ }
ApiErrorResponse::InvalidRequestUrl | ApiErrorResponse::InvalidHttpMethod => {
ErrorCode::InvalidRequestUrl
}
diff --git a/crates/router/src/connector/aci.rs b/crates/router/src/connector/aci.rs
index 72f9a0df012..a8567cf2ff5 100644
--- a/crates/router/src/connector/aci.rs
+++ b/crates/router/src/connector/aci.rs
@@ -109,7 +109,10 @@ impl
"{}{}{}{}{}",
self.base_url(connectors),
"v1/payments/",
- req.request.connector_transaction_id,
+ req.request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
"?entityId=",
auth.entity_id
))
diff --git a/crates/router/src/connector/adyen/transformers.rs b/crates/router/src/connector/adyen/transformers.rs
index 7cdf63ab748..cf8c71da1ac 100644
--- a/crates/router/src/connector/adyen/transformers.rs
+++ b/crates/router/src/connector/adyen/transformers.rs
@@ -130,7 +130,7 @@ pub struct AdyenRedirectionAction {
method: String,
#[serde(rename = "type")]
type_of_response: String,
- data: HashMap<String, String>,
+ data: Option<HashMap<String, String>>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
@@ -491,12 +491,21 @@ pub fn get_redirection_response(
.change_context(errors::ParsingError)
.attach_printable("Failed to parse redirection url")?;
+ let form_field_for_redirection = match response.action.data {
+ Some(data) => data,
+ None => std::collections::HashMap::from_iter(
+ redirection_url_response
+ .query_pairs()
+ .map(|(k, v)| (k.to_string(), v.to_string())),
+ ),
+ };
+
let redirection_data = services::RedirectForm {
url: redirection_url_response.to_string(),
method: services::Method::from_str(&response.action.method)
.into_report()
.change_context(errors::ParsingError)?,
- form_fields: response.action.data,
+ form_fields: form_field_for_redirection,
};
// We don't get connector transaction id for redirections in Adyen.
diff --git a/crates/router/src/connector/braintree.rs b/crates/router/src/connector/braintree.rs
index 798d29b84bc..8d591700aa2 100644
--- a/crates/router/src/connector/braintree.rs
+++ b/crates/router/src/connector/braintree.rs
@@ -108,7 +108,11 @@ impl
) -> CustomResult<String, errors::ConnectorError> {
let auth_type = braintree::BraintreeAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
- let connector_payment_id = req.request.connector_transaction_id.clone();
+ let connector_payment_id = req
+ .request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/merchants/{}/transactions/{}",
self.base_url(connectors),
diff --git a/crates/router/src/connector/checkout.rs b/crates/router/src/connector/checkout.rs
index 64d20f9659a..f1df92b9411 100644
--- a/crates/router/src/connector/checkout.rs
+++ b/crates/router/src/connector/checkout.rs
@@ -107,7 +107,10 @@ impl
"{}{}{}",
self.base_url(connectors),
"payments/",
- req.request.connector_transaction_id
+ req.request
+ .connector_transaction_id
+ .get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?
))
}
diff --git a/crates/router/src/connector/stripe.rs b/crates/router/src/connector/stripe.rs
index 7109fb153f0..b682933a091 100644
--- a/crates/router/src/connector/stripe.rs
+++ b/crates/router/src/connector/stripe.rs
@@ -202,7 +202,8 @@ impl
"{}{}/{}",
self.base_url(connectors),
"v1/payment_intents",
- id
+ id.get_connector_transaction_id()
+ .change_context(errors::ConnectorError::MissingConnectorTransactionID)?
))
}
diff --git a/crates/router/src/core/errors.rs b/crates/router/src/core/errors.rs
index 6aa621d4068..96e44e5c639 100644
--- a/crates/router/src/core/errors.rs
+++ b/crates/router/src/core/errors.rs
@@ -286,6 +286,8 @@ pub enum ConnectorError {
FailedToObtainAuthType,
#[error("This step has not been implemented for: {0}")]
NotImplemented(String),
+ #[error("Missing connector transaction ID")]
+ MissingConnectorTransactionID,
#[error("Webhooks not implemented for this connector")]
WebhooksNotImplemented,
#[error("Failed to decode webhook event body")]
diff --git a/crates/router/src/core/errors/api_error_response.rs b/crates/router/src/core/errors/api_error_response.rs
index 9a2377ae429..c79dcbe73aa 100644
--- a/crates/router/src/core/errors/api_error_response.rs
+++ b/crates/router/src/core/errors/api_error_response.rs
@@ -28,6 +28,8 @@ pub enum ApiErrorResponse {
the Dashboard Settings section."
)]
BadCredentials,
+ #[error(error_type = ErrorType::InvalidRequestError, code = "IR_10", message = "Invalid Ephemeral Key for the customer")]
+ InvalidEphermeralKey,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_03", message = "Unrecognized request URL.")]
InvalidRequestUrl,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_04", message = "The HTTP method is not applicable for this API.")]
@@ -137,9 +139,9 @@ impl actix_web::ResponseError for ApiErrorResponse {
use reqwest::StatusCode;
match self {
- ApiErrorResponse::Unauthorized | ApiErrorResponse::BadCredentials => {
- StatusCode::UNAUTHORIZED
- } // 401
+ ApiErrorResponse::Unauthorized
+ | ApiErrorResponse::BadCredentials
+ | ApiErrorResponse::InvalidEphermeralKey => StatusCode::UNAUTHORIZED, // 401
ApiErrorResponse::InvalidRequestUrl => StatusCode::NOT_FOUND, // 404
ApiErrorResponse::InvalidHttpMethod => StatusCode::METHOD_NOT_ALLOWED, // 405
ApiErrorResponse::MissingRequiredField { .. }
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index beccb70bfa0..97d802b2e16 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -12,6 +12,7 @@ use super::{
};
use crate::{
configs::settings::Server,
+ consts,
core::{
errors::{self, CustomResult, RouterResult, StorageErrorExt},
payment_methods::cards,
@@ -21,7 +22,7 @@ use crate::{
services,
types::{
api::{self, enums as api_enums},
- storage::{self, enums as storage_enums},
+ storage::{self, enums as storage_enums, ephemeral_key},
},
utils::{
self,
@@ -571,7 +572,7 @@ pub async fn create_customer_if_not_exist<'a, F: Clone, R>(
pub async fn make_pm_data<'a, F: Clone, R>(
operation: BoxedOperation<'a, F, R>,
state: &'a AppState,
- payment_method: Option<storage_enums::PaymentMethodType>,
+ payment_method_type: Option<storage_enums::PaymentMethodType>,
txn_id: &str,
_payment_attempt: &storage::PaymentAttempt,
request: &Option<api::PaymentMethod>,
@@ -579,7 +580,7 @@ pub async fn make_pm_data<'a, F: Clone, R>(
) -> RouterResult<(BoxedOperation<'a, F, R>, Option<api::PaymentMethod>)> {
let payment_method = match (request, token) {
(_, Some(token)) => Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(
- if payment_method == Some(storage_enums::PaymentMethodType::Card) {
+ if payment_method_type == Some(storage_enums::PaymentMethodType::Card) {
// TODO: Handle token expiry
Vault::get_payment_method_data_from_locker(state, token).await?
} else {
@@ -598,7 +599,13 @@ pub async fn make_pm_data<'a, F: Clone, R>(
let payment_method = match payment_method {
Some(pm) => Some(pm),
- None => Vault::get_payment_method_data_from_locker(state, txn_id).await?,
+ None => {
+ if payment_method_type == Some(storage_enums::PaymentMethodType::Card) {
+ Vault::get_payment_method_data_from_locker(state, txn_id).await?
+ } else {
+ None
+ }
+ }
};
Ok((operation, payment_method))
@@ -897,6 +904,40 @@ pub fn make_merchant_url_with_response(
Ok(merchant_url_with_response.to_string())
}
+pub async fn make_ephemeral_key(
+ state: &AppState,
+ customer_id: String,
+ merchant_id: String,
+) -> errors::RouterResponse<ephemeral_key::EphemeralKey> {
+ let store = &state.store;
+ let id = utils::generate_id(consts::ID_LENGTH, "eki");
+ let secret = format!("epk_{}", &Uuid::new_v4().simple().to_string());
+ let ek = ephemeral_key::EphemeralKeyNew {
+ id,
+ customer_id,
+ merchant_id,
+ secret,
+ };
+ let ek = store
+ .create_ephemeral_key(ek, state.conf.eph_key.validity)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to create ephemeral key")?;
+ Ok(services::BachResponse::Json(ek))
+}
+
+pub async fn delete_ephemeral_key(
+ store: &dyn StorageInterface,
+ ek_id: String,
+) -> errors::RouterResponse<ephemeral_key::EphemeralKey> {
+ let ek = store
+ .delete_ephemeral_key(&ek_id)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to delete ephemeral key")?;
+ Ok(services::BachResponse::Json(ek))
+}
+
pub fn make_pg_redirect_response(
payment_id: String,
response: &api::PaymentsResponse,
diff --git a/crates/router/src/core/payments/operations/payment_response.rs b/crates/router/src/core/payments/operations/payment_response.rs
index e14e13e9e34..bb4535ffe7d 100644
--- a/crates/router/src/core/payments/operations/payment_response.rs
+++ b/crates/router/src/core/payments/operations/payment_response.rs
@@ -154,12 +154,15 @@ async fn payment_response_ut<F: Clone, T>(
storage::PaymentAttemptUpdate::ResponseUpdate {
status: router_data.status,
- connector_transaction_id: Some(
- response
- .resource_id
- .get_connector_transaction_id()
- .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?,
- ),
+ connector_transaction_id: match response.resource_id {
+ types::ResponseId::NoResponseId => None,
+ _ => Some(
+ response
+ .resource_id
+ .get_connector_transaction_id()
+ .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?,
+ ),
+ },
authentication_type: None,
payment_method_id: Some(router_data.payment_method_id),
redirect: Some(response.redirect),
@@ -187,12 +190,15 @@ async fn payment_response_ut<F: Clone, T>(
.attach_printable("Could not parse the connector response")?;
let connector_response_update = storage::ConnectorResponseUpdate::ResponseUpdate {
- connector_transaction_id: Some(
- connector_response
- .resource_id
- .get_connector_transaction_id()
- .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?,
- ),
+ connector_transaction_id: match connector_response.resource_id {
+ types::ResponseId::NoResponseId => None,
+ _ => Some(
+ connector_response
+ .resource_id
+ .get_connector_transaction_id()
+ .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?,
+ ),
+ },
authentication_data,
encoded_data: payment_data.connector_response.encoded_data.clone(),
};
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index da9c6863016..df63eb59e53 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -376,10 +376,12 @@ impl<F: Clone> TryFrom<PaymentData<F>> for types::PaymentsSyncData {
fn try_from(payment_data: PaymentData<F>) -> Result<Self, Self::Error> {
Ok(Self {
- connector_transaction_id: payment_data
- .payment_attempt
- .connector_transaction_id
- .ok_or(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?,
+ connector_transaction_id: match payment_data.payment_attempt.connector_transaction_id {
+ Some(connector_txn_id) => {
+ types::ResponseId::ConnectorTransactionId(connector_txn_id)
+ }
+ None => types::ResponseId::NoResponseId,
+ },
encoded_data: payment_data.connector_response.encoded_data,
})
}
diff --git a/crates/router/src/db/ephemeral_key.rs b/crates/router/src/db/ephemeral_key.rs
index b1db0c0d5bb..81a99a16d0d 100644
--- a/crates/router/src/db/ephemeral_key.rs
+++ b/crates/router/src/db/ephemeral_key.rs
@@ -49,8 +49,8 @@ mod storage {
let expires = created_at.saturating_add(validity.hours());
let created_ek = EphemeralKey {
id: new.id,
- created_at,
- expires,
+ created_at: created_at.assume_utc().unix_timestamp(),
+ expires: expires.assume_utc().unix_timestamp(),
customer_id: new.customer_id,
merchant_id: new.merchant_id,
secret: new.secret,
diff --git a/crates/router/src/lib.rs b/crates/router/src/lib.rs
index c6553349f9b..c918af20f97 100644
--- a/crates/router/src/lib.rs
+++ b/crates/router/src/lib.rs
@@ -105,6 +105,7 @@ pub fn mk_app(
.service(routes::PaymentMethods::server(state.clone()))
.service(routes::MerchantAccount::server(state.clone()))
.service(routes::MerchantConnectorAccount::server(state.clone()))
+ .service(routes::EphemeralKey::server(state.clone()))
.service(routes::Webhooks::server(state.clone()));
#[cfg(feature = "stripe")]
diff --git a/crates/router/src/routes.rs b/crates/router/src/routes.rs
index ffc5bdcf6fd..854a949044b 100644
--- a/crates/router/src/routes.rs
+++ b/crates/router/src/routes.rs
@@ -1,6 +1,7 @@
mod admin;
mod app;
mod customers;
+mod ephemeral_key;
mod health;
mod mandates;
mod metrics;
@@ -11,7 +12,7 @@ mod refunds;
mod webhooks;
pub use self::app::{
- AppState, Customers, Health, Mandates, MerchantAccount, MerchantConnectorAccount,
+ AppState, Customers, EphemeralKey, Health, Mandates, MerchantAccount, MerchantConnectorAccount,
PaymentMethods, Payments, Payouts, Refunds, Webhooks,
};
#[cfg(feature = "stripe")]
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 554c8e1ce5c..8310f428f4f 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1,8 +1,8 @@
use actix_web::{web, Scope};
use super::{
- admin::*, customers::*, health::*, mandates::*, payment_methods::*, payments::*, payouts::*,
- refunds::*, webhooks::*,
+ admin::*, customers::*, ephemeral_key::*, health::*, mandates::*, payment_methods::*,
+ payments::*, payouts::*, refunds::*, webhooks::*,
};
use crate::{
configs::settings::Settings,
@@ -189,6 +189,17 @@ impl MerchantConnectorAccount {
}
}
+pub struct EphemeralKey;
+
+impl EphemeralKey {
+ pub fn server(config: AppState) -> Scope {
+ web::scope("/ephemeral_keys")
+ .app_data(web::Data::new(config))
+ .service(web::resource("").route(web::post().to(ephemeral_key_create)))
+ .service(web::resource("/{id}").route(web::delete().to(ephemeral_key_delete)))
+ }
+}
+
pub struct Mandates;
impl Mandates {
diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs
index ecd7a298add..b60cb007120 100644
--- a/crates/router/src/routes/customers.rs
+++ b/crates/router/src/routes/customers.rs
@@ -5,7 +5,11 @@ use router_env::{
};
use super::app::AppState;
-use crate::{core::customers::*, services::api, types::api::customers};
+use crate::{
+ core::customers::*,
+ services::{self, api},
+ types::api::customers,
+};
#[instrument(skip_all, fields(flow = ?Flow::CustomersCreate))]
// #[post("")]
@@ -35,12 +39,22 @@ pub async fn customers_retrieve(
customer_id: path.into_inner(),
})
.into_inner();
+ let auth_type = match services::authenticate_eph_key(
+ &req,
+ &*state.store,
+ payload.customer_id.clone(),
+ )
+ .await
+ {
+ Ok(auth_type) => auth_type,
+ Err(err) => return api::log_and_return_error_response(err),
+ };
api::server_wrap(
&state,
&req,
payload,
|state, merchant_account, req| retrieve_customer(&*state.store, merchant_account, req),
- api::MerchantAuthentication::ApiKey,
+ auth_type,
)
.await
}
diff --git a/crates/router/src/routes/ephemeral_key.rs b/crates/router/src/routes/ephemeral_key.rs
new file mode 100644
index 00000000000..30a580a0f50
--- /dev/null
+++ b/crates/router/src/routes/ephemeral_key.rs
@@ -0,0 +1,44 @@
+use actix_web::{web, HttpRequest, HttpResponse};
+use router_env::{
+ tracing::{self, instrument},
+ Flow,
+};
+
+use super::AppState;
+use crate::{core::payments::helpers, services::api, types::api::customers};
+
+#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyCreate))]
+pub async fn ephemeral_key_create(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ json_payload: web::Json<customers::CustomerId>,
+) -> HttpResponse {
+ let payload = json_payload.into_inner();
+ api::server_wrap(
+ &state,
+ &req,
+ payload,
+ |state, merchant_account, req| {
+ helpers::make_ephemeral_key(state, req.customer_id, merchant_account.merchant_id)
+ },
+ api::MerchantAuthentication::ApiKey,
+ )
+ .await
+}
+
+#[instrument(skip_all, fields(flow = ?Flow::EphemeralKeyDelete))]
+pub async fn ephemeral_key_delete(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+) -> HttpResponse {
+ let payload = path.into_inner();
+ api::server_wrap(
+ &state,
+ &req,
+ payload,
+ |state, _, req| helpers::delete_ephemeral_key(&*state.store, req),
+ api::MerchantAuthentication::ApiKey,
+ )
+ .await
+}
diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rs
index d94bd3bacfe..1ef2da29c32 100644
--- a/crates/router/src/services/api.rs
+++ b/crates/router/src/services/api.rs
@@ -31,7 +31,7 @@ use crate::{
storage::{self, enums},
ErrorResponse, Response,
},
- utils::OptionExt,
+ utils::{self, OptionExt},
};
pub type BoxedConnectorIntegration<'a, T, Req, Resp> =
@@ -596,6 +596,29 @@ pub(crate) fn get_auth_type_and_check_client_secret(
))
}
+pub(crate) async fn authenticate_eph_key<'a>(
+ req: &'a actix_web::HttpRequest,
+ store: &dyn StorageInterface,
+ customer_id: String,
+) -> RouterResult<MerchantAuthentication<'a>> {
+ let api_key = get_api_key(req)?;
+ if api_key.starts_with("epk") {
+ let ek = store
+ .get_ephemeral_key(api_key)
+ .await
+ .change_context(errors::ApiErrorResponse::BadCredentials)?;
+ utils::when(
+ ek.customer_id.ne(&customer_id),
+ Err(report!(errors::ApiErrorResponse::InvalidEphermeralKey)),
+ )?;
+ Ok(MerchantAuthentication::MerchantId(Cow::Owned(
+ ek.merchant_id,
+ )))
+ } else {
+ Ok(MerchantAuthentication::ApiKey)
+ }
+}
+
fn get_api_key(req: &HttpRequest) -> RouterResult<&str> {
req.headers()
.get("api-key")
diff --git a/crates/router/src/types.rs b/crates/router/src/types.rs
index be1abcaf8a7..0c904a16bdb 100644
--- a/crates/router/src/types.rs
+++ b/crates/router/src/types.rs
@@ -104,7 +104,7 @@ pub struct PaymentsCaptureData {
#[derive(Debug, Clone)]
pub struct PaymentsSyncData {
//TODO : add fields based on the connector requirements
- pub connector_transaction_id: String,
+ pub connector_transaction_id: ResponseId,
pub encoded_data: Option<String>,
}
diff --git a/crates/router/src/types/storage/ephemeral_key.rs b/crates/router/src/types/storage/ephemeral_key.rs
index d3afbbdcfa8..44226d50fd6 100644
--- a/crates/router/src/types/storage/ephemeral_key.rs
+++ b/crates/router/src/types/storage/ephemeral_key.rs
@@ -10,7 +10,7 @@ pub struct EphemeralKey {
pub id: String,
pub merchant_id: String,
pub customer_id: String,
- pub created_at: time::PrimitiveDateTime,
- pub expires: time::PrimitiveDateTime,
+ pub created_at: i64,
+ pub expires: i64,
pub secret: String,
}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index 29b3e7b722c..bc9f52a6860 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -80,6 +80,10 @@ pub enum Flow {
CustomersDelete,
/// Customers get mandates flow.
CustomersGetMandates,
+ /// Create an Ephemeral Key.
+ EphemeralKeyCreate,
+ /// Delete an Ephemeral Key.
+ EphemeralKeyDelete,
/// Mandates retrieve flow.
MandatesRetrieve,
/// Mandates revoke flow.
|
customers
|
Added ephemeral key authentication for customer retrieve (#89)
|
d63f6f7224f35018e7c707353508bbacc2baed5c
|
2023-11-28 21:35:42
|
ShivanshMathurJuspay
|
refactor(events): Adding changes to type of API events to Kafka (#2992)
| false
|
diff --git a/crates/router/src/events/api_logs.rs b/crates/router/src/events/api_logs.rs
index 3f0bf651c46..3f598e88394 100644
--- a/crates/router/src/events/api_logs.rs
+++ b/crates/router/src/events/api_logs.rs
@@ -31,11 +31,11 @@ pub struct ApiEvent {
status_code: i64,
#[serde(flatten)]
auth_type: AuthenticationType,
- request: serde_json::Value,
+ request: String,
user_agent: Option<String>,
ip_addr: Option<String>,
url_path: String,
- response: Option<serde_json::Value>,
+ response: Option<String>,
error: Option<serde_json::Value>,
#[serde(flatten)]
event_type: ApiEventsType,
@@ -59,12 +59,12 @@ impl ApiEvent {
) -> Self {
Self {
api_flow: api_flow.to_string(),
- created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos(),
+ created_at_timestamp: OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000,
request_id: request_id.as_hyphenated().to_string(),
latency,
status_code,
- request,
- response,
+ request: request.to_string(),
+ response: response.map(|resp| resp.to_string()),
auth_type,
error,
ip_addr: http_req
diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rs
index e24c7cebcb2..b01e3762bfa 100644
--- a/crates/router/src/services/authentication.rs
+++ b/crates/router/src/services/authentication.rs
@@ -47,11 +47,11 @@ pub enum AuthenticationType {
key_id: String,
},
AdminApiKey,
- MerchantJWT {
+ MerchantJwt {
merchant_id: String,
user_id: Option<String>,
},
- MerchantID {
+ MerchantId {
merchant_id: String,
},
PublishableKey {
@@ -70,9 +70,9 @@ impl AuthenticationType {
merchant_id,
key_id: _,
}
- | Self::MerchantID { merchant_id }
+ | Self::MerchantId { merchant_id }
| Self::PublishableKey { merchant_id }
- | Self::MerchantJWT {
+ | Self::MerchantJwt {
merchant_id,
user_id: _,
}
@@ -352,7 +352,7 @@ where
};
Ok((
auth.clone(),
- AuthenticationType::MerchantID {
+ AuthenticationType::MerchantId {
merchant_id: auth.merchant_account.merchant_id.clone(),
},
))
@@ -423,7 +423,7 @@ where
Ok((
(),
- AuthenticationType::MerchantJWT {
+ AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
@@ -451,7 +451,7 @@ where
org_id: payload.org_id,
role_id: payload.role_id,
},
- AuthenticationType::MerchantJWT {
+ AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
@@ -479,13 +479,13 @@ where
let permissions = authorization::get_permissions(&payload.role_id)?;
authorization::check_authorization(&self.required_permission, permissions)?;
- // Check if token has access to merchantID that has been requested through query param
+ // Check if token has access to MerchantId that has been requested through query param
if payload.merchant_id != self.merchant_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
Ok((
(),
- AuthenticationType::MerchantJWT {
+ AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
@@ -549,7 +549,7 @@ where
};
Ok((
auth.clone(),
- AuthenticationType::MerchantJWT {
+ AuthenticationType::MerchantJwt {
merchant_id: auth.merchant_account.merchant_id.clone(),
user_id: None,
},
@@ -579,7 +579,7 @@ where
org_id: payload.org_id,
role_id: payload.role_id,
},
- AuthenticationType::MerchantJWT {
+ AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
|
refactor
|
Adding changes to type of API events to Kafka (#2992)
|
be4419865fb05172bde39b9273c9f5b216b1a1ad
|
2024-08-29 12:15:35
|
Narayan Bhat
|
refactor(customers): add offset and limit to customers list (#5735)
| false
|
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rs
index 6a9f2b64791..e689e66489c 100644
--- a/crates/api_models/src/customers.rs
+++ b/crates/api_models/src/customers.rs
@@ -48,6 +48,16 @@ pub struct CustomerRequest {
pub metadata: Option<pii::SecretSerdeValue>,
}
+#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)]
+pub struct CustomerListRequest {
+ /// Offset
+ #[schema(example = 32)]
+ pub offset: Option<u32>,
+ /// Limit
+ #[schema(example = 32)]
+ pub limit: Option<u16>,
+}
+
#[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))]
impl CustomerRequest {
pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> {
diff --git a/crates/api_models/src/events.rs b/crates/api_models/src/events.rs
index a0808c0c24b..58727a46cf3 100644
--- a/crates/api_models/src/events.rs
+++ b/crates/api_models/src/events.rs
@@ -19,6 +19,7 @@ use common_utils::{
impl_api_event_type,
};
+use crate::customers::CustomerListRequest;
#[allow(unused_imports)]
use crate::{
admin::*,
@@ -131,7 +132,8 @@ impl_api_event_type!(
GetDisputeMetricRequest,
OrganizationResponse,
OrganizationRequest,
- OrganizationId
+ OrganizationId,
+ CustomerListRequest
)
);
diff --git a/crates/diesel_models/src/query/customers.rs b/crates/diesel_models/src/query/customers.rs
index ddcaeafd315..cf6e8fa645f 100644
--- a/crates/diesel_models/src/query/customers.rs
+++ b/crates/diesel_models/src/query/customers.rs
@@ -23,6 +23,11 @@ impl CustomerNew {
}
}
+pub struct CustomerListConstraints {
+ pub limit: i64,
+ pub offset: Option<i64>,
+}
+
// #[cfg(all(feature = "v2", feature = "customer_v2"))]
impl Customer {
#[cfg(all(feature = "v2", feature = "customer_v2"))]
@@ -56,12 +61,13 @@ impl Customer {
pub async fn list_by_merchant_id(
conn: &PgPooledConn,
merchant_id: &id_type::MerchantId,
+ constraints: CustomerListConstraints,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
- None,
- None,
+ Some(constraints.limit),
+ constraints.offset,
Some(dsl::created_at),
)
.await
diff --git a/crates/router/src/consts.rs b/crates/router/src/consts.rs
index 5a7070c2700..d7afe8dafde 100644
--- a/crates/router/src/consts.rs
+++ b/crates/router/src/consts.rs
@@ -32,6 +32,8 @@ pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60;
/// The length of a merchant fingerprint secret
pub const FINGERPRINT_SECRET_LENGTH: usize = 64;
+pub const DEFAULT_LIST_API_LIMIT: u16 = 10;
+
// String literals
pub(crate) const UNSUPPORTED_ERROR_MESSAGE: &str = "Unsupported response type";
pub(crate) const LOW_BALANCE_ERROR_MESSAGE: &str = "Insufficient balance in the payment method";
diff --git a/crates/router/src/core/customers.rs b/crates/router/src/core/customers.rs
index 1044ca78224..a38078b5a2b 100644
--- a/crates/router/src/core/customers.rs
+++ b/crates/router/src/core/customers.rs
@@ -496,10 +496,24 @@ pub async fn list_customers(
merchant_id: id_type::MerchantId,
_profile_id_list: Option<Vec<id_type::ProfileId>>,
key_store: domain::MerchantKeyStore,
+ request: customers::CustomerListRequest,
) -> errors::CustomerResponse<Vec<customers::CustomerResponse>> {
let db = state.store.as_ref();
+
+ let customer_list_constraints = crate::db::customers::CustomerListConstraints {
+ limit: request
+ .limit
+ .unwrap_or(crate::consts::DEFAULT_LIST_API_LIMIT),
+ offset: request.offset,
+ };
+
let domain_customers = db
- .list_customers_by_merchant_id(&(&state).into(), &merchant_id, &key_store)
+ .list_customers_by_merchant_id(
+ &(&state).into(),
+ &merchant_id,
+ &key_store,
+ customer_list_constraints,
+ )
.await
.switch()?;
diff --git a/crates/router/src/core/locker_migration.rs b/crates/router/src/core/locker_migration.rs
index 14a27c9ecff..107586ee26d 100644
--- a/crates/router/src/core/locker_migration.rs
+++ b/crates/router/src/core/locker_migration.rs
@@ -49,6 +49,8 @@ pub async fn rust_locker_migration(
state: SessionState,
merchant_id: &id_type::MerchantId,
) -> CustomResult<services::ApplicationResponse<MigrateCardResponse>, errors::ApiErrorResponse> {
+ use crate::db::customers::CustomerListConstraints;
+
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let key_store = state
@@ -67,8 +69,14 @@ pub async fn rust_locker_migration(
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
+ // Handle cases where the number of customers is greater than the limit
+ let constraints = CustomerListConstraints {
+ limit: u16::MAX,
+ offset: None,
+ };
+
let domain_customers = db
- .list_customers_by_merchant_id(key_manager_state, merchant_id, &key_store)
+ .list_customers_by_merchant_id(key_manager_state, merchant_id, &key_store, constraints)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)?;
diff --git a/crates/router/src/db/customers.rs b/crates/router/src/db/customers.rs
index 084177d9509..b271a16d9d9 100644
--- a/crates/router/src/db/customers.rs
+++ b/crates/router/src/db/customers.rs
@@ -1,4 +1,5 @@
use common_utils::{ext_traits::AsyncExt, id_type, types::keymanager::KeyManagerState};
+use diesel_models::query::customers::CustomerListConstraints as DieselCustomerListConstraints;
use error_stack::ResultExt;
use futures::future::try_join_all;
use hyperswitch_domain_models::customer;
@@ -17,6 +18,20 @@ use crate::{
},
};
+pub struct CustomerListConstraints {
+ pub limit: u16,
+ pub offset: Option<u32>,
+}
+
+impl From<CustomerListConstraints> for DieselCustomerListConstraints {
+ fn from(value: CustomerListConstraints) -> Self {
+ Self {
+ limit: i64::from(value.limit),
+ offset: value.offset.map(i64::from),
+ }
+ }
+}
+
#[async_trait::async_trait]
pub trait CustomerInterface
where
@@ -88,6 +103,7 @@ where
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
+ constraints: CustomerListConstraints,
) -> CustomResult<Vec<customer::Customer>, errors::StorageError>;
async fn insert_customer(
@@ -514,13 +530,20 @@ mod storage {
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
+ constraints: super::CustomerListConstraints,
) -> CustomResult<Vec<customer::Customer>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- let encrypted_customers =
- storage_types::Customer::list_by_merchant_id(&conn, merchant_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
+ let customer_list_constraints =
+ diesel_models::query::customers::CustomerListConstraints::from(constraints);
+
+ let encrypted_customers = storage_types::Customer::list_by_merchant_id(
+ &conn,
+ merchant_id,
+ customer_list_constraints,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?;
let customers = try_join_all(encrypted_customers.into_iter().map(
|encrypted_customer| async {
@@ -1055,13 +1078,20 @@ mod storage {
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
+ constraints: super::CustomerListConstraints,
) -> CustomResult<Vec<customer::Customer>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
- let encrypted_customers =
- storage_types::Customer::list_by_merchant_id(&conn, merchant_id)
- .await
- .map_err(|error| report!(errors::StorageError::from(error)))?;
+ let customer_list_constraints =
+ diesel_models::query::customers::CustomerListConstraints::from(constraints);
+
+ let encrypted_customers = storage_types::Customer::list_by_merchant_id(
+ &conn,
+ merchant_id,
+ customer_list_constraints,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))?;
let customers = try_join_all(encrypted_customers.into_iter().map(
|encrypted_customer| async {
@@ -1227,6 +1257,7 @@ impl CustomerInterface for MockDb {
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
+ constraints: CustomerListConstraints,
) -> CustomResult<Vec<customer::Customer>, errors::StorageError> {
let customers = self.customers.lock().await;
@@ -1234,6 +1265,8 @@ impl CustomerInterface for MockDb {
customers
.iter()
.filter(|customer| customer.merchant_id == *merchant_id)
+ .take(usize::from(constraints.limit))
+ .skip(usize::try_from(constraints.offset.unwrap_or(0)).unwrap_or(0))
.map(|customer| async {
customer
.to_owned()
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 0d8b753463b..eb99b6bb85e 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -448,9 +448,10 @@ impl CustomerInterface for KafkaStore {
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
+ constraints: super::customers::CustomerListConstraints,
) -> CustomResult<Vec<domain::Customer>, errors::StorageError> {
self.diesel_store
- .list_customers_by_merchant_id(state, merchant_id, key_store)
+ .list_customers_by_merchant_id(state, merchant_id, key_store, constraints)
.await
}
diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rs
index b770f0ce23d..4c5294d98e6 100644
--- a/crates/router/src/routes/customers.rs
+++ b/crates/router/src/routes/customers.rs
@@ -111,20 +111,26 @@ pub async fn customers_retrieve(
}
#[instrument(skip_all, fields(flow = ?Flow::CustomersList))]
-pub async fn customers_list(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+pub async fn customers_list(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query: web::Query<customers::CustomerListRequest>,
+) -> HttpResponse {
let flow = Flow::CustomersList;
+ let payload = query.into_inner();
api::server_wrap(
flow,
state,
&req,
- (),
- |state, auth, _, _| {
+ payload,
+ |state, auth, request, _| {
list_customers(
state,
auth.merchant_account.get_id().to_owned(),
None,
auth.key_store,
+ request,
)
},
auth::auth_type(
diff --git a/crates/router/src/types/api/customers.rs b/crates/router/src/types/api/customers.rs
index 7c5b960ca5e..9cfec6f7b5b 100644
--- a/crates/router/src/types/api/customers.rs
+++ b/crates/router/src/types/api/customers.rs
@@ -2,7 +2,8 @@ use api_models::customers;
#[cfg(all(feature = "v2", feature = "customer_v2"))]
pub use api_models::customers::GlobalId;
pub use api_models::customers::{
- CustomerDeleteResponse, CustomerId, CustomerRequest, CustomerUpdateRequest, UpdateCustomerId,
+ CustomerDeleteResponse, CustomerId, CustomerListRequest, CustomerRequest,
+ CustomerUpdateRequest, UpdateCustomerId,
};
#[cfg(all(feature = "v2", feature = "customer_v2"))]
use hyperswitch_domain_models::customer;
|
refactor
|
add offset and limit to customers list (#5735)
|
6e5ab0d121d6345f18bccc7f917064caa2737475
|
2023-10-04 17:37:37
|
Chethan Rao
|
refactor(payment_methods): add `requires_cvv` config while creating merchant account (#2431)
| false
|
diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rs
index dabe22da626..c7009bf4cc9 100644
--- a/crates/router/src/core/admin.rs
+++ b/crates/router/src/core/admin.rs
@@ -219,6 +219,17 @@ pub async fn create_merchant_account(
.insert_merchant(merchant_account, &key_store)
.await
.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?;
+
+ db.insert_config(diesel_models::configs::ConfigNew {
+ key: format!("{}_requires_cvv", merchant_account.merchant_id),
+ config: "true".to_string(),
+ })
+ .await
+ .map_err(|err| {
+ crate::logger::error!("Error while setting requires_cvv config: {err:?}");
+ })
+ .ok();
+
Ok(service_api::ApplicationResponse::Json(
merchant_account
.try_into()
diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rs
index c22b7323095..20a3e130eb2 100644
--- a/crates/router/src/core/payment_methods/cards.rs
+++ b/crates/router/src/core/payment_methods/cards.rs
@@ -1831,7 +1831,7 @@ pub async fn list_customer_payment_method(
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to fetch merchant_id config for requires_cvv")?;
+ .attach_printable("Failed to fetch requires_cvv config")?;
let requires_cvv = is_requires_cvv.config != "false";
|
refactor
|
add `requires_cvv` config while creating merchant account (#2431)
|
920b3236ee132dac446fc73de82d24806c6b5148
|
2024-07-24 20:09:41
|
Sakil Mostak
|
feat(connector): [Itaubank] Add refund and rsync flow (#5420)
| false
|
diff --git a/crates/hyperswitch_domain_models/src/router_request_types.rs b/crates/hyperswitch_domain_models/src/router_request_types.rs
index 121087bd115..808000e8dc8 100644
--- a/crates/hyperswitch_domain_models/src/router_request_types.rs
+++ b/crates/hyperswitch_domain_models/src/router_request_types.rs
@@ -414,7 +414,6 @@ pub struct PaymentsSyncData {
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub currency: storage_enums::Currency,
pub payment_experience: Option<common_enums::PaymentExperience>,
- pub browser_info: Option<BrowserInformation>,
pub amount: MinorUnit,
pub integrity_object: Option<SyncIntegrityObject>,
diff --git a/crates/hyperswitch_interfaces/src/consts.rs b/crates/hyperswitch_interfaces/src/consts.rs
index 4d6c27b7554..2ac6ac3c107 100644
--- a/crates/hyperswitch_interfaces/src/consts.rs
+++ b/crates/hyperswitch_interfaces/src/consts.rs
@@ -5,3 +5,9 @@ pub const NO_ERROR_MESSAGE: &str = "No error message";
/// No error code string const
pub const NO_ERROR_CODE: &str = "No error code";
+
+/// Accepted format for request
+pub const ACCEPT_HEADER: &str = "text/html,application/json";
+
+/// User agent for request send from backend server
+pub const USER_AGENT: &str = "Hyperswitch-Backend-Server";
diff --git a/crates/router/src/connector/itaubank.rs b/crates/router/src/connector/itaubank.rs
index aa1ccaa98c7..a31aa9f1e24 100644
--- a/crates/router/src/connector/itaubank.rs
+++ b/crates/router/src/connector/itaubank.rs
@@ -6,10 +6,7 @@ use hyperswitch_interfaces::consts;
use masking::PeekInterface;
use transformers as itaubank;
-use super::utils::{
- self as connector_utils, BrowserInformationData, PaymentsAuthorizeRequestData,
- PaymentsSyncRequestData,
-};
+use super::utils::{self as connector_utils, RefundsRequestData};
use crate::{
configs::settings,
core::errors::{self, CustomResult},
@@ -75,10 +72,24 @@ where
field_name: "access_token",
})?;
- let header = vec![(
- headers::AUTHORIZATION.to_string(),
- format!("Bearer {}", access_token.token.peek()).into(),
- )];
+ let header = vec![
+ (
+ headers::AUTHORIZATION.to_string(),
+ format!("Bearer {}", access_token.token.peek()).into(),
+ ),
+ (
+ headers::ACCEPT.to_string(),
+ consts::ACCEPT_HEADER.to_string().into(),
+ ),
+ (
+ headers::USER_AGENT.to_string(),
+ consts::USER_AGENT.to_string().into(),
+ ),
+ (
+ headers::CONTENT_TYPE.to_string(),
+ self.common_get_content_type().to_string().into(),
+ ),
+ ];
Ok(header)
}
@@ -153,20 +164,22 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
_req: &types::RefreshTokenRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let flow_header = vec![(
- headers::CONTENT_TYPE.to_string(),
- types::RefreshTokenType::get_content_type(self)
- .to_string()
- .into(),
- ),
- (
- headers::ACCEPT.to_string(),
- "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.".to_string().into(),
- ),
- (
- headers::USER_AGENT.to_string(),
- "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36".to_string().into(),
- )];
+ let flow_header = vec![
+ (
+ headers::CONTENT_TYPE.to_string(),
+ types::RefreshTokenType::get_content_type(self)
+ .to_string()
+ .into(),
+ ),
+ (
+ headers::ACCEPT.to_string(),
+ consts::ACCEPT_HEADER.to_string().into(),
+ ),
+ (
+ headers::USER_AGENT.to_string(),
+ consts::USER_AGENT.to_string().into(),
+ ),
+ ];
Ok(flow_header)
}
fn get_request_body(
@@ -187,6 +200,7 @@ impl ConnectorIntegration<api::AccessTokenAuth, types::AccessTokenRequestData, t
let req = Some(
services::RequestBuilder::new()
.method(services::Method::Post)
+ .attach_default_headers()
.headers(types::RefreshTokenType::get_headers(self, req, connectors)?)
.url(&types::RefreshTokenType::get_url(self, req, connectors)?)
.set_body(types::RefreshTokenType::get_request_body(
@@ -273,26 +287,7 @@ impl ConnectorIntegration<api::Authorize, types::PaymentsAuthorizeData, types::P
req: &types::PaymentsAuthorizeRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let mut header = self.build_headers(req, connectors)?;
- let browser_info = req.request.get_browser_info()?;
- let mut flow_header = vec![
- (
- headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
- .to_string()
- .into(),
- ),
- (
- headers::ACCEPT.to_string(),
- browser_info.get_accept_header()?.into(),
- ),
- (
- headers::USER_AGENT.to_string(),
- browser_info.get_user_agent()?.into(),
- ),
- ];
- header.append(&mut flow_header);
- Ok(header)
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -384,26 +379,7 @@ impl ConnectorIntegration<api::PSync, types::PaymentsSyncData, types::PaymentsRe
req: &types::PaymentsSyncRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::Maskable<String>)>, errors::ConnectorError> {
- let mut header = self.build_headers(req, connectors)?;
- let browser_info = req.request.get_browser_info()?;
- let mut flow_header = vec![
- (
- headers::CONTENT_TYPE.to_string(),
- types::PaymentsAuthorizeType::get_content_type(self)
- .to_string()
- .into(),
- ),
- (
- headers::ACCEPT.to_string(),
- browser_info.get_accept_header()?.into(),
- ),
- (
- headers::USER_AGENT.to_string(),
- browser_info.get_user_agent()?.into(),
- ),
- ];
- header.append(&mut flow_header);
- Ok(header)
+ self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
@@ -550,6 +526,17 @@ impl ConnectorIntegration<api::Capture, types::PaymentsCaptureData, types::Payme
impl ConnectorIntegration<api::Void, types::PaymentsCancelData, types::PaymentsResponseData>
for Itaubank
{
+ 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: "itaubank".to_string(),
+ }
+ .into())
+ }
}
impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsResponseData>
@@ -569,10 +556,24 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
fn get_url(
&self,
- _req: &types::RefundsRouterData<api::Execute>,
- _connectors: &settings::Connectors,
+ req: &types::RefundsRouterData<api::Execute>,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let itaubank_metadata = req.request.get_connector_metadata()?;
+ let pix_data: itaubank::ItaubankMetaData = serde_json::from_value(itaubank_metadata)
+ .change_context(errors::ConnectorError::MissingRequiredField {
+ field_name: "itaubank_metadata",
+ })?;
+ Ok(format!(
+ "{}itau-ep9-gtw-pix-recebimentos-ext-v2/v2/pix/{}/devolucao/{}",
+ self.base_url(connectors),
+ pix_data
+ .pix_id
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "pix_id"
+ })?,
+ req.request.connector_transaction_id
+ ))
}
fn get_request_body(
@@ -597,7 +598,7 @@ impl ConnectorIntegration<api::Execute, types::RefundsData, types::RefundsRespon
connectors: &settings::Connectors,
) -> CustomResult<Option<services::Request>, errors::ConnectorError> {
let request = services::RequestBuilder::new()
- .method(services::Method::Post)
+ .method(services::Method::Put)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
@@ -653,10 +654,24 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
fn get_url(
&self,
- _req: &types::RefundSyncRouterData,
- _connectors: &settings::Connectors,
+ req: &types::RefundSyncRouterData,
+ connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
- Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
+ let itaubank_metadata = req.request.get_connector_metadata()?;
+ let pix_data: itaubank::ItaubankMetaData = serde_json::from_value(itaubank_metadata)
+ .change_context(errors::ConnectorError::MissingRequiredField {
+ field_name: "itaubank_metadata",
+ })?;
+ Ok(format!(
+ "{}itau-ep9-gtw-pix-recebimentos-ext-v2/v2/pix/{}/devolucao/{}",
+ self.base_url(connectors),
+ pix_data
+ .pix_id
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "pix_id"
+ })?,
+ req.request.connector_transaction_id
+ ))
}
fn build_request(
@@ -685,7 +700,7 @@ impl ConnectorIntegration<api::RSync, types::RefundsData, types::RefundsResponse
) -> CustomResult<types::RefundSyncRouterData, errors::ConnectorError> {
let response: itaubank::RefundResponse = res
.response
- .parse_struct("itaubank RefundSyncResponse")
+ .parse_struct("itaubank RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
diff --git a/crates/router/src/connector/itaubank/transformers.rs b/crates/router/src/connector/itaubank/transformers.rs
index c6cad43f23c..de96bdb2f2b 100644
--- a/crates/router/src/connector/itaubank/transformers.rs
+++ b/crates/router/src/connector/itaubank/transformers.rs
@@ -302,6 +302,18 @@ fn get_qr_code_data(
pub struct ItaubankPaymentsSyncResponse {
status: ItaubankPaymentStatus,
txid: String,
+ pix: Vec<ItaubankPixResponse>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ItaubankPixResponse {
+ #[serde(rename = "endToEndId")]
+ pix_id: Option<String>,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct ItaubankMetaData {
+ pub pix_id: Option<String>,
}
impl<F, T>
@@ -318,6 +330,19 @@ impl<F, T>
types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
+ let pix_data = item
+ .response
+ .pix
+ .first()
+ .ok_or(errors::ConnectorError::MissingRequiredField {
+ field_name: "pix_id",
+ })?
+ .to_owned();
+
+ let connector_metadata = Some(serde_json::json!(ItaubankMetaData {
+ pix_id: pix_data.pix_id
+ }));
+
Ok(Self {
status: enums::AttemptStatus::from(item.response.status),
response: Ok(types::PaymentsResponseData::TransactionResponse {
@@ -326,7 +351,7 @@ impl<F, T>
),
redirection_data: None,
mandate_reference: None,
- connector_metadata: None,
+ connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(item.response.txid),
incremental_authorization_allowed: None,
@@ -339,7 +364,7 @@ impl<F, T>
#[derive(Default, Debug, Serialize)]
pub struct ItaubankRefundRequest {
- pub amount: StringMajorUnit,
+ pub valor: StringMajorUnit, // refund_amount
}
impl<F> TryFrom<&ItaubankRouterData<&types::RefundsRouterData<F>>> for ItaubankRefundRequest {
@@ -348,32 +373,34 @@ impl<F> TryFrom<&ItaubankRouterData<&types::RefundsRouterData<F>>> for ItaubankR
item: &ItaubankRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
- amount: item.amount.to_owned(),
+ valor: item.amount.to_owned(),
})
}
}
#[allow(dead_code)]
#[derive(Debug, Serialize, Deserialize, Clone)]
+#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundStatus {
- Succeeded,
- Failed,
- Processing,
+ EmProcessamento, // Processing
+ Devolvido, // Returned
+ NaoRealizado, // Unrealized
}
impl From<RefundStatus> for enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
- RefundStatus::Succeeded => Self::Success,
- RefundStatus::Failed => Self::Failure,
- RefundStatus::Processing => Self::Pending,
+ RefundStatus::Devolvido => Self::Success,
+ RefundStatus::NaoRealizado => Self::Failure,
+ RefundStatus::EmProcessamento => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
- id: String,
+ rtr_id: String,
status: RefundStatus,
}
@@ -386,7 +413,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::Execute, RefundResponse>>
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
+ connector_refund_id: item.response.rtr_id,
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
@@ -403,7 +430,7 @@ impl TryFrom<types::RefundsResponseRouterData<api::RSync, RefundResponse>>
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(types::RefundsResponseData {
- connector_refund_id: item.response.id.to_string(),
+ connector_refund_id: item.response.rtr_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.status),
}),
..item.data
diff --git a/crates/router/src/connector/utils.rs b/crates/router/src/connector/utils.rs
index 8f732e14312..d61d78d37ff 100644
--- a/crates/router/src/connector/utils.rs
+++ b/crates/router/src/connector/utils.rs
@@ -1064,7 +1064,6 @@ impl PaymentsCompleteAuthorizeRequestData for types::CompleteAuthorizeData {
pub trait PaymentsSyncRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError>;
- fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
}
impl PaymentsSyncRequestData for types::PaymentsSyncData {
@@ -1085,11 +1084,6 @@ impl PaymentsSyncRequestData for types::PaymentsSyncData {
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
}
}
- fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
- self.browser_info
- .clone()
- .ok_or_else(missing_field_err("browser_info"))
- }
}
#[cfg(feature = "payouts")]
@@ -1182,6 +1176,7 @@ pub trait RefundsRequestData {
fn get_connector_refund_id(&self) -> Result<String, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
+ fn get_connector_metadata(&self) -> Result<serde_json::Value, Error>;
}
impl RefundsRequestData for types::RefundsData {
@@ -1202,6 +1197,11 @@ impl RefundsRequestData for types::RefundsData {
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
+ fn get_connector_metadata(&self) -> Result<serde_json::Value, Error> {
+ self.connector_metadata
+ .clone()
+ .ok_or_else(missing_field_err("connector_metadata"))
+ }
}
#[cfg(feature = "payouts")]
diff --git a/crates/router/src/core/payments/transformers.rs b/crates/router/src/core/payments/transformers.rs
index f28dd10fc9a..35d72ac6ef1 100644
--- a/crates/router/src/core/payments/transformers.rs
+++ b/crates/router/src/core/payments/transformers.rs
@@ -1445,16 +1445,6 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData
fn try_from(additional_data: PaymentAdditionalData<'_, F>) -> Result<Self, Self::Error> {
let payment_data = additional_data.payment_data;
- let browser_info: Option<types::BrowserInformation> = payment_data
- .payment_attempt
- .browser_info
- .clone()
- .map(|b| b.parse_value("BrowserInformation"))
- .transpose()
- .change_context(errors::ApiErrorResponse::InvalidDataValue {
- field_name: "browser_info",
- })?;
-
let amount = payment_data
.surcharge_details
.as_ref()
@@ -1482,7 +1472,6 @@ impl<F: Clone> TryFrom<PaymentAdditionalData<'_, F>> for types::PaymentsSyncData
payment_method_type: payment_data.payment_attempt.payment_method_type,
currency: payment_data.currency,
payment_experience: payment_data.payment_attempt.payment_experience,
- browser_info,
})
}
}
diff --git a/crates/router/tests/connectors/bambora.rs b/crates/router/tests/connectors/bambora.rs
index a5926d21602..a4cb9b4c5e0 100644
--- a/crates/router/tests/connectors/bambora.rs
+++ b/crates/router/tests/connectors/bambora.rs
@@ -114,7 +114,6 @@ async fn should_sync_authorized_payment() {
payment_experience: None,
integrity_object: None,
amount: MinorUnit::new(100),
- browser_info: None,
}),
None,
)
@@ -234,7 +233,6 @@ async fn should_sync_auto_captured_payment() {
payment_experience: None,
integrity_object: None,
amount: MinorUnit::new(100),
- browser_info: None,
}),
None,
)
diff --git a/crates/router/tests/connectors/forte.rs b/crates/router/tests/connectors/forte.rs
index 2a9926df654..45a30614bfa 100644
--- a/crates/router/tests/connectors/forte.rs
+++ b/crates/router/tests/connectors/forte.rs
@@ -163,7 +163,6 @@ async fn should_sync_authorized_payment() {
payment_experience: None,
integrity_object: None,
amount: MinorUnit::new(100),
- browser_info: None,
}),
get_default_payment_info(),
)
diff --git a/crates/router/tests/connectors/nexinets.rs b/crates/router/tests/connectors/nexinets.rs
index 8623ae48e00..7909aa9c7fc 100644
--- a/crates/router/tests/connectors/nexinets.rs
+++ b/crates/router/tests/connectors/nexinets.rs
@@ -130,7 +130,6 @@ async fn should_sync_authorized_payment() {
payment_experience: None,
integrity_object: None,
amount: MinorUnit::new(100),
- browser_info: None,
}),
None,
)
diff --git a/crates/router/tests/connectors/paypal.rs b/crates/router/tests/connectors/paypal.rs
index d3891729d94..8de891ef09d 100644
--- a/crates/router/tests/connectors/paypal.rs
+++ b/crates/router/tests/connectors/paypal.rs
@@ -147,7 +147,6 @@ async fn should_sync_authorized_payment() {
payment_experience: None,
integrity_object: None,
amount: MinorUnit::new(100),
- browser_info: None,
}),
get_default_payment_info(),
)
@@ -349,7 +348,6 @@ async fn should_sync_auto_captured_payment() {
payment_experience: None,
amount: MinorUnit::new(100),
integrity_object: None,
- browser_info: None,
}),
get_default_payment_info(),
)
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index 612d2863e5d..47e7274c054 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -1003,7 +1003,6 @@ impl Default for PaymentSyncType {
payment_experience: None,
amount: MinorUnit::new(100),
integrity_object: None,
- browser_info: None,
};
Self(data)
}
diff --git a/crates/router/tests/connectors/zen.rs b/crates/router/tests/connectors/zen.rs
index 6e52db34097..2b9ea8f8211 100644
--- a/crates/router/tests/connectors/zen.rs
+++ b/crates/router/tests/connectors/zen.rs
@@ -108,7 +108,6 @@ async fn should_sync_authorized_payment() {
payment_experience: None,
amount: MinorUnit::new(100),
integrity_object: None,
- browser_info: None,
}),
None,
)
@@ -228,7 +227,6 @@ async fn should_sync_auto_captured_payment() {
payment_experience: None,
amount: MinorUnit::new(100),
integrity_object: None,
- browser_info: None,
}),
None,
)
diff --git a/cypress-tests/cypress/e2e/PaymentMethodListTest/00000-PaymentMethodListTests.cy.js b/cypress-tests/cypress/e2e/PaymentMethodListTest/00000-PaymentMethodListTests.cy.js
index 768ad0f7c52..ce0d98c7f62 100644
--- a/cypress-tests/cypress/e2e/PaymentMethodListTest/00000-PaymentMethodListTests.cy.js
+++ b/cypress-tests/cypress/e2e/PaymentMethodListTest/00000-PaymentMethodListTests.cy.js
@@ -84,9 +84,10 @@ describe("Payment Method list using Constraint Graph flow tests", () => {
// payment method list which should only have ideal with stripe
it("payment-method-list-call-test", () => {
- let data = getConnectorDetails("stripe")[
- "pm_list"
- ]["PmListResponse"]["PmListWithStripeForIdeal"];
+ let data =
+ getConnectorDetails("stripe")["pm_list"]["PmListResponse"][
+ "PmListWithStripeForIdeal"
+ ];
cy.paymentMethodListTestLessThanEqualToOnePaymentMethod(
data,
globalState
@@ -164,9 +165,10 @@ describe("Payment Method list using Constraint Graph flow tests", () => {
// payment method list which should only have ideal with stripe
it("payment-method-list-call-test", () => {
- let data = getConnectorDetails("stripe")[
- "pm_list"
- ]["PmListResponse"]["PmListNull"];
+ let data =
+ getConnectorDetails("stripe")["pm_list"]["PmListResponse"][
+ "PmListNull"
+ ];
cy.paymentMethodListTestLessThanEqualToOnePaymentMethod(
data,
globalState
@@ -244,9 +246,10 @@ describe("Payment Method list using Constraint Graph flow tests", () => {
// payment method list which should only have credit with Stripe and Cybersource
it("payment-method-list-call-test", () => {
- let data = getConnectorDetails("stripe")[
- "pm_list"
- ]["PmListResponse"]["PmListWithCreditTwoConnector"];
+ let data =
+ getConnectorDetails("stripe")["pm_list"]["PmListResponse"][
+ "PmListWithCreditTwoConnector"
+ ];
cy.paymentMethodListTestTwoConnectorsForOnePaymentMethodCredit(
data,
globalState
@@ -324,9 +327,10 @@ describe("Payment Method list using Constraint Graph flow tests", () => {
// payment method list which shouldn't have anything
it("payment-method-list-call-test", () => {
- let data = getConnectorDetails("stripe")[
- "pm_list"
- ]["PmListResponse"]["PmListNull"];
+ let data =
+ getConnectorDetails("stripe")["pm_list"]["PmListResponse"][
+ "PmListNull"
+ ];
cy.paymentMethodListTestLessThanEqualToOnePaymentMethod(
data,
globalState
@@ -408,9 +412,10 @@ describe("Payment Method list using Constraint Graph flow tests", () => {
// payment method list which should have credit with stripe and cybersource and no ideal
it("payment-method-list-call-test", () => {
- let data = getConnectorDetails("stripe")[
- "pm_list"
- ]["PmListResponse"]["PmListWithCreditTwoConnector"];
+ let data =
+ getConnectorDetails("stripe")["pm_list"]["PmListResponse"][
+ "PmListWithCreditTwoConnector"
+ ];
cy.paymentMethodListTestTwoConnectorsForOnePaymentMethodCredit(
data,
globalState
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/ItauBank.js b/cypress-tests/cypress/e2e/PaymentUtils/ItauBank.js
index ab66b3f743e..70b6b09eda0 100644
--- a/cypress-tests/cypress/e2e/PaymentUtils/ItauBank.js
+++ b/cypress-tests/cypress/e2e/PaymentUtils/ItauBank.js
@@ -1,68 +1,67 @@
export const connectorDetails = {
- card_pm: {
- ZeroAuthMandate: {
- Response: {
- status: 500,
- body: {
- error: {
- type: "invalid_request",
- message: "setup mandate flow not supported",
- code: "IR_20",
- },
- },
- },
+ card_pm: {
+ ZeroAuthMandate: {
+ Response: {
+ status: 400,
+ body: {
+ error: {
+ type: "invalid_request",
+ message: "setup mandate flow not supported",
+ code: "IR_20",
},
+ },
+ },
},
- bank_transfer_pm: {
- PaymentIntent: {
- Request: {
- currency: "BRL",
- },
- Response: {
- status: 200,
- body: {
- status: "requires_payment_method",
+ },
+ bank_transfer_pm: {
+ PaymentIntent: {
+ Request: {
+ currency: "BRL",
+ },
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_payment_method",
+ },
+ },
+ },
+ Pix: {
+ Request: {
+ payment_method: "bank_transfer",
+ payment_method_type: "pix",
+ payment_method_data: {
+ bank_transfer: {
+ pix: {
+ pix_key: "a1f4102e-a446-4a57-bcce-6fa48899c1d1",
+ cnpj: 74469027417312,
+ cpf: 10599054689,
},
},
},
- Pix: {
- Request: {
- payment_method: "bank_transfer",
- payment_method_type: "pix",
- payment_method_data: {
- bank_transfer: {
- pix: {
- pix_key: "a1f4102e-a446-4a57-bcce-6fa48899c1d1",
- cnpj: 74469027417312,
- cpf: 10599054689
- },
- },
- },
- billing: {
- address: {
- line1: "1467",
- line2: "Harrison Street",
- line3: "Harrison Street",
- city: "San Fransico",
- state: "California",
- zip: "94122",
- country: "BR",
- first_name: "joseph",
- last_name: "Doe",
- },
- phone: {
- number: "9123456789",
- country_code: "+91",
- },
- },
- currency: "BRL",
+ billing: {
+ address: {
+ line1: "1467",
+ line2: "Harrison Street",
+ line3: "Harrison Street",
+ city: "San Fransico",
+ state: "California",
+ zip: "94122",
+ country: "BR",
+ first_name: "joseph",
+ last_name: "Doe",
},
- Response: {
- status: 200,
- body: {
- status: "requires_customer_action",
- },
+ phone: {
+ number: "9123456789",
+ country_code: "+91",
},
},
},
+ Response: {
+ status: 200,
+ body: {
+ status: "requires_customer_action",
+ },
+ },
+ },
+ },
};
diff --git a/cypress-tests/cypress/e2e/PaymentUtils/Utils.js b/cypress-tests/cypress/e2e/PaymentUtils/Utils.js
index a75b95024dc..27e0b2b937e 100644
--- a/cypress-tests/cypress/e2e/PaymentUtils/Utils.js
+++ b/cypress-tests/cypress/e2e/PaymentUtils/Utils.js
@@ -26,7 +26,7 @@ const connectorDetails = {
paypal: paypalConnectorDetails,
stripe: stripeConnectorDetails,
trustpay: trustpayConnectorDetails,
- datatrans:datatransConnectorDetails
+ datatrans: datatransConnectorDetails,
};
export default function getConnectorDetails(connectorId) {
diff --git a/cypress-tests/cypress/support/commands.js b/cypress-tests/cypress/support/commands.js
index 5901ba339ea..ccf0ceeddee 100644
--- a/cypress-tests/cypress/support/commands.js
+++ b/cypress-tests/cypress/support/commands.js
@@ -337,7 +337,9 @@ Cypress.Commands.add(
.sort();
}
let config_payment_method_type = getPaymentMethodType(res_data);
- let response_payment_method_type = getPaymentMethodType(response.body);
+ let response_payment_method_type = getPaymentMethodType(
+ response.body
+ );
for (let i = 0; i < response_payment_method_type.length; i++) {
expect(config_payment_method_type[i]).to.equal(
response_payment_method_type[i]
@@ -671,20 +673,13 @@ Cypress.Commands.add(
"nextActionUrl", // This is intentionally kept as nextActionUrl to avoid issues during handleRedirection call,
response.body.next_action.qr_code_url
);
- globalState.set(
- "nextActionType",
- "qr_code_url"
- );
- }
- else{
+ globalState.set("nextActionType", "qr_code_url");
+ } else {
globalState.set(
"nextActionUrl", // This is intentionally kept as nextActionUrl to avoid issues during handleRedirection call,
response.body.next_action.image_data_url
);
- globalState.set(
- "nextActionType",
- "image_data_url"
- );
+ globalState.set("nextActionType", "image_data_url");
}
break;
default:
@@ -1343,7 +1338,7 @@ Cypress.Commands.add(
let connectorId = globalState.get("connectorId");
let expected_url = new URL(expected_redirection);
let redirection_url = new URL(globalState.get("nextActionUrl"));
- let next_action_type = globalState.get("nextActionType")
+ let next_action_type = globalState.get("nextActionType");
cy.log(payment_method_type);
handleRedirection(
"bank_transfer",
diff --git a/cypress-tests/cypress/support/redirectionHandler.js b/cypress-tests/cypress/support/redirectionHandler.js
index 278d20b2758..f0998a44fc3 100644
--- a/cypress-tests/cypress/support/redirectionHandler.js
+++ b/cypress-tests/cypress/support/redirectionHandler.js
@@ -74,15 +74,14 @@ function bankTransferRedirection(
verifyReturnUrl(redirection_url, expected_url, true);
}
});
- break;
+ break;
case "image_data_url":
switch (connectorId) {
- case "itaubank":
+ case "itaubank":
switch (payment_method_type) {
case "pix":
fetchAndParseImageData(redirection_url).then((qrCodeData) => {
- console.log("Imaage_data>>>>>>>>>", qrCodeData)
- expect(qrCodeData).to.contains('itau.com.br/pix/qr/v2') // image data contains the following value
+ expect(qrCodeData).to.contains("itau.com.br/pix/qr/v2"); // image data contains the following value
});
break;
default:
@@ -96,7 +95,6 @@ function bankTransferRedirection(
default:
verifyReturnUrl(redirection_url, expected_url, true);
}
-
}
function bankRedirectRedirection(
diff --git a/cypress-tests/package.json b/cypress-tests/package.json
index 2eb58696d89..3f6647ee8ba 100644
--- a/cypress-tests/package.json
+++ b/cypress-tests/package.json
@@ -7,9 +7,9 @@
"cypress": "npx cypress open",
"cypress-e2e": "npx cypress run --e2e",
"cypress:ci": "npx cypress run --headless",
- "cypress:payments": "cypress run --spec 'cypress/e2e/PaymentTest/**/*'",
- "cypress:payouts": "cypress run --spec 'cypress/e2e/PayoutTest/**/*'",
- "cypress:routing": "cypress run --spec 'cypress/e2e/RoutingTest/**/*'"
+ "cypress:payments": "cypress run --headless --spec 'cypress/e2e/PaymentTest/**/*'",
+ "cypress:payouts": "cypress run --headless --spec 'cypress/e2e/PayoutTest/**/*'",
+ "cypress:routing": "cypress run --headless --spec 'cypress/e2e/RoutingTest/**/*'"
},
"author": "",
"license": "ISC",
|
feat
|
[Itaubank] Add refund and rsync flow (#5420)
|
b279591057cdba6004c99efc82bb856f0bacd1e0
|
2023-12-08 17:58:42
|
Chethan Rao
|
refactor(payment_methods): make the card_holder_name optional for card details in the payment APIs (#3074)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 93c97cbd443..b19f4d7b7db 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -682,7 +682,7 @@ pub struct Card {
/// The card holder's name
#[schema(value_type = String, example = "John Test")]
- pub card_holder_name: Secret<String>,
+ pub card_holder_name: Option<Secret<String>>,
/// The CVC number for the card
#[schema(value_type = String, example = "242")]
diff --git a/crates/router/src/compatibility/stripe/payment_intents/types.rs b/crates/router/src/compatibility/stripe/payment_intents/types.rs
index 3c7d5f2918f..38007a3110d 100644
--- a/crates/router/src/compatibility/stripe/payment_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/payment_intents/types.rs
@@ -118,7 +118,7 @@ impl From<StripeCard> for payments::Card {
card_number: card.number,
card_exp_month: card.exp_month,
card_exp_year: card.exp_year,
- card_holder_name: card.holder_name.unwrap_or("name".to_string().into()),
+ card_holder_name: card.holder_name,
card_cvc: card.cvc,
card_issuer: None,
card_network: None,
diff --git a/crates/router/src/compatibility/stripe/setup_intents/types.rs b/crates/router/src/compatibility/stripe/setup_intents/types.rs
index 9d3f74af8cb..4c99d0cb00b 100644
--- a/crates/router/src/compatibility/stripe/setup_intents/types.rs
+++ b/crates/router/src/compatibility/stripe/setup_intents/types.rs
@@ -95,7 +95,7 @@ impl From<StripeCard> for payments::Card {
card_number: card.number,
card_exp_month: card.exp_month,
card_exp_year: card.exp_year,
- card_holder_name: masking::Secret::new("stripe_cust".to_owned()),
+ card_holder_name: Some(masking::Secret::new("stripe_cust".to_owned())),
card_cvc: card.cvc,
card_issuer: None,
card_network: None,
diff --git a/crates/router/src/connector/aci/transformers.rs b/crates/router/src/connector/aci/transformers.rs
index 9cfb657bdca..53639f268c8 100644
--- a/crates/router/src/connector/aci/transformers.rs
+++ b/crates/router/src/connector/aci/transformers.rs
@@ -254,7 +254,9 @@ impl TryFrom<api_models::payments::Card> for PaymentDetails {
fn try_from(card_data: api_models::payments::Card) -> Result<Self, Self::Error> {
Ok(Self::AciCard(Box::new(CardDetails {
card_number: card_data.card_number,
- card_holder: card_data.card_holder_name,
+ card_holder: card_data
+ .card_holder_name
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?,
card_expiry_month: card_data.card_exp_month,
card_expiry_year: card_data.card_exp_year,
card_cvv: card_data.card_cvc,
diff --git a/crates/router/src/connector/bambora/transformers.rs b/crates/router/src/connector/bambora/transformers.rs
index 2d50569f9a4..4729bfa5a6e 100644
--- a/crates/router/src/connector/bambora/transformers.rs
+++ b/crates/router/src/connector/bambora/transformers.rs
@@ -5,7 +5,7 @@ use masking::{PeekInterface, Secret};
use serde::{Deserialize, Deserializer, Serialize};
use crate::{
- connector::utils::{BrowserInformationData, PaymentsAuthorizeRequestData},
+ connector::utils::{self, BrowserInformationData, PaymentsAuthorizeRequestData},
consts,
core::errors,
services,
@@ -117,7 +117,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for BamboraPaymentsRequest {
enums::AuthenticationType::NoThreeDs => None,
};
let bambora_card = BamboraCard {
- name: req_card.card_holder_name,
+ name: req_card
+ .card_holder_name
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?,
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
expiry_year: req_card.card_exp_year,
diff --git a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
index f6c1bfc46b0..d1201309637 100644
--- a/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
+++ b/crates/router/src/connector/braintree/braintree_graphql_transformers.rs
@@ -867,7 +867,9 @@ impl TryFrom<&types::TokenizationRouterData> for BraintreeTokenRequest {
expiration_year: card_data.card_exp_year,
expiration_month: card_data.card_exp_month,
cvv: card_data.card_cvc,
- cardholder_name: card_data.card_holder_name,
+ cardholder_name: card_data
+ .card_holder_name
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?,
},
};
Ok(Self {
diff --git a/crates/router/src/connector/dlocal/transformers.rs b/crates/router/src/connector/dlocal/transformers.rs
index 92d01cfe56d..25462c758f1 100644
--- a/crates/router/src/connector/dlocal/transformers.rs
+++ b/crates/router/src/connector/dlocal/transformers.rs
@@ -6,7 +6,7 @@ use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
- connector::utils::{AddressDetailsData, PaymentsAuthorizeRequestData, RouterData},
+ connector::utils::{self, AddressDetailsData, PaymentsAuthorizeRequestData, RouterData},
core::errors,
services,
types::{self, api, storage::enums},
@@ -125,7 +125,10 @@ impl TryFrom<&DlocalRouterData<&types::PaymentsAuthorizeRouterData>> for DlocalP
document: get_doc_from_currency(country.to_string()),
},
card: Some(Card {
- holder_name: ccard.card_holder_name.clone(),
+ holder_name: ccard
+ .card_holder_name
+ .clone()
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?,
number: ccard.card_number.clone(),
cvv: ccard.card_cvc.clone(),
expiration_month: ccard.card_exp_month.clone(),
diff --git a/crates/router/src/connector/dummyconnector/transformers.rs b/crates/router/src/connector/dummyconnector/transformers.rs
index 3c7bd2e09d9..bbb3b10c8e0 100644
--- a/crates/router/src/connector/dummyconnector/transformers.rs
+++ b/crates/router/src/connector/dummyconnector/transformers.rs
@@ -4,6 +4,7 @@ use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
+ connector::utils,
core::errors,
services,
types::{self, api, storage::enums},
@@ -83,15 +84,18 @@ pub struct DummyConnectorCard {
cvc: Secret<String>,
}
-impl From<api_models::payments::Card> for DummyConnectorCard {
- fn from(value: api_models::payments::Card) -> Self {
- Self {
- name: value.card_holder_name,
+impl TryFrom<api_models::payments::Card> for DummyConnectorCard {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(value: api_models::payments::Card) -> Result<Self, Self::Error> {
+ Ok(Self {
+ name: value
+ .card_holder_name
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?,
number: value.card_number,
expiry_month: value.card_exp_month,
expiry_year: value.card_exp_year,
cvc: value.card_cvc,
- }
+ })
}
}
@@ -151,7 +155,7 @@ impl<const T: u8> TryFrom<&types::PaymentsAuthorizeRouterData>
.payment_method_data
{
api::PaymentMethodData::Card(ref req_card) => {
- Ok(PaymentMethodData::Card(req_card.clone().into()))
+ Ok(PaymentMethodData::Card(req_card.clone().try_into()?))
}
api::PaymentMethodData::Wallet(ref wallet_data) => {
Ok(PaymentMethodData::Wallet(wallet_data.clone().try_into()?))
diff --git a/crates/router/src/connector/forte/transformers.rs b/crates/router/src/connector/forte/transformers.rs
index 4bb354f6cda..411457fab67 100644
--- a/crates/router/src/connector/forte/transformers.rs
+++ b/crates/router/src/connector/forte/transformers.rs
@@ -82,7 +82,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for FortePaymentsRequest {
let address = item.get_billing_address()?;
let card = Card {
card_type,
- name_on_card: ccard.card_holder_name.clone(),
+ name_on_card: ccard
+ .card_holder_name
+ .clone()
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?,
account_number: ccard.card_number.clone(),
expire_month: ccard.card_exp_month.clone(),
expire_year: ccard.card_exp_year.clone(),
diff --git a/crates/router/src/connector/mollie/transformers.rs b/crates/router/src/connector/mollie/transformers.rs
index 62fb94e236a..c1151adcf6d 100644
--- a/crates/router/src/connector/mollie/transformers.rs
+++ b/crates/router/src/connector/mollie/transformers.rs
@@ -286,7 +286,10 @@ impl TryFrom<&types::TokenizationRouterData> for MollieCardTokenRequest {
match item.request.payment_method_data.clone() {
api_models::payments::PaymentMethodData::Card(ccard) => {
let auth = MollieAuthType::try_from(&item.connector_auth_type)?;
- let card_holder = ccard.card_holder_name.clone();
+ let card_holder = ccard
+ .card_holder_name
+ .clone()
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?;
let card_number = ccard.card_number.clone();
let card_expiry_date =
ccard.get_card_expiry_month_year_2_digit_with_delimiter("/".to_owned());
diff --git a/crates/router/src/connector/noon/transformers.rs b/crates/router/src/connector/noon/transformers.rs
index b478d63e0f1..e2262e7b895 100644
--- a/crates/router/src/connector/noon/transformers.rs
+++ b/crates/router/src/connector/noon/transformers.rs
@@ -200,7 +200,10 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for NoonPaymentsRequest {
_ => (
match item.request.payment_method_data.clone() {
api::PaymentMethodData::Card(req_card) => Ok(NoonPaymentData::Card(NoonCard {
- name_on_card: req_card.card_holder_name.clone(),
+ name_on_card: req_card
+ .card_holder_name
+ .clone()
+ .ok_or_else(conn_utils::missing_field_err("card_holder_name"))?,
number_plain: req_card.card_number.clone(),
expiry_month: req_card.card_exp_month.clone(),
expiry_year: req_card.get_expiry_year_4_digit(),
diff --git a/crates/router/src/connector/nuvei/transformers.rs b/crates/router/src/connector/nuvei/transformers.rs
index 73e039c6339..4ed6b25b136 100644
--- a/crates/router/src/connector/nuvei/transformers.rs
+++ b/crates/router/src/connector/nuvei/transformers.rs
@@ -1000,7 +1000,7 @@ impl From<NuveiCardDetails> for PaymentOption {
Self {
card: Some(Card {
card_number: Some(card.card_number),
- card_holder_name: Some(card.card_holder_name),
+ card_holder_name: card.card_holder_name,
expiration_month: Some(card.card_exp_month),
expiration_year: Some(card.card_exp_year),
three_d: card_details.three_d,
diff --git a/crates/router/src/connector/opayo/transformers.rs b/crates/router/src/connector/opayo/transformers.rs
index 7b633f6aa64..a0e3877f82b 100644
--- a/crates/router/src/connector/opayo/transformers.rs
+++ b/crates/router/src/connector/opayo/transformers.rs
@@ -29,7 +29,9 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for OpayoPaymentsRequest {
match item.request.payment_method_data.clone() {
api::PaymentMethodData::Card(req_card) => {
let card = OpayoCard {
- name: req_card.card_holder_name,
+ name: req_card
+ .card_holder_name
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?,
number: req_card.card_number,
expiry_month: req_card.card_exp_month,
expiry_year: req_card.card_exp_year,
diff --git a/crates/router/src/connector/payeezy/transformers.rs b/crates/router/src/connector/payeezy/transformers.rs
index 0170d18ecb4..8b4f4a46959 100644
--- a/crates/router/src/connector/payeezy/transformers.rs
+++ b/crates/router/src/connector/payeezy/transformers.rs
@@ -241,7 +241,10 @@ fn get_payment_method_data(
let card_type = PayeezyCardType::try_from(card.get_card_issuer()?)?;
let payeezy_card = PayeezyCard {
card_type,
- cardholder_name: card.card_holder_name.clone(),
+ cardholder_name: card
+ .card_holder_name
+ .clone()
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?,
card_number: card.card_number.clone(),
exp_date: card.get_card_expiry_month_year_2_digit_with_delimiter("".to_string()),
cvv: card.card_cvc.clone(),
diff --git a/crates/router/src/connector/paypal/transformers.rs b/crates/router/src/connector/paypal/transformers.rs
index 8b6a2297d09..0871bc5097a 100644
--- a/crates/router/src/connector/paypal/transformers.rs
+++ b/crates/router/src/connector/paypal/transformers.rs
@@ -443,7 +443,10 @@ impl TryFrom<&PaypalRouterData<&types::PaymentsAuthorizeRouterData>> for PaypalP
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(),
+ name: ccard
+ .card_holder_name
+ .clone()
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?,
number: Some(ccard.card_number.clone()),
security_code: Some(ccard.card_cvc.clone()),
attributes,
diff --git a/crates/router/src/connector/powertranz/transformers.rs b/crates/router/src/connector/powertranz/transformers.rs
index e0ecd81c7e5..6d5a756c571 100644
--- a/crates/router/src/connector/powertranz/transformers.rs
+++ b/crates/router/src/connector/powertranz/transformers.rs
@@ -101,7 +101,7 @@ impl TryFrom<&types::PaymentsAuthorizeRouterData> for PowertranzPaymentsRequest
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsAuthorizeRouterData) -> Result<Self, Self::Error> {
let source = match item.request.payment_method_data.clone() {
- api::PaymentMethodData::Card(card) => Ok(Source::from(&card)),
+ api::PaymentMethodData::Card(card) => Source::try_from(&card),
api::PaymentMethodData::Wallet(_)
| api::PaymentMethodData::CardRedirect(_)
| api::PaymentMethodData::PayLater(_)
@@ -211,15 +211,19 @@ impl TryFrom<&types::BrowserInformation> for BrowserInfo {
})
}*/
-impl From<&Card> for Source {
- fn from(card: &Card) -> Self {
+impl TryFrom<&Card> for Source {
+ type Error = error_stack::Report<errors::ConnectorError>;
+ fn try_from(card: &Card) -> Result<Self, Self::Error> {
let card = PowertranzCard {
- cardholder_name: card.card_holder_name.clone(),
+ cardholder_name: card
+ .card_holder_name
+ .clone()
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?,
card_pan: card.card_number.clone(),
card_expiration: card.get_expiry_date_as_yymm(),
card_cvv: card.card_cvc.clone(),
};
- Self::Card(card)
+ Ok(Self::Card(card))
}
}
diff --git a/crates/router/src/connector/rapyd/transformers.rs b/crates/router/src/connector/rapyd/transformers.rs
index 193eb819892..aab47bc8b21 100644
--- a/crates/router/src/connector/rapyd/transformers.rs
+++ b/crates/router/src/connector/rapyd/transformers.rs
@@ -4,7 +4,7 @@ use time::PrimitiveDateTime;
use url::Url;
use crate::{
- connector::utils::PaymentsAuthorizeRequestData,
+ connector::utils::{self, PaymentsAuthorizeRequestData},
consts,
core::errors,
pii::Secret,
@@ -131,7 +131,10 @@ impl TryFrom<&RapydRouterData<&types::PaymentsAuthorizeRouterData>> for RapydPay
number: ccard.card_number.to_owned(),
expiration_month: ccard.card_exp_month.to_owned(),
expiration_year: ccard.card_exp_year.to_owned(),
- name: ccard.card_holder_name.to_owned(),
+ name: ccard
+ .card_holder_name
+ .to_owned()
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?,
cvv: ccard.card_cvc.to_owned(),
}),
address: None,
diff --git a/crates/router/src/connector/shift4/transformers.rs b/crates/router/src/connector/shift4/transformers.rs
index ce68aad25c5..2b89e7ebf6c 100644
--- a/crates/router/src/connector/shift4/transformers.rs
+++ b/crates/router/src/connector/shift4/transformers.rs
@@ -296,7 +296,10 @@ impl<T>
number: card.card_number.clone(),
exp_month: card.card_exp_month.clone(),
exp_year: card.card_exp_year.clone(),
- cardholder_name: card.card_holder_name.clone(),
+ cardholder_name: card
+ .card_holder_name
+ .clone()
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?,
};
if item.is_three_ds() {
Ok(Self::Cards3DSRequest(Box::new(Cards3DSRequest {
diff --git a/crates/router/src/connector/stax/transformers.rs b/crates/router/src/connector/stax/transformers.rs
index 2fd3b3474ea..7395172239e 100644
--- a/crates/router/src/connector/stax/transformers.rs
+++ b/crates/router/src/connector/stax/transformers.rs
@@ -226,7 +226,9 @@ impl TryFrom<&types::TokenizationRouterData> for StaxTokenRequest {
let stax_card_data = StaxTokenizeData {
card_exp: card_data
.get_card_expiry_month_year_2_digit_with_delimiter("".to_string()),
- person_name: card_data.card_holder_name,
+ person_name: card_data
+ .card_holder_name
+ .ok_or_else(missing_field_err("card_holder_name"))?,
card_number: card_data.card_number,
card_cvv: card_data.card_cvc,
customer_id: Secret::new(customer_id),
diff --git a/crates/router/src/connector/worldline/transformers.rs b/crates/router/src/connector/worldline/transformers.rs
index b5739fe857a..d9e9d1ff7c0 100644
--- a/crates/router/src/connector/worldline/transformers.rs
+++ b/crates/router/src/connector/worldline/transformers.rs
@@ -351,7 +351,10 @@ fn make_card_request(
let expiry_date: Secret<String> = Secret::new(secret_value);
let card = Card {
card_number: ccard.card_number.clone(),
- cardholder_name: ccard.card_holder_name.clone(),
+ cardholder_name: ccard
+ .card_holder_name
+ .clone()
+ .ok_or_else(utils::missing_field_err("card_holder_name"))?,
cvv: ccard.card_cvc.clone(),
expiry_date,
};
diff --git a/crates/router/src/core/payment_methods/vault.rs b/crates/router/src/core/payment_methods/vault.rs
index 5ad78c9d730..c71632c9b06 100644
--- a/crates/router/src/core/payment_methods/vault.rs
+++ b/crates/router/src/core/payment_methods/vault.rs
@@ -51,7 +51,10 @@ impl Vaultable for api::Card {
card_number: self.card_number.peek().clone(),
exp_year: self.card_exp_year.peek().clone(),
exp_month: self.card_exp_month.peek().clone(),
- name_on_card: Some(self.card_holder_name.peek().clone()),
+ name_on_card: self
+ .card_holder_name
+ .clone()
+ .map(|name| name.peek().clone()),
nickname: None,
card_last_four: None,
card_token: None,
@@ -99,7 +102,7 @@ impl Vaultable for api::Card {
.attach_printable("Invalid card number format from the mock locker")?,
card_exp_month: value1.exp_month.into(),
card_exp_year: value1.exp_year.into(),
- card_holder_name: value1.name_on_card.unwrap_or_default().into(),
+ card_holder_name: value1.name_on_card.map(masking::Secret::new),
card_cvc: value2.card_security_code.unwrap_or_default().into(),
card_issuer: None,
card_network: None,
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 4e491964e96..866a0581e4e 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -946,6 +946,42 @@ pub fn verify_mandate_details(
)
}
+// This function validates card_holder_name field to be either null or a non-empty string
+pub fn validate_card_holder_name(
+ payment_method_data: Option<api::PaymentMethodData>,
+) -> CustomResult<(), errors::ApiErrorResponse> {
+ if let Some(pmd) = payment_method_data {
+ match pmd {
+ // This validation would occur during payments create
+ api::PaymentMethodData::Card(card) => {
+ if let Some(name) = &card.card_holder_name {
+ if name.clone().expose().is_empty() {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "card_holder_name cannot be empty".to_string(),
+ })
+ .into_report();
+ }
+ }
+ }
+
+ // This validation would occur during payments confirm
+ api::PaymentMethodData::CardToken(card) => {
+ if let Some(name) = card.card_holder_name {
+ if name.expose().is_empty() {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "card_holder_name cannot be empty".to_string(),
+ })
+ .into_report();
+ }
+ }
+ }
+ _ => (),
+ }
+ }
+
+ Ok(())
+}
+
#[instrument(skip_all)]
pub fn payment_attempt_status_fsm(
payment_method_data: &Option<api::PaymentMethodData>,
@@ -1033,7 +1069,7 @@ pub(crate) async fn get_payment_method_create_request(
card_number: card.card_number.clone(),
card_exp_month: card.card_exp_month.clone(),
card_exp_year: card.card_exp_year.clone(),
- card_holder_name: Some(card.card_holder_name.clone()),
+ card_holder_name: card.card_holder_name.clone(),
nick_name: card.nick_name.clone(),
};
let customer_id = customer.customer_id.clone();
@@ -1404,21 +1440,25 @@ pub async fn retrieve_payment_method_with_temporary_token(
let mut updated_card = card.clone();
let mut is_card_updated = false;
- let name_on_card = if card.card_holder_name.clone().expose().is_empty() {
- card_token_data
- .and_then(|token_data| token_data.card_holder_name.clone())
- .filter(|name_on_card| !name_on_card.clone().expose().is_empty())
- .map(|name_on_card| {
+ // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
+ // from payment_method.card_token object
+ let name_on_card = if let Some(name) = card.card_holder_name.clone() {
+ if name.expose().is_empty() {
+ card_token_data.and_then(|token_data| {
is_card_updated = true;
- name_on_card
+ token_data.card_holder_name.clone()
})
+ } else {
+ card.card_holder_name.clone()
+ }
} else {
- Some(card.card_holder_name.clone())
+ card_token_data.and_then(|token_data| {
+ is_card_updated = true;
+ token_data.card_holder_name.clone()
+ })
};
- if let Some(name_on_card) = name_on_card {
- updated_card.card_holder_name = name_on_card;
- }
+ updated_card.card_holder_name = name_on_card;
if let Some(token_data) = card_token_data {
if let Some(cvc) = token_data.card_cvc.clone() {
@@ -1487,23 +1527,21 @@ pub async fn retrieve_card_with_permanent_token(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card information from the permanent locker")?;
- let name_on_card = if let Some(name_on_card) = card.name_on_card.clone() {
- if card.name_on_card.unwrap_or_default().expose().is_empty() {
- card_token_data
- .and_then(|token_data| token_data.card_holder_name.clone())
- .filter(|name_on_card| !name_on_card.clone().expose().is_empty())
+ // The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
+ // from payment_method.card_token object
+ let name_on_card = if let Some(name) = card.name_on_card.clone() {
+ if name.expose().is_empty() {
+ card_token_data.and_then(|token_data| token_data.card_holder_name.clone())
} else {
- Some(name_on_card)
+ card.name_on_card
}
} else {
- card_token_data
- .and_then(|token_data| token_data.card_holder_name.clone())
- .filter(|name_on_card| !name_on_card.clone().expose().is_empty())
+ card_token_data.and_then(|token_data| token_data.card_holder_name.clone())
};
let api_card = api::Card {
card_number: card.card_number,
- card_holder_name: name_on_card.unwrap_or(masking::Secret::from("".to_string())),
+ card_holder_name: name_on_card,
card_exp_month: card.card_exp_month,
card_exp_year: card.card_exp_year,
card_cvc: card_token_data
@@ -3324,7 +3362,7 @@ pub async fn get_additional_payment_data(
bank_code: card_data.bank_code.to_owned(),
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
- card_holder_name: Some(card_data.card_holder_name.clone()),
+ card_holder_name: card_data.card_holder_name.clone(),
last4: last4.clone(),
card_isin: card_isin.clone(),
},
@@ -3352,7 +3390,7 @@ pub async fn get_additional_payment_data(
card_isin: card_isin.clone(),
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
- card_holder_name: Some(card_data.card_holder_name.clone()),
+ card_holder_name: card_data.card_holder_name.clone(),
},
))
});
@@ -3367,7 +3405,7 @@ pub async fn get_additional_payment_data(
card_isin,
card_exp_month: Some(card_data.card_exp_month.clone()),
card_exp_year: Some(card_data.card_exp_year.clone()),
- card_holder_name: Some(card_data.card_holder_name.clone()),
+ card_holder_name: card_data.card_holder_name.clone(),
},
)))
}
diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rs
index af2a9fa49c8..612ddadc1c5 100644
--- a/crates/router/src/core/payments/operations/payment_confirm.rs
+++ b/crates/router/src/core/payments/operations/payment_confirm.rs
@@ -871,6 +871,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
helpers::validate_payment_method_fields_present(request)?;
+ helpers::validate_card_holder_name(request.payment_method_data.clone())?;
+
let mandate_type =
helpers::validate_mandate(request, payments::is_operation_confirm(self))?;
diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rs
index eb7f31ba24d..cbce6ba9e97 100644
--- a/crates/router/src/core/payments/operations/payment_create.rs
+++ b/crates/router/src/core/payments/operations/payment_create.rs
@@ -560,6 +560,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
helpers::validate_amount_to_capture_and_capture_method(None, request)?;
helpers::validate_card_data(request.payment_method_data.clone())?;
+ helpers::validate_card_holder_name(request.payment_method_data.clone())?;
+
helpers::validate_payment_method_fields_present(request)?;
let mandate_type =
diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rs
index f1a35cffce8..84f11124c73 100644
--- a/crates/router/src/core/payments/operations/payment_update.rs
+++ b/crates/router/src/core/payments/operations/payment_update.rs
@@ -655,6 +655,8 @@ impl<F: Send + Clone, Ctx: PaymentMethodRetrieve> ValidateRequest<F, api::Paymen
helpers::validate_payment_method_fields_present(request)?;
+ helpers::validate_card_holder_name(request.payment_method_data.clone())?;
+
let mandate_type = helpers::validate_mandate(request, false)?;
Ok((
diff --git a/crates/router/src/types/api/payments.rs b/crates/router/src/types/api/payments.rs
index 2acf42fa479..9159abf4bd1 100644
--- a/crates/router/src/types/api/payments.rs
+++ b/crates/router/src/types/api/payments.rs
@@ -244,7 +244,7 @@ mod payments_test {
card_number: "1234432112344321".to_string().try_into().unwrap(),
card_exp_month: "12".to_string().into(),
card_exp_year: "99".to_string().into(),
- card_holder_name: "JohnDoe".to_string().into(),
+ card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())),
card_cvc: "123".to_string().into(),
card_issuer: Some("HDFC".to_string()),
card_network: Some(api_models::enums::CardNetwork::Visa),
diff --git a/crates/router/src/utils/verify_connector.rs b/crates/router/src/utils/verify_connector.rs
index 6ad683d63ba..060f92d0e5a 100644
--- a/crates/router/src/utils/verify_connector.rs
+++ b/crates/router/src/utils/verify_connector.rs
@@ -20,7 +20,7 @@ pub fn generate_card_from_details(
card_network: None,
card_exp_year: masking::Secret::new(card_exp_year),
card_exp_month: masking::Secret::new(card_exp_month),
- card_holder_name: masking::Secret::new("HyperSwitch".to_string()),
+ card_holder_name: Some(masking::Secret::new("HyperSwitch".to_string())),
nick_name: None,
card_type: None,
card_issuing_country: None,
diff --git a/crates/router/tests/connectors/aci.rs b/crates/router/tests/connectors/aci.rs
index 7ddc504956f..dd8c1ed5f77 100644
--- a/crates/router/tests/connectors/aci.rs
+++ b/crates/router/tests/connectors/aci.rs
@@ -38,7 +38,7 @@ fn construct_payment_router_data() -> types::PaymentsAuthorizeRouterData {
card_number: cards::CardNumber::from_str("4200000000000000").unwrap(),
card_exp_month: Secret::new("10".to_string()),
card_exp_year: Secret::new("2025".to_string()),
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
card_cvc: Secret::new("999".to_string()),
card_issuer: None,
card_network: None,
@@ -232,7 +232,7 @@ async fn payments_create_failure() {
card_number: cards::CardNumber::from_str("4200000000000000").unwrap(),
card_exp_month: Secret::new("10".to_string()),
card_exp_year: Secret::new("2025".to_string()),
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
card_cvc: Secret::new("99".to_string()),
card_issuer: None,
card_network: None,
diff --git a/crates/router/tests/connectors/adyen.rs b/crates/router/tests/connectors/adyen.rs
index 714dc0d7d67..14177e6fb50 100644
--- a/crates/router/tests/connectors/adyen.rs
+++ b/crates/router/tests/connectors/adyen.rs
@@ -126,7 +126,7 @@ impl AdyenTest {
card_number: cards::CardNumber::from_str(card_number).unwrap(),
card_exp_month: Secret::new(card_exp_month.to_string()),
card_exp_year: Secret::new(card_exp_year.to_string()),
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
card_cvc: Secret::new(card_cvc.to_string()),
card_issuer: None,
card_network: None,
diff --git a/crates/router/tests/connectors/airwallex.rs b/crates/router/tests/connectors/airwallex.rs
index 6e7f6c000d2..cfc4c0c003d 100644
--- a/crates/router/tests/connectors/airwallex.rs
+++ b/crates/router/tests/connectors/airwallex.rs
@@ -60,7 +60,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
card_number: cards::CardNumber::from_str("4035501000000008").unwrap(),
card_exp_month: Secret::new("02".to_string()),
card_exp_year: Secret::new("2035".to_string()),
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
card_cvc: Secret::new("123".to_string()),
card_issuer: None,
card_network: None,
diff --git a/crates/router/tests/connectors/authorizedotnet.rs b/crates/router/tests/connectors/authorizedotnet.rs
index 4021d57d543..3ae4298e836 100644
--- a/crates/router/tests/connectors/authorizedotnet.rs
+++ b/crates/router/tests/connectors/authorizedotnet.rs
@@ -42,7 +42,7 @@ fn get_payment_method_data() -> api::Card {
card_number: cards::CardNumber::from_str("5424000000000015").unwrap(),
card_exp_month: Secret::new("02".to_string()),
card_exp_year: Secret::new("2035".to_string()),
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
card_cvc: Secret::new("123".to_string()),
..Default::default()
}
diff --git a/crates/router/tests/connectors/bluesnap.rs b/crates/router/tests/connectors/bluesnap.rs
index 30052d11da4..852b23f022c 100644
--- a/crates/router/tests/connectors/bluesnap.rs
+++ b/crates/router/tests/connectors/bluesnap.rs
@@ -400,7 +400,7 @@ async fn should_fail_payment_for_incorrect_cvc() {
Some(types::PaymentsAuthorizeData {
email: Some(Email::from_str("[email protected]").unwrap()),
payment_method_data: types::api::PaymentMethodData::Card(api::Card {
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
@@ -426,7 +426,7 @@ async fn should_fail_payment_for_invalid_exp_month() {
Some(types::PaymentsAuthorizeData {
email: Some(Email::from_str("[email protected]").unwrap()),
payment_method_data: types::api::PaymentMethodData::Card(api::Card {
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
@@ -452,7 +452,7 @@ async fn should_fail_payment_for_incorrect_expiry_year() {
Some(types::PaymentsAuthorizeData {
email: Some(Email::from_str("[email protected]").unwrap()),
payment_method_data: types::api::PaymentMethodData::Card(api::Card {
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
diff --git a/crates/router/tests/connectors/fiserv.rs b/crates/router/tests/connectors/fiserv.rs
index 1394667718c..36d5f66dbcc 100644
--- a/crates/router/tests/connectors/fiserv.rs
+++ b/crates/router/tests/connectors/fiserv.rs
@@ -46,7 +46,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
card_number: cards::CardNumber::from_str("4005550000000019").unwrap(),
card_exp_month: Secret::new("02".to_string()),
card_exp_year: Secret::new("2035".to_string()),
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
card_cvc: Secret::new("123".to_string()),
card_issuer: None,
card_network: None,
diff --git a/crates/router/tests/connectors/payme.rs b/crates/router/tests/connectors/payme.rs
index 5550ba12af8..7de81a8bed2 100644
--- a/crates/router/tests/connectors/payme.rs
+++ b/crates/router/tests/connectors/payme.rs
@@ -87,7 +87,7 @@ fn payment_method_details() -> Option<types::PaymentsAuthorizeData> {
card_cvc: Secret::new("123".to_string()),
card_exp_month: Secret::new("10".to_string()),
card_exp_year: Secret::new("2025".to_string()),
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
..utils::CCardType::default().0
}),
amount: 1000,
diff --git a/crates/router/tests/connectors/rapyd.rs b/crates/router/tests/connectors/rapyd.rs
index 143f87fc575..c53f4e8d8b1 100644
--- a/crates/router/tests/connectors/rapyd.rs
+++ b/crates/router/tests/connectors/rapyd.rs
@@ -46,7 +46,7 @@ async fn should_only_authorize_payment() {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
card_exp_month: Secret::new("02".to_string()),
card_exp_year: Secret::new("2024".to_string()),
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
card_cvc: Secret::new("123".to_string()),
card_issuer: None,
card_network: None,
@@ -74,7 +74,7 @@ async fn should_authorize_and_capture_payment() {
card_number: cards::CardNumber::from_str("4111111111111111").unwrap(),
card_exp_month: Secret::new("02".to_string()),
card_exp_year: Secret::new("2024".to_string()),
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
card_cvc: Secret::new("123".to_string()),
card_issuer: None,
card_network: None,
diff --git a/crates/router/tests/connectors/utils.rs b/crates/router/tests/connectors/utils.rs
index 7e5cfeb4397..d3b20b01e4c 100644
--- a/crates/router/tests/connectors/utils.rs
+++ b/crates/router/tests/connectors/utils.rs
@@ -869,7 +869,7 @@ impl Default for CCardType {
card_number: cards::CardNumber::from_str("4200000000000000").unwrap(),
card_exp_month: Secret::new("10".to_string()),
card_exp_year: Secret::new("2025".to_string()),
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
card_cvc: Secret::new("999".to_string()),
card_issuer: None,
card_network: None,
diff --git a/crates/router/tests/connectors/worldline.rs b/crates/router/tests/connectors/worldline.rs
index fd697f95b75..6a92e0dc93f 100644
--- a/crates/router/tests/connectors/worldline.rs
+++ b/crates/router/tests/connectors/worldline.rs
@@ -71,7 +71,7 @@ impl WorldlineTest {
card_number: cards::CardNumber::from_str(card_number).unwrap(),
card_exp_month: Secret::new(card_exp_month.to_string()),
card_exp_year: Secret::new(card_exp_year.to_string()),
- card_holder_name: Secret::new("John Doe".to_string()),
+ card_holder_name: Some(masking::Secret::new("John Doe".to_string())),
card_cvc: Secret::new(card_cvc.to_string()),
card_issuer: None,
card_network: None,
diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rs
index 9d48aaddd45..8f5ac25736c 100644
--- a/crates/router/tests/payments.rs
+++ b/crates/router/tests/payments.rs
@@ -320,7 +320,7 @@ async fn payments_create_core() {
card_number: "4242424242424242".to_string().try_into().unwrap(),
card_exp_month: "10".to_string().into(),
card_exp_year: "35".to_string().into(),
- card_holder_name: "Arun Raj".to_string().into(),
+ card_holder_name: Some(masking::Secret::new("Arun Raj".to_string())),
card_cvc: "123".to_string().into(),
card_issuer: None,
card_network: None,
@@ -496,7 +496,7 @@ async fn payments_create_core_adyen_no_redirect() {
card_number: "5555 3412 4444 1115".to_string().try_into().unwrap(),
card_exp_month: "03".to_string().into(),
card_exp_year: "2030".to_string().into(),
- card_holder_name: "JohnDoe".to_string().into(),
+ card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())),
card_cvc: "737".to_string().into(),
card_issuer: None,
card_network: None,
diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rs
index 42e5524a15d..89ac522d237 100644
--- a/crates/router/tests/payments2.rs
+++ b/crates/router/tests/payments2.rs
@@ -80,7 +80,7 @@ async fn payments_create_core() {
card_number: "4242424242424242".to_string().try_into().unwrap(),
card_exp_month: "10".to_string().into(),
card_exp_year: "35".to_string().into(),
- card_holder_name: "Arun Raj".to_string().into(),
+ card_holder_name: Some(masking::Secret::new("Arun Raj".to_string())),
card_cvc: "123".to_string().into(),
card_issuer: None,
card_network: None,
@@ -263,7 +263,7 @@ async fn payments_create_core_adyen_no_redirect() {
card_number: "5555 3412 4444 1115".to_string().try_into().unwrap(),
card_exp_month: "03".to_string().into(),
card_exp_year: "2030".to_string().into(),
- card_holder_name: "JohnDoe".to_string().into(),
+ card_holder_name: Some(masking::Secret::new("JohnDoe".to_string())),
card_cvc: "737".to_string().into(),
bank_code: None,
card_issuer: None,
|
refactor
|
make the card_holder_name optional for card details in the payment APIs (#3074)
|
5cb84f66e4c59f6ffbd12bf4e91ab0152ac1c2c5
|
2024-05-31 16:38:52
|
Narayan Bhat
|
refactor(first_name): check if first_name is sent as empty string (#4832)
| false
|
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 30329e132b8..f4e49058c9b 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -2904,7 +2904,11 @@ impl AddressDetails {
pub fn unify_address_details(self, other: Option<&Self>) -> Self {
if let Some(other) = other {
- let (first_name, last_name) = if self.first_name.is_some() {
+ let (first_name, last_name) = if self
+ .first_name
+ .as_ref()
+ .is_some_and(|first_name| !first_name.is_empty_after_trim())
+ {
(self.first_name, self.last_name)
} else {
(other.first_name.clone(), other.last_name.clone())
|
refactor
|
check if first_name is sent as empty string (#4832)
|
2f47491c65fb724476283cf17b5f2c1185c1cd67
|
2024-07-25 14:47:39
|
Sanchith Hegde
|
ci: obtain files modified from PR instead of git diff (#5436)
| false
|
diff --git a/.github/workflows/CI-pr.yml b/.github/workflows/CI-pr.yml
index 4bd50710ce9..4c591cba812 100644
--- a/.github/workflows/CI-pr.yml
+++ b/.github/workflows/CI-pr.yml
@@ -101,10 +101,6 @@ jobs:
- name: Checkout repository
uses: actions/checkout@v4
- - name: "Fetch base branch"
- shell: bash
- run: git fetch origin $GITHUB_BASE_REF --depth 1
-
- name: Install mold linker
uses: rui314/setup-mold@v1
if: ${{ runner.os == 'Linux' }}
@@ -150,6 +146,8 @@ jobs:
- name: Cargo hack
shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
run: just ci_hack
# cargo-deny:
@@ -205,10 +203,6 @@ jobs:
ref: ${{ github.event.pull_request.head.ref }}
token: ${{ steps.generate_token.outputs.token }}
- - name: "Fetch base branch"
- shell: bash
- run: git fetch origin $GITHUB_BASE_REF --depth 1
-
- name: Install mold linker
uses: rui314/setup-mold@v1
if: ${{ runner.os == 'Linux' }}
@@ -277,6 +271,8 @@ jobs:
- name: Run cargo check
shell: bash
+ env:
+ GH_TOKEN: ${{ github.token }}
run: just ci_hack
typos:
diff --git a/scripts/ci-checks.sh b/scripts/ci-checks.sh
index 6bc37451a1c..51089955728 100755
--- a/scripts/ci-checks.sh
+++ b/scripts/ci-checks.sh
@@ -16,29 +16,37 @@ PACKAGES_CHECKED=()
PACKAGES_SKIPPED=()
# If we are running this on a pull request, then only check for packages that are modified
-if [[ -n "${GITHUB_BASE_REF:-}" ]]; then
+if [[ "${GITHUB_EVENT_NAME:-}" == 'pull_request' ]]; then
+ # Obtain the pull request number and files modified in the pull request
+ pull_request_number="$(jq --raw-output '.pull_request.number' "${GITHUB_EVENT_PATH}")"
+ files_modified="$(
+ gh api \
+ --header 'Accept: application/vnd.github+json' \
+ --header 'X-GitHub-Api-Version: 2022-11-28' \
+ --paginate \
+ "https://api.github.com/repos/${GITHUB_REPOSITORY}/pulls/${pull_request_number}/files" \
+ --jq '.[].filename'
+ )"
+
while IFS= read -r package_name; do
- # Obtain comma-separated list of transitive workspace dependencies for each workspace member
+ # Obtain pipe-separated list of transitive workspace dependencies for each workspace member
change_paths="$(cargo tree --all-features --no-dedupe --prefix none --package "${package_name}" \
| grep 'crates/' \
| sort --unique \
- | awk --field-separator ' ' '{ printf "crates/%s\n", $1 }' | paste -d ',' -s -)"
-
- # Store change paths in an array by splitting `change_paths` by comma
- IFS=',' read -ra change_paths <<< "${change_paths}"
+ | awk --field-separator ' ' '{ printf "crates/%s\n", $1 }' | paste -d '|' -s -)"
# A package must be checked if any of its transitive dependencies (or itself) has been modified
- if git diff --exit-code --quiet "origin/${GITHUB_BASE_REF}" -- "${change_paths[@]}"; then
- printf '::debug::Skipping `%s` since none of these paths were modified: %s\n' "${package_name}" "${change_paths[*]}"
- PACKAGES_SKIPPED+=("${package_name}")
- else
- printf '::debug::Checking `%s` since at least one of these paths was modified: %s\n' "${package_name}" "${change_paths[*]}"
+ if grep --quiet --extended-regexp "^(${change_paths})" <<< "${files_modified}"; then
+ printf '::debug::Checking `%s` since at least one of these paths was modified: %s\n' "${package_name}" "${change_paths[*]//|/ }"
PACKAGES_CHECKED+=("${package_name}")
+ else
+ printf '::debug::Skipping `%s` since none of these paths were modified: %s\n' "${package_name}" "${change_paths[*]//|/ }"
+ PACKAGES_SKIPPED+=("${package_name}")
fi
done <<< "${workspace_members}"
printf '::notice::Packages checked: %s; Packages skipped: %s\n' "${PACKAGES_CHECKED[*]}" "${PACKAGES_SKIPPED[*]}"
- packages_checked=$(printf '%s\n' "${PACKAGES_CHECKED[@]}" | jq -R . | jq -s .)
+ packages_checked="$(jq --compact-output --null-input '$ARGS.positional' --args -- "${PACKAGES_CHECKED[@]}")"
crates_with_features="$(cargo metadata --format-version 1 --no-deps \
| jq \
@@ -92,7 +100,7 @@ while IFS= read -r crate && [[ -n "${crate}" ]]; do
all_commands+=("$command")
done <<< "${crates_without_v1_feature}"
-if (( ${#all_commands[@]} == 0 )); then
+if ((${#all_commands[@]} == 0)); then
echo "There are no commands to be be executed"
exit 0
fi
|
ci
|
obtain files modified from PR instead of git diff (#5436)
|
50298c19674cf75fe6a6aee4fa099a4885902357
|
2023-08-01 23:51:21
|
Kritik Modi
|
fix(payments): write a foreign_from implementation for payment_method_data and add missing payment methods in helpers.rs (#1801)
| false
|
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 690d45efb75..97f48da1031 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -956,6 +956,7 @@ pub enum PaymentMethod {
Reward,
Upi,
Voucher,
+ GiftCard,
}
#[derive(
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 2953a5a390c..326ac771960 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -37,7 +37,7 @@ use crate::{
types::{self, AsyncLift},
},
storage::{self, enums as storage_enums, ephemeral_key, CustomerUpdate::Update},
- transformers::ForeignInto,
+ transformers::ForeignTryFrom,
ErrorResponse, RouterData,
},
utils::{
@@ -1400,65 +1400,156 @@ pub(crate) fn validate_payment_method_fields_present(
},
)?;
- let payment_method: Option<api_enums::PaymentMethod> =
- (req.payment_method_type).map(ForeignInto::foreign_into);
-
utils::when(
- req.payment_method.is_some()
- && req.payment_method_type.is_some()
- && (req.payment_method != payment_method),
+ req.payment_method.is_some() && req.payment_method_type.is_some(),
|| {
- Err(errors::ApiErrorResponse::InvalidRequestData {
- message: ("payment_method_type doesn't correspond to the specified payment_method"
- .to_string()),
- })
+ req.payment_method
+ .map_or(Ok(()), |req_payment_method| {
+ req.payment_method_type.map_or(Ok(()), |req_payment_method_type| {
+ if !validate_payment_method_type_against_payment_method(req_payment_method, req_payment_method_type) {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: ("payment_method_type doesn't correspond to the specified payment_method"
+ .to_string()),
+ })
+ } else {
+ Ok(())
+ }
+ })
+ })
},
)?;
+ let validate_payment_method_and_payment_method_data =
+ |req_payment_method_data, req_payment_method: api_enums::PaymentMethod| {
+ api_enums::PaymentMethod::foreign_try_from(req_payment_method_data).and_then(|payment_method|
+ if req_payment_method != payment_method {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: ("payment_method_data doesn't correspond to the specified payment_method"
+ .to_string()),
+ })
+ } else {
+ Ok(())
+ })
+ };
+
utils::when(
- !matches!(
- req.payment_method
- .as_ref()
- .zip(req.payment_method_data.as_ref()),
- Some(
- (
- api_enums::PaymentMethod::Card,
- api::PaymentMethodData::Card(..)
- ) | (
- api_enums::PaymentMethod::Wallet,
- api::PaymentMethodData::Wallet(..)
- ) | (
- api_enums::PaymentMethod::PayLater,
- api::PaymentMethodData::PayLater(..)
- ) | (
- api_enums::PaymentMethod::BankRedirect,
- api::PaymentMethodData::BankRedirect(..)
- ) | (
- api_enums::PaymentMethod::BankDebit,
- api::PaymentMethodData::BankDebit(..)
- ) | (
- api_enums::PaymentMethod::Crypto,
- api::PaymentMethodData::Crypto(..)
- ) | (
- api_enums::PaymentMethod::Upi,
- api::PaymentMethodData::Upi(..)
- ) | (
- api_enums::PaymentMethod::Voucher,
- api::PaymentMethodData::Voucher(..)
- )
- ) | None
- ),
+ req.payment_method.is_some() && req.payment_method_data.is_some(),
|| {
- Err(errors::ApiErrorResponse::InvalidRequestData {
- message: "payment_method_data doesn't correspond to the specified payment_method"
- .to_string(),
- })
+ req.payment_method_data
+ .clone()
+ .map_or(Ok(()), |req_payment_method_data| {
+ req.payment_method.map_or(Ok(()), |req_payment_method| {
+ validate_payment_method_and_payment_method_data(
+ req_payment_method_data,
+ req_payment_method,
+ )
+ })
+ })
},
)?;
Ok(())
}
+pub fn validate_payment_method_type_against_payment_method(
+ payment_method: api_enums::PaymentMethod,
+ payment_method_type: api_enums::PaymentMethodType,
+) -> bool {
+ match payment_method {
+ api_enums::PaymentMethod::Card => matches!(
+ payment_method_type,
+ api_enums::PaymentMethodType::Credit | api_enums::PaymentMethodType::Debit
+ ),
+ api_enums::PaymentMethod::PayLater => matches!(
+ payment_method_type,
+ api_enums::PaymentMethodType::Affirm
+ | api_enums::PaymentMethodType::Alma
+ | api_enums::PaymentMethodType::AfterpayClearpay
+ | api_enums::PaymentMethodType::Klarna
+ | api_enums::PaymentMethodType::PayBright
+ | api_enums::PaymentMethodType::Atome
+ | api_enums::PaymentMethodType::Walley
+ ),
+ api_enums::PaymentMethod::Wallet => matches!(
+ payment_method_type,
+ api_enums::PaymentMethodType::ApplePay
+ | api_enums::PaymentMethodType::GooglePay
+ | api_enums::PaymentMethodType::Paypal
+ | api_enums::PaymentMethodType::AliPay
+ | api_enums::PaymentMethodType::AliPayHk
+ | api_enums::PaymentMethodType::Dana
+ | api_enums::PaymentMethodType::MbWay
+ | api_enums::PaymentMethodType::MobilePay
+ | api_enums::PaymentMethodType::SamsungPay
+ | api_enums::PaymentMethodType::Twint
+ | api_enums::PaymentMethodType::Vipps
+ | api_enums::PaymentMethodType::TouchNGo
+ | api_enums::PaymentMethodType::Swish
+ | api_enums::PaymentMethodType::WeChatPay
+ | api_enums::PaymentMethodType::GoPay
+ | api_enums::PaymentMethodType::Gcash
+ | api_enums::PaymentMethodType::Momo
+ | api_enums::PaymentMethodType::KakaoPay
+ ),
+ api_enums::PaymentMethod::BankRedirect => matches!(
+ payment_method_type,
+ api_enums::PaymentMethodType::Giropay
+ | api_enums::PaymentMethodType::Ideal
+ | api_enums::PaymentMethodType::Sofort
+ | api_enums::PaymentMethodType::Eps
+ | api_enums::PaymentMethodType::BancontactCard
+ | api_enums::PaymentMethodType::Blik
+ | api_enums::PaymentMethodType::OnlineBankingThailand
+ | api_enums::PaymentMethodType::OnlineBankingCzechRepublic
+ | api_enums::PaymentMethodType::OnlineBankingFinland
+ | api_enums::PaymentMethodType::OnlineBankingFpx
+ | api_enums::PaymentMethodType::OnlineBankingPoland
+ | api_enums::PaymentMethodType::OnlineBankingSlovakia
+ | api_enums::PaymentMethodType::Przelewy24
+ | api_enums::PaymentMethodType::Trustly
+ | api_enums::PaymentMethodType::Bizum
+ | api_enums::PaymentMethodType::Interac
+ ),
+ api_enums::PaymentMethod::BankTransfer => matches!(
+ payment_method_type,
+ api_enums::PaymentMethodType::Ach
+ | api_enums::PaymentMethodType::Sepa
+ | api_enums::PaymentMethodType::Bacs
+ | api_enums::PaymentMethodType::Multibanco
+ | api_enums::PaymentMethodType::Pix
+ | api_enums::PaymentMethodType::Pse
+ ),
+ api_enums::PaymentMethod::BankDebit => matches!(
+ payment_method_type,
+ api_enums::PaymentMethodType::Ach
+ | api_enums::PaymentMethodType::Sepa
+ | api_enums::PaymentMethodType::Bacs
+ | api_enums::PaymentMethodType::Becs
+ ),
+ api_enums::PaymentMethod::Crypto => matches!(
+ payment_method_type,
+ api_enums::PaymentMethodType::CryptoCurrency
+ ),
+ api_enums::PaymentMethod::Reward => matches!(
+ payment_method_type,
+ api_enums::PaymentMethodType::Evoucher | api_enums::PaymentMethodType::ClassicReward
+ ),
+ api_enums::PaymentMethod::Upi => matches!(
+ payment_method_type,
+ api_enums::PaymentMethodType::UpiCollect
+ ),
+ api_enums::PaymentMethod::Voucher => matches!(
+ payment_method_type,
+ api_enums::PaymentMethodType::Boleto
+ | api_enums::PaymentMethodType::Efecty
+ | api_enums::PaymentMethodType::PagoEfectivo
+ | api_enums::PaymentMethodType::RedCompra
+ | api_enums::PaymentMethodType::RedPagos
+ ),
+ api_enums::PaymentMethod::GiftCard => false,
+ }
+}
+
pub fn check_force_psync_precondition(
status: &storage_enums::AttemptStatus,
connector_transaction_id: &Option<String>,
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index b4d0b1298b9..5d9d9a73d91 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -230,6 +230,32 @@ impl ForeignFrom<api_enums::PaymentMethodType> for api_enums::PaymentMethod {
}
}
+impl ForeignTryFrom<api_models::payments::PaymentMethodData> for api_enums::PaymentMethod {
+ type Error = errors::ApiErrorResponse;
+ fn foreign_try_from(
+ payment_method_data: api_models::payments::PaymentMethodData,
+ ) -> Result<Self, Self::Error> {
+ match payment_method_data {
+ api_models::payments::PaymentMethodData::Card(..) => Ok(Self::Card),
+ api_models::payments::PaymentMethodData::Wallet(..) => Ok(Self::Wallet),
+ api_models::payments::PaymentMethodData::PayLater(..) => Ok(Self::PayLater),
+ api_models::payments::PaymentMethodData::BankRedirect(..) => Ok(Self::BankRedirect),
+ api_models::payments::PaymentMethodData::BankDebit(..) => Ok(Self::BankDebit),
+ api_models::payments::PaymentMethodData::BankTransfer(..) => Ok(Self::BankTransfer),
+ api_models::payments::PaymentMethodData::Crypto(..) => Ok(Self::Crypto),
+ api_models::payments::PaymentMethodData::Reward(..) => Ok(Self::Reward),
+ api_models::payments::PaymentMethodData::Upi(..) => Ok(Self::Upi),
+ api_models::payments::PaymentMethodData::Voucher(..) => Ok(Self::Voucher),
+ api_models::payments::PaymentMethodData::GiftCard(..) => Ok(Self::GiftCard),
+ api_models::payments::PaymentMethodData::MandatePayment => {
+ Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: ("Mandate payments cannot have payment_method_data field".to_string()),
+ })
+ }
+ }
+ }
+}
+
impl ForeignTryFrom<storage_enums::RefundStatus> for storage_enums::EventType {
type Error = errors::ValidationError;
diff --git a/openapi/openapi_spec.json b/openapi/openapi_spec.json
index 79c70fda30d..ac8c594e9ce 100644
--- a/openapi/openapi_spec.json
+++ b/openapi/openapi_spec.json
@@ -7003,7 +7003,8 @@
"bank_debit",
"reward",
"upi",
- "voucher"
+ "voucher",
+ "gift_card"
]
},
"PaymentMethodCreate": {
|
fix
|
write a foreign_from implementation for payment_method_data and add missing payment methods in helpers.rs (#1801)
|
4b989fe0fb7931479e127fecbaace42d989c0620
|
2024-12-16 14:23:31
|
Mani Chandra
|
feat(users): Incorporate themes in user APIs (#6772)
| false
|
diff --git a/config/config.example.toml b/config/config.example.toml
index 5aa9e543fb2..0fe6b8caa2c 100644
--- a/config/config.example.toml
+++ b/config/config.example.toml
@@ -797,5 +797,12 @@ host = "localhost" # Client Host
port = 7000 # Client Port
service = "dynamo" # Service name
-[theme_storage]
+[theme.storage]
file_storage_backend = "file_system" # Theme storage backend to be used
+
+[theme.email_config]
+entity_name = "Hyperswitch" # Name of the entity to be showed in emails
+entity_logo_url = "https://example.com/logo.svg" # Logo URL of the entity to be used in emails
+foreground_color = "#000000" # Foreground color of email text
+primary_color = "#006DF9" # Primary color of email body
+background_color = "#FFFFFF" # Background color of email body
diff --git a/config/deployments/env_specific.toml b/config/deployments/env_specific.toml
index 5cadc66ddfc..848a2305ae4 100644
--- a/config/deployments/env_specific.toml
+++ b/config/deployments/env_specific.toml
@@ -328,9 +328,16 @@ host = "localhost" # Client Host
port = 7000 # Client Port
service = "dynamo" # Service name
-[theme_storage]
+[theme.storage]
file_storage_backend = "aws_s3" # Theme storage backend to be used
-[theme_storage.aws_s3]
+[theme.storage.aws_s3]
region = "bucket_region" # AWS region where the S3 bucket for theme storage is located
bucket_name = "bucket" # AWS S3 bucket name for theme storage
+
+[theme.email_config]
+entity_name = "Hyperswitch" # Name of the entity to be showed in emails
+entity_logo_url = "https://example.com/logo.svg" # Logo URL of the entity to be used in emails
+foreground_color = "#000000" # Foreground color of email text
+primary_color = "#006DF9" # Primary color of email body
+background_color = "#FFFFFF" # Background color of email body
diff --git a/config/development.toml b/config/development.toml
index fa577a78e6a..077e09f0463 100644
--- a/config/development.toml
+++ b/config/development.toml
@@ -797,5 +797,12 @@ host = "localhost"
port = 7000
service = "dynamo"
-[theme_storage]
-file_storage_backend = "file_system"
+[theme.storage]
+file_storage_backend = "file_system" # Theme storage backend to be used
+
+[theme.email_config]
+entity_name = "Hyperswitch" # Name of the entity to be showed in emails
+entity_logo_url = "https://example.com/logo.svg" # Logo URL of the entity to be used in emails
+foreground_color = "#000000" # Foreground color of email text
+primary_color = "#006DF9" # Primary color of email body
+background_color = "#FFFFFF" # Background color of email body
diff --git a/config/docker_compose.toml b/config/docker_compose.toml
index 3cc690203e6..dbd5286b290 100644
--- a/config/docker_compose.toml
+++ b/config/docker_compose.toml
@@ -694,5 +694,12 @@ prod_intent_recipient_email = "[email protected]" # Recipient email for prod
email_role_arn = "" # The amazon resource name ( arn ) of the role which has permission to send emails
sts_role_session_name = "" # An identifier for the assumed role session, used to uniquely identify a session.
-[theme_storage]
+[theme.storage]
file_storage_backend = "file_system" # Theme storage backend to be used
+
+[theme.email_config]
+entity_name = "Hyperswitch" # Name of the entity to be showed in emails
+entity_logo_url = "https://example.com/logo.svg" # Logo URL of the entity to be used in emails
+foreground_color = "#000000" # Foreground color of email text
+primary_color = "#006DF9" # Primary color of email body
+background_color = "#FFFFFF" # Background color of email body
diff --git a/crates/api_models/src/user.rs b/crates/api_models/src/user.rs
index e61696803a2..7b5911cf1a8 100644
--- a/crates/api_models/src/user.rs
+++ b/crates/api_models/src/user.rs
@@ -150,6 +150,7 @@ pub struct GetUserDetailsResponse {
pub recovery_codes_left: Option<usize>,
pub profile_id: id_type::ProfileId,
pub entity_type: EntityType,
+ pub theme_id: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
@@ -345,8 +346,9 @@ pub struct SsoSignInRequest {
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
-pub struct AuthIdQueryParam {
+pub struct AuthIdAndThemeIdQueryParam {
pub auth_id: Option<String>,
+ pub theme_id: Option<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
diff --git a/crates/api_models/src/user/theme.rs b/crates/api_models/src/user/theme.rs
index 23218c4a163..c79da307b9a 100644
--- a/crates/api_models/src/user/theme.rs
+++ b/crates/api_models/src/user/theme.rs
@@ -1,6 +1,9 @@
use actix_multipart::form::{bytes::Bytes, text::Text, MultipartForm};
use common_enums::EntityType;
-use common_utils::{id_type, types::theme::ThemeLineage};
+use common_utils::{
+ id_type,
+ types::theme::{EmailThemeConfig, ThemeLineage},
+};
use masking::Secret;
use serde::{Deserialize, Serialize};
@@ -13,6 +16,7 @@ pub struct GetThemeResponse {
pub org_id: Option<id_type::OrganizationId>,
pub merchant_id: Option<id_type::MerchantId>,
pub profile_id: Option<id_type::ProfileId>,
+ pub email_config: EmailThemeConfig,
pub theme_data: ThemeData,
}
@@ -35,12 +39,14 @@ pub struct CreateThemeRequest {
pub lineage: ThemeLineage,
pub theme_name: String,
pub theme_data: ThemeData,
+ pub email_config: Option<EmailThemeConfig>,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct UpdateThemeRequest {
pub lineage: ThemeLineage,
pub theme_data: ThemeData,
+ // TODO: Add support to update email config
}
// All the below structs are for the theme.json file,
diff --git a/crates/common_utils/src/types/theme.rs b/crates/common_utils/src/types/theme.rs
index 239cffc40d4..05ae26b565a 100644
--- a/crates/common_utils/src/types/theme.rs
+++ b/crates/common_utils/src/types/theme.rs
@@ -1,4 +1,5 @@
use common_enums::EntityType;
+use serde::{Deserialize, Serialize};
use crate::{
events::{ApiEventMetric, ApiEventsType},
@@ -7,15 +8,14 @@ use crate::{
/// Enum for having all the required lineage for every level.
/// Currently being used for theme related APIs and queries.
-#[derive(Debug, serde::Deserialize, serde::Serialize)]
+#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "entity_type", rename_all = "snake_case")]
pub enum ThemeLineage {
- // TODO: Add back Tenant variant when we introduce Tenant Variant in EntityType
- // /// Tenant lineage variant
- // Tenant {
- // /// tenant_id: String
- // tenant_id: String,
- // },
+ /// Tenant lineage variant
+ Tenant {
+ /// tenant_id: TenantId
+ tenant_id: id_type::TenantId,
+ },
/// Org lineage variant
Organization {
/// tenant_id: TenantId
@@ -48,9 +48,35 @@ pub enum ThemeLineage {
impl_api_event_type!(Miscellaneous, (ThemeLineage));
impl ThemeLineage {
+ /// Constructor for ThemeLineage
+ pub fn new(
+ entity_type: EntityType,
+ tenant_id: id_type::TenantId,
+ org_id: id_type::OrganizationId,
+ merchant_id: id_type::MerchantId,
+ profile_id: id_type::ProfileId,
+ ) -> Self {
+ match entity_type {
+ EntityType::Tenant => Self::Tenant { tenant_id },
+ EntityType::Organization => Self::Organization { tenant_id, org_id },
+ EntityType::Merchant => Self::Merchant {
+ tenant_id,
+ org_id,
+ merchant_id,
+ },
+ EntityType::Profile => Self::Profile {
+ tenant_id,
+ org_id,
+ merchant_id,
+ profile_id,
+ },
+ }
+ }
+
/// Get the entity_type from the lineage
pub fn entity_type(&self) -> EntityType {
match self {
+ Self::Tenant { .. } => EntityType::Tenant,
Self::Organization { .. } => EntityType::Organization,
Self::Merchant { .. } => EntityType::Merchant,
Self::Profile { .. } => EntityType::Profile,
@@ -60,7 +86,8 @@ impl ThemeLineage {
/// Get the tenant_id from the lineage
pub fn tenant_id(&self) -> &id_type::TenantId {
match self {
- Self::Organization { tenant_id, .. }
+ Self::Tenant { tenant_id }
+ | Self::Organization { tenant_id, .. }
| Self::Merchant { tenant_id, .. }
| Self::Profile { tenant_id, .. } => tenant_id,
}
@@ -69,6 +96,7 @@ impl ThemeLineage {
/// Get the org_id from the lineage
pub fn org_id(&self) -> Option<&id_type::OrganizationId> {
match self {
+ Self::Tenant { .. } => None,
Self::Organization { org_id, .. }
| Self::Merchant { org_id, .. }
| Self::Profile { org_id, .. } => Some(org_id),
@@ -78,7 +106,7 @@ impl ThemeLineage {
/// Get the merchant_id from the lineage
pub fn merchant_id(&self) -> Option<&id_type::MerchantId> {
match self {
- Self::Organization { .. } => None,
+ Self::Tenant { .. } | Self::Organization { .. } => None,
Self::Merchant { merchant_id, .. } | Self::Profile { merchant_id, .. } => {
Some(merchant_id)
}
@@ -88,8 +116,72 @@ impl ThemeLineage {
/// Get the profile_id from the lineage
pub fn profile_id(&self) -> Option<&id_type::ProfileId> {
match self {
- Self::Organization { .. } | Self::Merchant { .. } => None,
+ Self::Tenant { .. } | Self::Organization { .. } | Self::Merchant { .. } => None,
Self::Profile { profile_id, .. } => Some(profile_id),
}
}
+
+ /// Get higher lineages from the current lineage
+ pub fn get_same_and_higher_lineages(self) -> Vec<Self> {
+ match &self {
+ Self::Tenant { .. } => vec![self],
+ Self::Organization { tenant_id, .. } => vec![
+ Self::Tenant {
+ tenant_id: tenant_id.clone(),
+ },
+ self,
+ ],
+ Self::Merchant {
+ tenant_id, org_id, ..
+ } => vec![
+ Self::Tenant {
+ tenant_id: tenant_id.clone(),
+ },
+ Self::Organization {
+ tenant_id: tenant_id.clone(),
+ org_id: org_id.clone(),
+ },
+ self,
+ ],
+ Self::Profile {
+ tenant_id,
+ org_id,
+ merchant_id,
+ ..
+ } => vec![
+ Self::Tenant {
+ tenant_id: tenant_id.clone(),
+ },
+ Self::Organization {
+ tenant_id: tenant_id.clone(),
+ org_id: org_id.clone(),
+ },
+ Self::Merchant {
+ tenant_id: tenant_id.clone(),
+ org_id: org_id.clone(),
+ merchant_id: merchant_id.clone(),
+ },
+ self,
+ ],
+ }
+ }
+}
+
+/// Struct for holding the theme settings for email
+#[derive(Debug, Clone, Default, Deserialize, Serialize)]
+pub struct EmailThemeConfig {
+ /// The entity name to be used in the email
+ pub entity_name: String,
+
+ /// The URL of the entity logo to be used in the email
+ pub entity_logo_url: String,
+
+ /// The primary color to be used in the email
+ pub primary_color: String,
+
+ /// The foreground color to be used in the email
+ pub foreground_color: String,
+
+ /// The background color to be used in the email
+ pub background_color: String,
}
diff --git a/crates/diesel_models/src/query/user/theme.rs b/crates/diesel_models/src/query/user/theme.rs
index a26e401ffbb..945ce1a9bb2 100644
--- a/crates/diesel_models/src/query/user/theme.rs
+++ b/crates/diesel_models/src/query/user/theme.rs
@@ -1,13 +1,22 @@
+use async_bb8_diesel::AsyncRunQueryDsl;
use common_utils::types::theme::ThemeLineage;
use diesel::{
associations::HasTable,
+ debug_query,
pg::Pg,
+ result::Error as DieselError,
sql_types::{Bool, Nullable},
- BoolExpressionMethods, ExpressionMethods,
+ BoolExpressionMethods, ExpressionMethods, NullableExpressionMethods, QueryDsl,
};
+use error_stack::{report, ResultExt};
+use router_env::logger;
use crate::{
- query::generics,
+ errors::DatabaseError,
+ query::generics::{
+ self,
+ db_metrics::{track_database_call, DatabaseOperation},
+ },
schema::themes::dsl,
user::theme::{Theme, ThemeNew},
PgPooledConn, StorageResult,
@@ -27,15 +36,14 @@ impl Theme {
+ 'static,
> {
match lineage {
- // TODO: Add back Tenant variant when we introduce Tenant Variant in EntityType
- // ThemeLineage::Tenant { tenant_id } => Box::new(
- // dsl::tenant_id
- // .eq(tenant_id)
- // .and(dsl::org_id.is_null())
- // .and(dsl::merchant_id.is_null())
- // .and(dsl::profile_id.is_null())
- // .nullable(),
- // ),
+ ThemeLineage::Tenant { tenant_id } => Box::new(
+ dsl::tenant_id
+ .eq(tenant_id)
+ .and(dsl::org_id.is_null())
+ .and(dsl::merchant_id.is_null())
+ .and(dsl::profile_id.is_null())
+ .nullable(),
+ ),
ThemeLineage::Organization { tenant_id, org_id } => Box::new(
dsl::tenant_id
.eq(tenant_id)
@@ -77,6 +85,41 @@ impl Theme {
.await
}
+ pub async fn find_most_specific_theme_in_lineage(
+ conn: &PgPooledConn,
+ lineage: ThemeLineage,
+ ) -> StorageResult<Self> {
+ let query = <Self as HasTable>::table().into_boxed();
+
+ let query =
+ lineage
+ .get_same_and_higher_lineages()
+ .into_iter()
+ .fold(query, |mut query, lineage| {
+ query = query.or_filter(Self::lineage_filter(lineage));
+ query
+ });
+
+ logger::debug!(query = %debug_query::<Pg,_>(&query).to_string());
+
+ let data: Vec<Self> = match track_database_call::<Self, _, _>(
+ query.get_results_async(conn),
+ DatabaseOperation::Filter,
+ )
+ .await
+ {
+ Ok(value) => Ok(value),
+ Err(err) => match err {
+ DieselError::NotFound => Err(report!(err)).change_context(DatabaseError::NotFound),
+ _ => Err(report!(err)).change_context(DatabaseError::Others),
+ },
+ }?;
+
+ data.into_iter()
+ .min_by_key(|theme| theme.entity_type)
+ .ok_or(report!(DatabaseError::NotFound))
+ }
+
pub async fn find_by_lineage(
conn: &PgPooledConn,
lineage: ThemeLineage,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 782bdb1b9d3..178f5600542 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -1321,6 +1321,15 @@ diesel::table! {
entity_type -> Varchar,
#[max_length = 64]
theme_name -> Varchar,
+ #[max_length = 64]
+ email_primary_color -> Varchar,
+ #[max_length = 64]
+ email_foreground_color -> Varchar,
+ #[max_length = 64]
+ email_background_color -> Varchar,
+ #[max_length = 64]
+ email_entity_name -> Varchar,
+ email_entity_logo_url -> Text,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index cb1eaad64f4..da2298d934b 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -1268,6 +1268,15 @@ diesel::table! {
entity_type -> Varchar,
#[max_length = 64]
theme_name -> Varchar,
+ #[max_length = 64]
+ email_primary_color -> Varchar,
+ #[max_length = 64]
+ email_foreground_color -> Varchar,
+ #[max_length = 64]
+ email_background_color -> Varchar,
+ #[max_length = 64]
+ email_entity_name -> Varchar,
+ email_entity_logo_url -> Text,
}
}
diff --git a/crates/diesel_models/src/user/theme.rs b/crates/diesel_models/src/user/theme.rs
index e43a182126b..46cc90a45ec 100644
--- a/crates/diesel_models/src/user/theme.rs
+++ b/crates/diesel_models/src/user/theme.rs
@@ -1,5 +1,8 @@
use common_enums::EntityType;
-use common_utils::{date_time, id_type, types::theme::ThemeLineage};
+use common_utils::{
+ date_time, id_type,
+ types::theme::{EmailThemeConfig, ThemeLineage},
+};
use diesel::{Identifiable, Insertable, Queryable, Selectable};
use time::PrimitiveDateTime;
@@ -17,6 +20,11 @@ pub struct Theme {
pub last_modified_at: PrimitiveDateTime,
pub entity_type: EntityType,
pub theme_name: String,
+ pub email_primary_color: String,
+ pub email_foreground_color: String,
+ pub email_background_color: String,
+ pub email_entity_name: String,
+ pub email_entity_logo_url: String,
}
#[derive(Clone, Debug, Insertable, router_derive::DebugAsDisplay)]
@@ -31,10 +39,20 @@ pub struct ThemeNew {
pub last_modified_at: PrimitiveDateTime,
pub entity_type: EntityType,
pub theme_name: String,
+ pub email_primary_color: String,
+ pub email_foreground_color: String,
+ pub email_background_color: String,
+ pub email_entity_name: String,
+ pub email_entity_logo_url: String,
}
impl ThemeNew {
- pub fn new(theme_id: String, theme_name: String, lineage: ThemeLineage) -> Self {
+ pub fn new(
+ theme_id: String,
+ theme_name: String,
+ lineage: ThemeLineage,
+ email_config: EmailThemeConfig,
+ ) -> Self {
let now = date_time::now();
Self {
@@ -47,6 +65,23 @@ impl ThemeNew {
entity_type: lineage.entity_type(),
created_at: now,
last_modified_at: now,
+ email_primary_color: email_config.primary_color,
+ email_foreground_color: email_config.foreground_color,
+ email_background_color: email_config.background_color,
+ email_entity_name: email_config.entity_name,
+ email_entity_logo_url: email_config.entity_logo_url,
+ }
+ }
+}
+
+impl Theme {
+ pub fn email_config(&self) -> EmailThemeConfig {
+ EmailThemeConfig {
+ primary_color: self.email_primary_color.clone(),
+ foreground_color: self.email_foreground_color.clone(),
+ background_color: self.email_background_color.clone(),
+ entity_name: self.email_entity_name.clone(),
+ entity_logo_url: self.email_entity_logo_url.clone(),
}
}
}
diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rs
index 3ab56266b55..3862f70536f 100644
--- a/crates/router/src/configs/secrets_transformers.rs
+++ b/crates/router/src/configs/secrets_transformers.rs
@@ -545,6 +545,6 @@ pub(crate) async fn fetch_raw_secrets(
.network_tokenization_supported_card_networks,
network_tokenization_service,
network_tokenization_supported_connectors: conf.network_tokenization_supported_connectors,
- theme_storage: conf.theme_storage,
+ theme: conf.theme,
}
}
diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rs
index 1da4a33f5f3..4ab2a8fd5c7 100644
--- a/crates/router/src/configs/settings.rs
+++ b/crates/router/src/configs/settings.rs
@@ -6,7 +6,7 @@ use std::{
#[cfg(feature = "olap")]
use analytics::{opensearch::OpenSearchConfig, ReportConfig};
use api_models::{enums, payment_methods::RequiredFieldInfo};
-use common_utils::{ext_traits::ConfigExt, id_type};
+use common_utils::{ext_traits::ConfigExt, id_type, types::theme::EmailThemeConfig};
use config::{Environment, File};
use error_stack::ResultExt;
#[cfg(feature = "email")]
@@ -128,7 +128,7 @@ pub struct Settings<S: SecretState> {
pub network_tokenization_supported_card_networks: NetworkTokenizationSupportedCardNetworks,
pub network_tokenization_service: Option<SecretStateContainer<NetworkTokenizationService, S>>,
pub network_tokenization_supported_connectors: NetworkTokenizationSupportedConnectors,
- pub theme_storage: FileStorageConfig,
+ pub theme: ThemeSettings,
}
#[derive(Debug, Deserialize, Clone, Default)]
@@ -887,7 +887,8 @@ impl Settings<SecuredSecret> {
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.into()))?;
- self.theme_storage
+ self.theme
+ .storage
.validate()
.map_err(|err| ApplicationError::InvalidConfigurationValueError(err.to_string()))?;
@@ -992,6 +993,12 @@ impl Default for CellInformation {
}
}
+#[derive(Debug, Deserialize, Clone, Default)]
+pub struct ThemeSettings {
+ pub storage: FileStorageConfig,
+ pub email_config: EmailThemeConfig,
+}
+
fn deserialize_hashmap_inner<K, V>(
value: HashMap<String, String>,
) -> Result<HashMap<K, HashSet<V>>, String>
diff --git a/crates/router/src/core/errors/user.rs b/crates/router/src/core/errors/user.rs
index 33477df6330..fa5f185ab82 100644
--- a/crates/router/src/core/errors/user.rs
+++ b/crates/router/src/core/errors/user.rs
@@ -106,6 +106,8 @@ pub enum UserErrors {
ThemeAlreadyExists,
#[error("Invalid field: {0} in lineage")]
InvalidThemeLineage(String),
+ #[error("Missing required field: email_config")]
+ MissingEmailConfig,
}
impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorResponse> for UserErrors {
@@ -275,6 +277,9 @@ impl common_utils::errors::ErrorSwitch<api_models::errors::types::ApiErrorRespon
Self::InvalidThemeLineage(_) => {
AER::BadRequest(ApiError::new(sub_code, 55, self.get_error_message(), None))
}
+ Self::MissingEmailConfig => {
+ AER::BadRequest(ApiError::new(sub_code, 56, self.get_error_message(), None))
+ }
}
}
}
@@ -341,6 +346,7 @@ impl UserErrors {
Self::InvalidThemeLineage(field_name) => {
format!("Invalid field: {} in lineage", field_name)
}
+ Self::MissingEmailConfig => "Missing required field: email_config".to_string(),
}
}
}
diff --git a/crates/router/src/core/recon.rs b/crates/router/src/core/recon.rs
index 13cf4c488ec..c2f289d4cc0 100644
--- a/crates/router/src/core/recon.rs
+++ b/crates/router/src/core/recon.rs
@@ -1,12 +1,14 @@
use api_models::recon as recon_api;
#[cfg(feature = "email")]
-use common_utils::ext_traits::AsyncExt;
+use common_utils::{ext_traits::AsyncExt, types::theme::ThemeLineage};
use error_stack::ResultExt;
#[cfg(feature = "email")]
use masking::{ExposeInterface, PeekInterface, Secret};
#[cfg(feature = "email")]
-use crate::{consts, services::email::types as email_types, types::domain};
+use crate::{
+ consts, services::email::types as email_types, types::domain, utils::user::theme as theme_utils,
+};
use crate::{
core::errors::{self, RouterResponse, UserErrors, UserResponse},
services::{api as service_api, authentication},
@@ -35,6 +37,21 @@ pub async fn send_recon_request(
let user_in_db = &auth_data.user;
let merchant_id = auth_data.merchant_account.get_id().clone();
+ let theme = theme_utils::get_most_specific_theme_using_lineage(
+ &state.clone(),
+ ThemeLineage::Merchant {
+ tenant_id: state.tenant.tenant_id.clone(),
+ org_id: auth_data.merchant_account.get_org_id().clone(),
+ merchant_id: merchant_id.clone(),
+ },
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(format!(
+ "Failed to fetch theme for merchant_id = {:?}",
+ merchant_id
+ ))?;
+
let user_email = user_in_db.email.clone();
let email_contents = email_types::ProFeatureRequest {
feature_name: consts::RECON_FEATURE_TAG.to_string(),
@@ -55,6 +72,10 @@ pub async fn send_recon_request(
consts::EMAIL_SUBJECT_DASHBOARD_FEATURE_REQUEST,
user_email.expose().peek()
),
+ theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
+ theme_config: theme
+ .map(|theme| theme.email_config())
+ .unwrap_or(state.conf.theme.email_config.clone()),
};
state
.email_client
@@ -141,7 +162,7 @@ pub async fn recon_merchant_account_update(
let updated_merchant_account = db
.update_merchant(
key_manager_state,
- auth.merchant_account,
+ auth.merchant_account.clone(),
updated_merchant_account,
&auth.key_store,
)
@@ -154,6 +175,22 @@ pub async fn recon_merchant_account_update(
#[cfg(feature = "email")]
{
let user_email = &req.user_email.clone();
+
+ let theme = theme_utils::get_most_specific_theme_using_lineage(
+ &state.clone(),
+ ThemeLineage::Merchant {
+ tenant_id: state.tenant.tenant_id,
+ org_id: auth.merchant_account.get_org_id().clone(),
+ merchant_id: merchant_id.clone(),
+ },
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable(format!(
+ "Failed to fetch theme for merchant_id = {:?}",
+ merchant_id
+ ))?;
+
let email_contents = email_types::ReconActivation {
recipient_email: domain::UserEmail::from_pii_email(user_email.clone())
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -164,6 +201,10 @@ pub async fn recon_merchant_account_update(
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to form username")?,
subject: consts::EMAIL_SUBJECT_APPROVAL_RECON_REQUEST,
+ theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
+ theme_config: theme
+ .map(|theme| theme.email_config())
+ .unwrap_or(state.conf.theme.email_config.clone()),
};
if req.recon_status == enums::ReconStatus::Active {
let _ = state
diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rs
index 629476b2591..642473bdf8e 100644
--- a/crates/router/src/core/user.rs
+++ b/crates/router/src/core/user.rs
@@ -42,7 +42,10 @@ use crate::{
routes::{app::ReqState, SessionState},
services::{authentication as auth, authorization::roles, openidconnect, ApplicationResponse},
types::{domain, transformers::ForeignInto},
- utils::{self, user::two_factor_auth as tfa_utils},
+ utils::{
+ self,
+ user::{theme as theme_utils, two_factor_auth as tfa_utils},
+ },
};
pub mod dashboard_metadata;
@@ -55,6 +58,7 @@ pub async fn signup_with_merchant_id(
state: SessionState,
request: user_api::SignUpWithMerchantIdRequest,
auth_id: Option<String>,
+ theme_id: Option<String>,
) -> UserResponse<user_api::SignUpWithMerchantIdResponse> {
let new_user = domain::NewUser::try_from(request.clone())?;
new_user
@@ -75,12 +79,18 @@ pub async fn signup_with_merchant_id(
)
.await?;
+ let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;
+
let email_contents = email_types::ResetPassword {
recipient_email: user_from_db.get_email().try_into()?,
user_name: domain::UserName::new(user_from_db.get_name())?,
settings: state.conf.clone(),
subject: consts::user::EMAIL_SUBJECT_RESET_PASSWORD,
auth_id,
+ theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
+ theme_config: theme
+ .map(|theme| theme.email_config())
+ .unwrap_or(state.conf.theme.email_config.clone()),
};
let send_email_result = state
@@ -112,6 +122,13 @@ pub async fn get_user_details(
.await
.change_context(UserErrors::InternalServerError)?;
+ let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity(
+ &state,
+ &user_from_token,
+ EntityType::Profile,
+ )
+ .await?;
+
Ok(ApplicationResponse::Json(
user_api::GetUserDetailsResponse {
merchant_id: user_from_token.merchant_id,
@@ -125,6 +142,7 @@ pub async fn get_user_details(
recovery_codes_left: user.get_recovery_codes().map(|codes| codes.len()),
profile_id: user_from_token.profile_id,
entity_type: role_info.get_entity_type(),
+ theme_id: theme.map(|theme| theme.theme_id),
},
))
}
@@ -194,6 +212,7 @@ pub async fn connect_account(
state: SessionState,
request: user_api::ConnectAccountRequest,
auth_id: Option<String>,
+ theme_id: Option<String>,
) -> UserResponse<user_api::ConnectAccountResponse> {
let find_user = state
.global_store
@@ -203,12 +222,18 @@ pub async fn connect_account(
if let Ok(found_user) = find_user {
let user_from_db: domain::UserFromStorage = found_user.into();
+ let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;
+
let email_contents = email_types::MagicLink {
recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
settings: state.conf.clone(),
user_name: domain::UserName::new(user_from_db.get_name())?,
subject: consts::user::EMAIL_SUBJECT_MAGIC_LINK,
auth_id,
+ theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
+ theme_config: theme
+ .map(|theme| theme.email_config())
+ .unwrap_or(state.conf.theme.email_config.clone()),
};
let send_email_result = state
@@ -253,11 +278,17 @@ pub async fn connect_account(
)
.await?;
+ let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;
+
let magic_link_email = email_types::VerifyEmail {
recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
settings: state.conf.clone(),
subject: consts::user::EMAIL_SUBJECT_SIGNUP,
auth_id,
+ theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
+ theme_config: theme
+ .map(|theme| theme.email_config())
+ .unwrap_or(state.conf.theme.email_config.clone()),
};
let magic_link_result = state
@@ -270,20 +301,22 @@ pub async fn connect_account(
logger::info!(?magic_link_result);
- let welcome_to_community_email = email_types::WelcomeToCommunity {
- recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
- subject: consts::user::EMAIL_SUBJECT_WELCOME_TO_COMMUNITY,
- };
+ if state.tenant.tenant_id.get_string_repr() == common_utils::consts::DEFAULT_TENANT {
+ let welcome_to_community_email = email_types::WelcomeToCommunity {
+ recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
+ subject: consts::user::EMAIL_SUBJECT_WELCOME_TO_COMMUNITY,
+ };
- let welcome_email_result = state
- .email_client
- .compose_and_send_email(
- Box::new(welcome_to_community_email),
- state.conf.proxy.https_url.as_ref(),
- )
- .await;
+ let welcome_email_result = state
+ .email_client
+ .compose_and_send_email(
+ Box::new(welcome_to_community_email),
+ state.conf.proxy.https_url.as_ref(),
+ )
+ .await;
- logger::info!(?welcome_email_result);
+ logger::info!(?welcome_email_result);
+ }
return Ok(ApplicationResponse::Json(
user_api::ConnectAccountResponse {
@@ -371,6 +404,7 @@ pub async fn forgot_password(
state: SessionState,
request: user_api::ForgotPasswordRequest,
auth_id: Option<String>,
+ theme_id: Option<String>,
) -> UserResponse<()> {
let user_email = domain::UserEmail::from_pii_email(request.email)?;
@@ -387,12 +421,18 @@ pub async fn forgot_password(
})
.map(domain::UserFromStorage::from)?;
+ let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;
+
let email_contents = email_types::ResetPassword {
recipient_email: domain::UserEmail::from_pii_email(user_from_db.get_email())?,
settings: state.conf.clone(),
user_name: domain::UserName::new(user_from_db.get_name())?,
subject: consts::user::EMAIL_SUBJECT_RESET_PASSWORD,
auth_id,
+ theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
+ theme_config: theme
+ .map(|theme| theme.email_config())
+ .unwrap_or(state.conf.theme.email_config.clone()),
};
state
@@ -782,6 +822,13 @@ async fn handle_existing_user_invitation(
},
};
+ let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity(
+ state,
+ user_from_token,
+ role_info.get_entity_type(),
+ )
+ .await?;
+
let email_contents = email_types::InviteUser {
recipient_email: invitee_email,
user_name: domain::UserName::new(invitee_user_from_db.get_name())?,
@@ -789,6 +836,10 @@ async fn handle_existing_user_invitation(
subject: consts::user::EMAIL_SUBJECT_INVITATION,
entity,
auth_id: auth_id.clone(),
+ theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
+ theme_config: theme
+ .map(|theme| theme.email_config())
+ .unwrap_or(state.conf.theme.email_config.clone()),
};
is_email_sent = state
@@ -927,6 +978,13 @@ async fn handle_new_user_invitation(
},
};
+ let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity(
+ state,
+ user_from_token,
+ role_info.get_entity_type(),
+ )
+ .await?;
+
let email_contents = email_types::InviteUser {
recipient_email: invitee_email,
user_name: domain::UserName::new(new_user.get_name())?,
@@ -934,6 +992,10 @@ async fn handle_new_user_invitation(
subject: consts::user::EMAIL_SUBJECT_INVITATION,
entity,
auth_id: auth_id.clone(),
+ theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
+ theme_config: theme
+ .map(|theme| theme.email_config())
+ .unwrap_or(state.conf.theme.email_config.clone()),
};
let send_email_result = state
.email_client
@@ -1055,6 +1117,21 @@ pub async fn resend_invite(
.get_entity_id_and_type()
.ok_or(UserErrors::InternalServerError)?;
+ let invitee_role_info = roles::RoleInfo::from_role_id_and_org_id(
+ &state,
+ &user_role.role_id,
+ &user_from_token.org_id,
+ )
+ .await
+ .change_context(UserErrors::InternalServerError)?;
+
+ let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity(
+ &state,
+ &user_from_token,
+ invitee_role_info.get_entity_type(),
+ )
+ .await?;
+
let email_contents = email_types::InviteUser {
recipient_email: invitee_email,
user_name: domain::UserName::new(user.get_name())?,
@@ -1065,6 +1142,10 @@ pub async fn resend_invite(
entity_type,
},
auth_id: auth_id.clone(),
+ theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
+ theme_config: theme
+ .map(|theme| theme.email_config())
+ .unwrap_or(state.conf.theme.email_config.clone()),
};
state
@@ -1666,6 +1747,7 @@ pub async fn send_verification_mail(
state: SessionState,
req: user_api::SendVerifyEmailRequest,
auth_id: Option<String>,
+ theme_id: Option<String>,
) -> UserResponse<()> {
let user_email = domain::UserEmail::try_from(req.email)?;
let user = state
@@ -1684,11 +1766,17 @@ pub async fn send_verification_mail(
return Err(UserErrors::UserAlreadyVerified.into());
}
+ let theme = theme_utils::get_theme_using_optional_theme_id(&state, theme_id).await?;
+
let email_contents = email_types::VerifyEmail {
recipient_email: domain::UserEmail::from_pii_email(user.email)?,
settings: state.conf.clone(),
subject: consts::user::EMAIL_SUBJECT_SIGNUP,
auth_id,
+ theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
+ theme_config: theme
+ .map(|theme| theme.email_config())
+ .unwrap_or(state.conf.theme.email_config.clone()),
};
state
diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rs
index a64b0f39dc0..88380363b4e 100644
--- a/crates/router/src/core/user/dashboard_metadata.rs
+++ b/crates/router/src/core/user/dashboard_metadata.rs
@@ -1,4 +1,6 @@
use api_models::user::dashboard_metadata::{self as api, GetMultipleMetaDataPayload};
+#[cfg(feature = "email")]
+use common_enums::EntityType;
use diesel_models::{
enums::DashboardMetadata as DBEnum, user::dashboard_metadata::DashboardMetadata,
};
@@ -8,8 +10,6 @@ use masking::ExposeInterface;
#[cfg(feature = "email")]
use router_env::logger;
-#[cfg(feature = "email")]
-use crate::services::email::types as email_types;
use crate::{
core::errors::{UserErrors, UserResponse, UserResult},
routes::{app::ReqState, SessionState},
@@ -17,6 +17,8 @@ use crate::{
types::domain::{self, user::dashboard_metadata as types, MerchantKeyStore},
utils::user::dashboard_metadata as utils,
};
+#[cfg(feature = "email")]
+use crate::{services::email::types as email_types, utils::user::theme as theme_utils};
pub async fn set_metadata(
state: SessionState,
@@ -476,7 +478,21 @@ async fn insert_metadata(
.expose();
if utils::is_prod_email_required(&data, user_email) {
- let email_contents = email_types::BizEmailProd::new(state, data)?;
+ let theme = theme_utils::get_most_specific_theme_using_token_and_min_entity(
+ state,
+ &user,
+ EntityType::Merchant,
+ )
+ .await?;
+
+ let email_contents = email_types::BizEmailProd::new(
+ state,
+ data,
+ theme.as_ref().map(|theme| theme.theme_id.clone()),
+ theme
+ .map(|theme| theme.email_config())
+ .unwrap_or(state.conf.theme.email_config.clone()),
+ )?;
let send_email_result = state
.email_client
.compose_and_send_email(
diff --git a/crates/router/src/core/user/theme.rs b/crates/router/src/core/user/theme.rs
index dbf11256a50..27b342d9053 100644
--- a/crates/router/src/core/user/theme.rs
+++ b/crates/router/src/core/user/theme.rs
@@ -38,6 +38,7 @@ pub async fn get_theme_using_lineage(
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
+ email_config: theme.email_config(),
theme_id: theme.theme_id,
theme_name: theme.theme_name,
entity_type: theme.entity_type,
@@ -71,6 +72,7 @@ pub async fn get_theme_using_theme_id(
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
+ email_config: theme.email_config(),
theme_id: theme.theme_id,
theme_name: theme.theme_name,
entity_type: theme.entity_type,
@@ -113,10 +115,19 @@ pub async fn create_theme(
) -> UserResponse<theme_api::GetThemeResponse> {
theme_utils::validate_lineage(&state, &request.lineage).await?;
+ let email_config = if cfg!(feature = "email") {
+ request.email_config.ok_or(UserErrors::MissingEmailConfig)?
+ } else {
+ request
+ .email_config
+ .unwrap_or(state.conf.theme.email_config.clone())
+ };
+
let new_theme = ThemeNew::new(
Uuid::new_v4().to_string(),
request.theme_name,
request.lineage,
+ email_config,
);
let db_theme = state
@@ -147,6 +158,7 @@ pub async fn create_theme(
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
+ email_config: db_theme.email_config(),
theme_id: db_theme.theme_id,
entity_type: db_theme.entity_type,
tenant_id: db_theme.tenant_id,
@@ -195,6 +207,7 @@ pub async fn update_theme(
.change_context(UserErrors::InternalServerError)?;
Ok(ApplicationResponse::Json(theme_api::GetThemeResponse {
+ email_config: db_theme.email_config(),
theme_id: db_theme.theme_id,
entity_type: db_theme.entity_type,
tenant_id: db_theme.tenant_id,
diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rs
index 2fd30a3610b..a7e71284aaf 100644
--- a/crates/router/src/db/kafka_store.rs
+++ b/crates/router/src/db/kafka_store.rs
@@ -3755,6 +3755,15 @@ impl ThemeInterface for KafkaStore {
self.diesel_store.find_theme_by_theme_id(theme_id).await
}
+ async fn find_most_specific_theme_in_lineage(
+ &self,
+ lineage: ThemeLineage,
+ ) -> CustomResult<diesel_models::user::theme::Theme, errors::StorageError> {
+ self.diesel_store
+ .find_most_specific_theme_in_lineage(lineage)
+ .await
+ }
+
async fn find_theme_by_lineage(
&self,
lineage: ThemeLineage,
diff --git a/crates/router/src/db/user/theme.rs b/crates/router/src/db/user/theme.rs
index 9b55a98d0ad..51c0a52b3a0 100644
--- a/crates/router/src/db/user/theme.rs
+++ b/crates/router/src/db/user/theme.rs
@@ -21,6 +21,11 @@ pub trait ThemeInterface {
theme_id: String,
) -> CustomResult<storage::Theme, errors::StorageError>;
+ async fn find_most_specific_theme_in_lineage(
+ &self,
+ lineage: ThemeLineage,
+ ) -> CustomResult<storage::Theme, errors::StorageError>;
+
async fn find_theme_by_lineage(
&self,
lineage: ThemeLineage,
@@ -56,6 +61,16 @@ impl ThemeInterface for Store {
.map_err(|error| report!(errors::StorageError::from(error)))
}
+ async fn find_most_specific_theme_in_lineage(
+ &self,
+ lineage: ThemeLineage,
+ ) -> CustomResult<storage::Theme, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::Theme::find_most_specific_theme_in_lineage(&conn, lineage)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
async fn find_theme_by_lineage(
&self,
lineage: ThemeLineage,
@@ -80,13 +95,12 @@ impl ThemeInterface for Store {
fn check_theme_with_lineage(theme: &storage::Theme, lineage: &ThemeLineage) -> bool {
match lineage {
- // TODO: Add back Tenant variant when we introduce Tenant Variant in EntityType
- // ThemeLineage::Tenant { tenant_id } => {
- // &theme.tenant_id == tenant_id
- // && theme.org_id.is_none()
- // && theme.merchant_id.is_none()
- // && theme.profile_id.is_none()
- // }
+ ThemeLineage::Tenant { tenant_id } => {
+ &theme.tenant_id == tenant_id
+ && theme.org_id.is_none()
+ && theme.merchant_id.is_none()
+ && theme.profile_id.is_none()
+ }
ThemeLineage::Organization { tenant_id, org_id } => {
&theme.tenant_id == tenant_id
&& theme
@@ -174,6 +188,11 @@ impl ThemeInterface for MockDb {
last_modified_at: new_theme.last_modified_at,
entity_type: new_theme.entity_type,
theme_name: new_theme.theme_name,
+ email_primary_color: new_theme.email_primary_color,
+ email_foreground_color: new_theme.email_foreground_color,
+ email_background_color: new_theme.email_background_color,
+ email_entity_name: new_theme.email_entity_name,
+ email_entity_logo_url: new_theme.email_entity_logo_url,
};
themes.push(theme.clone());
@@ -198,6 +217,27 @@ impl ThemeInterface for MockDb {
)
}
+ async fn find_most_specific_theme_in_lineage(
+ &self,
+ lineage: ThemeLineage,
+ ) -> CustomResult<storage::Theme, errors::StorageError> {
+ let themes = self.themes.lock().await;
+ let lineages = lineage.get_same_and_higher_lineages();
+
+ themes
+ .iter()
+ .filter(|theme| {
+ lineages
+ .iter()
+ .any(|lineage| check_theme_with_lineage(theme, lineage))
+ })
+ .min_by_key(|theme| theme.entity_type)
+ .ok_or(
+ errors::StorageError::ValueNotFound("No theme found in lineage".to_string()).into(),
+ )
+ .cloned()
+ }
+
async fn find_theme_by_lineage(
&self,
lineage: ThemeLineage,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index ca7c4847ad4..5f04581fbb3 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -369,7 +369,7 @@ impl AppState {
let email_client = Arc::new(create_email_client(&conf).await);
let file_storage_client = conf.file_storage.get_file_storage_client().await;
- let theme_storage_client = conf.theme_storage.get_file_storage_client().await;
+ let theme_storage_client = conf.theme.storage.get_file_storage_client().await;
let grpc_client = conf.grpc_client.get_grpc_client_interface().await;
diff --git a/crates/router/src/routes/user.rs b/crates/router/src/routes/user.rs
index c32746c8718..d075048ddb6 100644
--- a/crates/router/src/routes/user.rs
+++ b/crates/router/src/routes/user.rs
@@ -41,18 +41,23 @@ pub async fn user_signup_with_merchant_id(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SignUpWithMerchantIdRequest>,
- query: web::Query<user_api::AuthIdQueryParam>,
+ query: web::Query<user_api::AuthIdAndThemeIdQueryParam>,
) -> HttpResponse {
let flow = Flow::UserSignUpWithMerchantId;
let req_payload = json_payload.into_inner();
- let auth_id = query.into_inner().auth_id;
+ let query_params = query.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
|state, _, req_body, _| {
- user_core::signup_with_merchant_id(state, req_body, auth_id.clone())
+ user_core::signup_with_merchant_id(
+ state,
+ req_body,
+ query_params.auth_id.clone(),
+ query_params.theme_id.clone(),
+ )
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
@@ -107,17 +112,24 @@ pub async fn user_connect_account(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::ConnectAccountRequest>,
- query: web::Query<user_api::AuthIdQueryParam>,
+ query: web::Query<user_api::AuthIdAndThemeIdQueryParam>,
) -> HttpResponse {
let flow = Flow::UserConnectAccount;
let req_payload = json_payload.into_inner();
- let auth_id = query.into_inner().auth_id;
+ let query_params = query.into_inner();
Box::pin(api::server_wrap(
flow.clone(),
state,
&http_req,
req_payload.clone(),
- |state, _: (), req_body, _| user_core::connect_account(state, req_body, auth_id.clone()),
+ |state, _: (), req_body, _| {
+ user_core::connect_account(
+ state,
+ req_body,
+ query_params.auth_id.clone(),
+ query_params.theme_id.clone(),
+ )
+ },
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
@@ -381,16 +393,23 @@ pub async fn forgot_password(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::ForgotPasswordRequest>,
- query: web::Query<user_api::AuthIdQueryParam>,
+ query: web::Query<user_api::AuthIdAndThemeIdQueryParam>,
) -> HttpResponse {
let flow = Flow::ForgotPassword;
- let auth_id = query.into_inner().auth_id;
+ let query_params = query.into_inner();
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
payload.into_inner(),
- |state, _: (), payload, _| user_core::forgot_password(state, payload, auth_id.clone()),
+ |state, _: (), payload, _| {
+ user_core::forgot_password(
+ state,
+ payload,
+ query_params.auth_id.clone(),
+ query_params.theme_id.clone(),
+ )
+ },
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
))
@@ -420,7 +439,7 @@ pub async fn invite_multiple_user(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<Vec<user_api::InviteUserRequest>>,
- auth_id_query_param: web::Query<user_api::AuthIdQueryParam>,
+ auth_id_query_param: web::Query<user_api::AuthIdAndThemeIdQueryParam>,
) -> HttpResponse {
let flow = Flow::InviteMultipleUser;
let auth_id = auth_id_query_param.into_inner().auth_id;
@@ -445,7 +464,7 @@ pub async fn resend_invite(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<user_api::ReInviteUserRequest>,
- query: web::Query<user_api::AuthIdQueryParam>,
+ query: web::Query<user_api::AuthIdAndThemeIdQueryParam>,
) -> HttpResponse {
let flow = Flow::ReInviteUser;
let auth_id = query.into_inner().auth_id;
@@ -512,17 +531,22 @@ pub async fn verify_email_request(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::SendVerifyEmailRequest>,
- query: web::Query<user_api::AuthIdQueryParam>,
+ query: web::Query<user_api::AuthIdAndThemeIdQueryParam>,
) -> HttpResponse {
let flow = Flow::VerifyEmailRequest;
- let auth_id = query.into_inner().auth_id;
+ let query_params = query.into_inner();
Box::pin(api::server_wrap(
flow,
state.clone(),
&http_req,
json_payload.into_inner(),
|state, _: (), req_body, _| {
- user_core::send_verification_mail(state, req_body, auth_id.clone())
+ user_core::send_verification_mail(
+ state,
+ req_body,
+ query_params.auth_id.clone(),
+ query_params.theme_id.clone(),
+ )
},
&auth::NoAuth,
api_locking::LockAction::NotApplicable,
diff --git a/crates/router/src/services/email/types.rs b/crates/router/src/services/email/types.rs
index 66e730f0824..128250a61aa 100644
--- a/crates/router/src/services/email/types.rs
+++ b/crates/router/src/services/email/types.rs
@@ -1,6 +1,6 @@
use api_models::user::dashboard_metadata::ProdIntent;
use common_enums::EntityType;
-use common_utils::{errors::CustomResult, pii};
+use common_utils::{errors::CustomResult, pii, types::theme::EmailThemeConfig};
use error_stack::ResultExt;
use external_services::email::{EmailContents, EmailData, EmailError};
use masking::{ExposeInterface, Secret};
@@ -212,13 +212,17 @@ pub fn get_link_with_token(
token: impl std::fmt::Display,
action: impl std::fmt::Display,
auth_id: &Option<impl std::fmt::Display>,
+ theme_id: &Option<impl std::fmt::Display>,
) -> String {
- let email_url = format!("{base_url}/user/{action}?token={token}");
+ let mut email_url = format!("{base_url}/user/{action}?token={token}");
if let Some(auth_id) = auth_id {
- format!("{email_url}&auth_id={auth_id}")
- } else {
- email_url
+ email_url = format!("{email_url}&auth_id={auth_id}");
}
+ if let Some(theme_id) = theme_id {
+ email_url = format!("{email_url}&theme_id={theme_id}");
+ }
+
+ email_url
}
pub struct VerifyEmail {
@@ -226,6 +230,8 @@ pub struct VerifyEmail {
pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
pub auth_id: Option<String>,
+ pub theme_id: Option<String>,
+ pub theme_config: EmailThemeConfig,
}
/// Currently only HTML is supported
@@ -246,6 +252,7 @@ impl EmailData for VerifyEmail {
token,
"verify_email",
&self.auth_id,
+ &self.theme_id,
);
let body = html::get_html_body(EmailBody::Verify {
@@ -266,6 +273,8 @@ pub struct ResetPassword {
pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
pub auth_id: Option<String>,
+ pub theme_id: Option<String>,
+ pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
@@ -285,6 +294,7 @@ impl EmailData for ResetPassword {
token,
"set_password",
&self.auth_id,
+ &self.theme_id,
);
let body = html::get_html_body(EmailBody::Reset {
@@ -306,6 +316,8 @@ pub struct MagicLink {
pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
pub auth_id: Option<String>,
+ pub theme_id: Option<String>,
+ pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
@@ -325,6 +337,7 @@ impl EmailData for MagicLink {
token,
"verify_email",
&self.auth_id,
+ &self.theme_id,
);
let body = html::get_html_body(EmailBody::MagicLink {
@@ -347,6 +360,8 @@ pub struct InviteUser {
pub subject: &'static str,
pub entity: Entity,
pub auth_id: Option<String>,
+ pub theme_id: Option<String>,
+ pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
@@ -366,6 +381,7 @@ impl EmailData for InviteUser {
token,
"accept_invite_from_email",
&self.auth_id,
+ &self.theme_id,
);
let body = html::get_html_body(EmailBody::AcceptInviteFromEmail {
link: invite_user_link,
@@ -384,6 +400,8 @@ pub struct ReconActivation {
pub recipient_email: domain::UserEmail,
pub user_name: domain::UserName,
pub subject: &'static str,
+ pub theme_id: Option<String>,
+ pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
@@ -410,10 +428,17 @@ pub struct BizEmailProd {
pub business_website: String,
pub settings: std::sync::Arc<configs::Settings>,
pub subject: &'static str,
+ pub theme_id: Option<String>,
+ pub theme_config: EmailThemeConfig,
}
impl BizEmailProd {
- pub fn new(state: &SessionState, data: ProdIntent) -> UserResult<Self> {
+ pub fn new(
+ state: &SessionState,
+ data: ProdIntent,
+ theme_id: Option<String>,
+ theme_config: EmailThemeConfig,
+ ) -> UserResult<Self> {
Ok(Self {
recipient_email: domain::UserEmail::from_pii_email(
state.conf.email.prod_intent_recipient_email.clone(),
@@ -428,6 +453,8 @@ impl BizEmailProd {
.unwrap_or(common_enums::CountryAlpha2::AD)
.to_string(),
business_website: data.business_website.unwrap_or_default(),
+ theme_id,
+ theme_config,
})
}
}
@@ -458,6 +485,8 @@ pub struct ProFeatureRequest {
pub user_name: domain::UserName,
pub user_email: domain::UserEmail,
pub subject: String,
+ pub theme_id: Option<String>,
+ pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
@@ -486,6 +515,8 @@ pub struct ApiKeyExpiryReminder {
pub expires_in: u8,
pub api_key_name: String,
pub prefix: String,
+ pub theme_id: Option<String>,
+ pub theme_config: EmailThemeConfig,
}
#[async_trait::async_trait]
diff --git a/crates/router/src/utils/user/theme.rs b/crates/router/src/utils/user/theme.rs
index 13452380d9d..1c8b76989ae 100644
--- a/crates/router/src/utils/user/theme.rs
+++ b/crates/router/src/utils/user/theme.rs
@@ -1,12 +1,15 @@
use std::path::PathBuf;
-use common_utils::{id_type, types::theme::ThemeLineage};
+use common_enums::EntityType;
+use common_utils::{ext_traits::AsyncExt, id_type, types::theme::ThemeLineage};
+use diesel_models::user::theme::Theme;
use error_stack::ResultExt;
use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
use crate::{
core::errors::{StorageErrorExt, UserErrors, UserResult},
routes::SessionState,
+ services::authentication::UserFromToken,
};
fn get_theme_dir_key(theme_id: &str) -> PathBuf {
@@ -54,6 +57,10 @@ pub async fn upload_file_to_theme_bucket(
pub async fn validate_lineage(state: &SessionState, lineage: &ThemeLineage) -> UserResult<()> {
match lineage {
+ ThemeLineage::Tenant { tenant_id } => {
+ validate_tenant(state, tenant_id)?;
+ Ok(())
+ }
ThemeLineage::Organization { tenant_id, org_id } => {
validate_tenant(state, tenant_id)?;
validate_org(state, org_id).await?;
@@ -96,8 +103,8 @@ async fn validate_org(state: &SessionState, org_id: &id_type::OrganizationId) ->
.store
.find_organization_by_org_id(org_id)
.await
- .to_not_found_response(UserErrors::InvalidThemeLineage("org_id".to_string()))?;
- Ok(())
+ .to_not_found_response(UserErrors::InvalidThemeLineage("org_id".to_string()))
+ .map(|_| ())
}
async fn validate_merchant_and_get_key_store(
@@ -153,6 +160,67 @@ async fn validate_profile(
profile_id,
)
.await
- .to_not_found_response(UserErrors::InvalidThemeLineage("profile_id".to_string()))?;
- Ok(())
+ .to_not_found_response(UserErrors::InvalidThemeLineage("profile_id".to_string()))
+ .map(|_| ())
+}
+
+pub async fn get_most_specific_theme_using_token_and_min_entity(
+ state: &SessionState,
+ user_from_token: &UserFromToken,
+ min_entity: EntityType,
+) -> UserResult<Option<Theme>> {
+ get_most_specific_theme_using_lineage(
+ state,
+ ThemeLineage::new(
+ min_entity,
+ user_from_token
+ .tenant_id
+ .clone()
+ .unwrap_or(state.tenant.tenant_id.clone()),
+ user_from_token.org_id.clone(),
+ user_from_token.merchant_id.clone(),
+ user_from_token.profile_id.clone(),
+ ),
+ )
+ .await
+}
+
+pub async fn get_most_specific_theme_using_lineage(
+ state: &SessionState,
+ lineage: ThemeLineage,
+) -> UserResult<Option<Theme>> {
+ match state
+ .global_store
+ .find_most_specific_theme_in_lineage(lineage)
+ .await
+ {
+ Ok(theme) => Ok(Some(theme)),
+ Err(e) => {
+ if e.current_context().is_db_not_found() {
+ Ok(None)
+ } else {
+ Err(e.change_context(UserErrors::InternalServerError))
+ }
+ }
+ }
+}
+
+pub async fn get_theme_using_optional_theme_id(
+ state: &SessionState,
+ theme_id: Option<String>,
+) -> UserResult<Option<Theme>> {
+ match theme_id
+ .async_map(|theme_id| state.global_store.find_theme_by_theme_id(theme_id))
+ .await
+ .transpose()
+ {
+ Ok(theme) => Ok(theme),
+ Err(e) => {
+ if e.current_context().is_db_not_found() {
+ Ok(None)
+ } else {
+ Err(e.change_context(UserErrors::InternalServerError))
+ }
+ }
+ }
}
diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rs
index bf6100179bf..cdc4959c456 100644
--- a/crates/router/src/workflows/api_key_expiry.rs
+++ b/crates/router/src/workflows/api_key_expiry.rs
@@ -1,4 +1,4 @@
-use common_utils::{errors::ValidationError, ext_traits::ValueExt};
+use common_utils::{errors::ValidationError, ext_traits::ValueExt, types::theme::ThemeLineage};
use diesel_models::{
enums as storage_enums, process_tracker::business_status, ApiKeyExpiryTrackingData,
};
@@ -11,7 +11,7 @@ use crate::{
routes::{metrics, SessionState},
services::email::types::ApiKeyExpiryReminder,
types::{api, domain::UserEmail, storage},
- utils::OptionExt,
+ utils::{user::theme as theme_utils, OptionExt},
};
pub struct ApiKeyExpiryWorkflow;
@@ -48,6 +48,7 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow {
let email_id = merchant_account
.merchant_details
+ .clone()
.parse_value::<api::MerchantDetails>("MerchantDetails")?
.primary_email
.ok_or(errors::ProcessTrackerError::EValidationError(
@@ -73,6 +74,20 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow {
)
.ok_or(errors::ProcessTrackerError::EApiErrorResponse)?;
+ let theme = theme_utils::get_most_specific_theme_using_lineage(
+ state,
+ ThemeLineage::Merchant {
+ tenant_id: state.tenant.tenant_id.clone(),
+ org_id: merchant_account.get_org_id().clone(),
+ merchant_id: merchant_account.get_id().clone(),
+ },
+ )
+ .await
+ .map_err(|err| {
+ logger::error!(?err, "Failed to get theme");
+ errors::ProcessTrackerError::EApiErrorResponse
+ })?;
+
let email_contents = ApiKeyExpiryReminder {
recipient_email: UserEmail::from_pii_email(email_id).map_err(|error| {
logger::error!(
@@ -85,6 +100,10 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow {
expires_in: *expires_in,
api_key_name,
prefix,
+ theme_id: theme.as_ref().map(|theme| theme.theme_id.clone()),
+ theme_config: theme
+ .map(|theme| theme.email_config())
+ .unwrap_or(state.conf.theme.email_config.clone()),
};
state
diff --git a/migrations/2024-12-05-131123_add-email-theme-data-in-themes/down.sql b/migrations/2024-12-05-131123_add-email-theme-data-in-themes/down.sql
new file mode 100644
index 00000000000..34732b5dd69
--- /dev/null
+++ b/migrations/2024-12-05-131123_add-email-theme-data-in-themes/down.sql
@@ -0,0 +1,6 @@
+-- This file should undo anything in `up.sql`
+ALTER TABLE themes DROP COLUMN IF EXISTS email_primary_color;
+ALTER TABLE themes DROP COLUMN IF EXISTS email_foreground_color;
+ALTER TABLE themes DROP COLUMN IF EXISTS email_background_color;
+ALTER TABLE themes DROP COLUMN IF EXISTS email_entity_name;
+ALTER TABLE themes DROP COLUMN IF EXISTS email_entity_logo_url;
diff --git a/migrations/2024-12-05-131123_add-email-theme-data-in-themes/up.sql b/migrations/2024-12-05-131123_add-email-theme-data-in-themes/up.sql
new file mode 100644
index 00000000000..1004302ab7f
--- /dev/null
+++ b/migrations/2024-12-05-131123_add-email-theme-data-in-themes/up.sql
@@ -0,0 +1,6 @@
+-- Your SQL goes here
+ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_primary_color VARCHAR(64) NOT NULL DEFAULT '#006DF9';
+ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_foreground_color VARCHAR(64) NOT NULL DEFAULT '#000000';
+ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_background_color VARCHAR(64) NOT NULL DEFAULT '#FFFFFF';
+ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_entity_name VARCHAR(64) NOT NULL DEFAULT 'Hyperswitch';
+ALTER TABLE themes ADD COLUMN IF NOT EXISTS email_entity_logo_url TEXT NOT NULL DEFAULT 'https://app.hyperswitch.io/email-assets/HyperswitchLogo.png';
|
feat
|
Incorporate themes in user APIs (#6772)
|
9f446bc1742c06a7fab3d92128ba4e7d3be80ea6
|
2023-10-12 12:12:51
|
Sai Harsha Vardhan
|
feat(router): add kv implementation for update address in update payments flow (#2542)
| false
|
diff --git a/crates/diesel_models/src/address.rs b/crates/diesel_models/src/address.rs
index 028d878f7da..569df3f551c 100644
--- a/crates/diesel_models/src/address.rs
+++ b/crates/diesel_models/src/address.rs
@@ -49,7 +49,7 @@ pub struct Address {
pub payment_id: Option<String>,
}
-#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
+#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, Serialize, Deserialize)]
#[diesel(table_name = address)]
pub struct AddressUpdateInternal {
pub city: Option<String>,
diff --git a/crates/diesel_models/src/kv.rs b/crates/diesel_models/src/kv.rs
index 93d045bd71a..ed886c783f9 100644
--- a/crates/diesel_models/src/kv.rs
+++ b/crates/diesel_models/src/kv.rs
@@ -2,7 +2,7 @@ use error_stack::{IntoReport, ResultExt};
use serde::{Deserialize, Serialize};
use crate::{
- address::AddressNew,
+ address::{Address, AddressNew, AddressUpdateInternal},
connector_response::{ConnectorResponse, ConnectorResponseNew, ConnectorResponseUpdate},
errors,
payment_attempt::{PaymentAttempt, PaymentAttemptNew, PaymentAttemptUpdate},
@@ -54,6 +54,7 @@ pub enum Updateable {
PaymentAttemptUpdate(PaymentAttemptUpdateMems),
RefundUpdate(RefundUpdateMems),
ConnectorResponseUpdate(ConnectorResponseUpdateMems),
+ AddressUpdate(Box<AddressUpdateMems>),
}
#[derive(Debug, Serialize, Deserialize)]
@@ -62,6 +63,12 @@ pub struct ConnectorResponseUpdateMems {
pub update_data: ConnectorResponseUpdate,
}
+#[derive(Debug, Serialize, Deserialize)]
+pub struct AddressUpdateMems {
+ pub orig: Address,
+ pub update_data: AddressUpdateInternal,
+}
+
#[derive(Debug, Serialize, Deserialize)]
pub struct PaymentIntentUpdateMems {
pub orig: PaymentIntent,
diff --git a/crates/diesel_models/src/query/address.rs b/crates/diesel_models/src/query/address.rs
index 9a4f20942cc..ada47622990 100644
--- a/crates/diesel_models/src/query/address.rs
+++ b/crates/diesel_models/src/query/address.rs
@@ -56,6 +56,32 @@ impl Address {
}
}
+ #[instrument(skip(conn))]
+ pub async fn update(
+ self,
+ conn: &PgPooledConn,
+ address_update_internal: AddressUpdateInternal,
+ ) -> StorageResult<Self> {
+ match generics::generic_update_with_unique_predicate_get_result::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(
+ conn,
+ dsl::address_id.eq(self.address_id.clone()),
+ address_update_internal,
+ )
+ .await
+ {
+ Err(error) => match error.current_context() {
+ errors::DatabaseError::NoFieldsToUpdate => Ok(self),
+ _ => Err(error),
+ },
+ result => result,
+ }
+ }
+
#[instrument(skip(conn))]
pub async fn delete_by_address_id(
conn: &PgPooledConn,
diff --git a/crates/drainer/src/lib.rs b/crates/drainer/src/lib.rs
index e09c5654057..632fb4a0c14 100644
--- a/crates/drainer/src/lib.rs
+++ b/crates/drainer/src/lib.rs
@@ -271,6 +271,11 @@ async fn drainer(
update_op,
connector_response
),
+ kv::Updateable::AddressUpdate(a) => macro_util::handle_resp!(
+ a.orig.update(&conn, a.update_data).await,
+ update_op,
+ address
+ ),
}
})
.await;
diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rs
index 143b9923958..a4cb7b2b9e6 100644
--- a/crates/router/src/core/payments/helpers.rs
+++ b/crates/router/src/core/payments/helpers.rs
@@ -181,10 +181,27 @@ pub async fn create_or_update_address_for_payment_by_request(
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting address")?;
+ let address = db
+ .find_address_by_merchant_id_payment_id_address_id(
+ merchant_id,
+ payment_id,
+ id,
+ merchant_key_store,
+ storage_scheme,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Error while fetching address")?;
Some(
- db.update_address(id.to_owned(), address_update, merchant_key_store)
- .await
- .to_not_found_response(errors::ApiErrorResponse::AddressNotFound)?,
+ db.update_address_for_payments(
+ address,
+ address_update,
+ payment_id.to_string(),
+ merchant_key_store,
+ storage_scheme,
+ )
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::AddressNotFound)?,
)
}
None => Some(
diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rs
index dda6838c973..0b7bffda2f8 100644
--- a/crates/router/src/db/address.rs
+++ b/crates/router/src/db/address.rs
@@ -28,6 +28,15 @@ where
key_store: &domain::MerchantKeyStore,
) -> CustomResult<domain::Address, errors::StorageError>;
+ async fn update_address_for_payments(
+ &self,
+ this: domain::Address,
+ address: domain::AddressUpdate,
+ payment_id: String,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::Address, errors::StorageError>;
+
async fn find_address_by_address_id(
&self,
address_id: &str,
@@ -155,6 +164,32 @@ mod storage {
.await
}
+ async fn update_address_for_payments(
+ &self,
+ this: domain::Address,
+ address_update: domain::AddressUpdate,
+ _payment_id: String,
+ key_store: &domain::MerchantKeyStore,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::Address, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ let address = Conversion::convert(this)
+ .await
+ .change_context(errors::StorageError::EncryptionError)?;
+ address
+ .update(&conn, address_update.into())
+ .await
+ .map_err(Into::into)
+ .into_report()
+ .async_and_then(|address| async {
+ address
+ .convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await
+ }
+
async fn insert_address_for_payments(
&self,
_payment_id: &str,
@@ -241,6 +276,7 @@ mod storage {
mod storage {
use common_utils::ext_traits::AsyncExt;
use data_models::MerchantStorageScheme;
+ use diesel_models::AddressUpdateInternal;
use error_stack::{IntoReport, ResultExt};
use redis_interface::HsetnxReply;
use router_env::{instrument, tracing};
@@ -348,6 +384,79 @@ mod storage {
.await
}
+ async fn update_address_for_payments(
+ &self,
+ this: domain::Address,
+ address_update: domain::AddressUpdate,
+ payment_id: String,
+ key_store: &domain::MerchantKeyStore,
+ storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::Address, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ let address = Conversion::convert(this)
+ .await
+ .change_context(errors::StorageError::EncryptionError)?;
+ match storage_scheme {
+ MerchantStorageScheme::PostgresOnly => {
+ address
+ .update(&conn, address_update.into())
+ .await
+ .map_err(Into::into)
+ .into_report()
+ .async_and_then(|address| async {
+ address
+ .convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ })
+ .await
+ }
+ MerchantStorageScheme::RedisKv => {
+ let key = format!("mid_{}_pid_{}", address.merchant_id.clone(), payment_id);
+ let field = format!("add_{}", address.address_id);
+ let updated_address = AddressUpdateInternal::from(address_update.clone())
+ .create_address(address.clone());
+ let redis_value = serde_json::to_string(&updated_address)
+ .into_report()
+ .change_context(errors::StorageError::KVError)?;
+ kv_wrapper::<(), _, _>(
+ self,
+ KvOperation::Hset::<storage_types::Address>((&field, redis_value)),
+ &key,
+ )
+ .await
+ .change_context(errors::StorageError::KVError)?
+ .try_into_hset()
+ .change_context(errors::StorageError::KVError)?;
+
+ let redis_entry = kv::TypedSql {
+ op: kv::DBOperation::Update {
+ updatable: kv::Updateable::AddressUpdate(Box::new(
+ kv::AddressUpdateMems {
+ orig: address,
+ update_data: address_update.into(),
+ },
+ )),
+ },
+ };
+
+ self.push_to_drainer_stream::<storage_types::Address>(
+ redis_entry,
+ PartitionKey::MerchantIdPaymentId {
+ merchant_id: &updated_address.merchant_id,
+ payment_id: &payment_id,
+ },
+ )
+ .await
+ .change_context(errors::StorageError::KVError)?;
+ updated_address
+ .convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError)
+ }
+ }
+ }
+
async fn insert_address_for_payments(
&self,
payment_id: &str,
@@ -584,6 +693,37 @@ impl AddressInterface for MockDb {
}
}
+ async fn update_address_for_payments(
+ &self,
+ this: domain::Address,
+ address_update: domain::AddressUpdate,
+ _payment_id: String,
+ key_store: &domain::MerchantKeyStore,
+ _storage_scheme: MerchantStorageScheme,
+ ) -> CustomResult<domain::Address, errors::StorageError> {
+ match self
+ .addresses
+ .lock()
+ .await
+ .iter_mut()
+ .find(|address| address.address_id == this.address_id)
+ .map(|a| {
+ let address_updated =
+ AddressUpdateInternal::from(address_update).create_address(a.clone());
+ *a = address_updated.clone();
+ address_updated
+ }) {
+ Some(address_updated) => address_updated
+ .convert(key_store.key.get_inner())
+ .await
+ .change_context(errors::StorageError::DecryptionError),
+ None => Err(errors::StorageError::ValueNotFound(
+ "cannot find address to update".to_string(),
+ )
+ .into()),
+ }
+ }
+
async fn insert_address_for_payments(
&self,
_payment_id: &str,
diff --git a/crates/router/src/types/domain/address.rs b/crates/router/src/types/domain/address.rs
index fadd83b34e0..bd9d034e8c9 100644
--- a/crates/router/src/types/domain/address.rs
+++ b/crates/router/src/types/domain/address.rs
@@ -125,7 +125,7 @@ impl behaviour::Conversion for Address {
}
}
-#[derive(Debug)]
+#[derive(Debug, Clone)]
pub enum AddressUpdate {
Update {
city: Option<String>,
diff --git a/crates/router/src/types/storage/kv.rs b/crates/router/src/types/storage/kv.rs
index 51c9eb2b42e..2afc73e6637 100644
--- a/crates/router/src/types/storage/kv.rs
+++ b/crates/router/src/types/storage/kv.rs
@@ -1,4 +1,4 @@
pub use diesel_models::kv::{
- ConnectorResponseUpdateMems, DBOperation, Insertable, PaymentAttemptUpdateMems,
- PaymentIntentUpdateMems, RefundUpdateMems, TypedSql, Updateable,
+ AddressUpdateMems, ConnectorResponseUpdateMems, DBOperation, Insertable,
+ PaymentAttemptUpdateMems, PaymentIntentUpdateMems, RefundUpdateMems, TypedSql, Updateable,
};
|
feat
|
add kv implementation for update address in update payments flow (#2542)
|
68aac34eb38189427f34753a108478f7e8f8b420
|
2025-03-21 17:04:41
|
Prajjwal Kumar
|
refactor(dynamic_routing): change insert operation to upsert for dynamic_routing_stats (#7398)
| false
|
diff --git a/crates/diesel_models/src/dynamic_routing_stats.rs b/crates/diesel_models/src/dynamic_routing_stats.rs
index 90cf4689080..f60db1e9fbf 100644
--- a/crates/diesel_models/src/dynamic_routing_stats.rs
+++ b/crates/diesel_models/src/dynamic_routing_stats.rs
@@ -1,4 +1,4 @@
-use diesel::{Insertable, Queryable, Selectable};
+use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use crate::schema::dynamic_routing_stats;
@@ -23,8 +23,8 @@ pub struct DynamicRoutingStatsNew {
pub global_success_based_connector: Option<String>,
}
-#[derive(Clone, Debug, Eq, PartialEq, Queryable, Selectable, Insertable)]
-#[diesel(table_name = dynamic_routing_stats, primary_key(payment_id), check_for_backend(diesel::pg::Pg))]
+#[derive(Clone, Debug, Eq, PartialEq, Identifiable, Queryable, Selectable, Insertable)]
+#[diesel(table_name = dynamic_routing_stats, primary_key(attempt_id, merchant_id), check_for_backend(diesel::pg::Pg))]
pub struct DynamicRoutingStats {
pub payment_id: common_utils::id_type::PaymentId,
pub attempt_id: String,
@@ -43,3 +43,21 @@ pub struct DynamicRoutingStats {
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub global_success_based_connector: Option<String>,
}
+
+#[derive(
+ Clone, Debug, Eq, PartialEq, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize,
+)]
+#[diesel(table_name = dynamic_routing_stats)]
+pub struct DynamicRoutingStatsUpdate {
+ pub amount: common_utils::types::MinorUnit,
+ pub success_based_routing_connector: String,
+ pub payment_connector: String,
+ pub currency: Option<common_enums::Currency>,
+ pub payment_method: Option<common_enums::PaymentMethod>,
+ pub capture_method: Option<common_enums::CaptureMethod>,
+ pub authentication_type: Option<common_enums::AuthenticationType>,
+ pub payment_status: common_enums::AttemptStatus,
+ pub conclusive_classification: common_enums::SuccessBasedRoutingConclusiveState,
+ pub payment_method_type: Option<common_enums::PaymentMethodType>,
+ pub global_success_based_connector: Option<String>,
+}
diff --git a/crates/diesel_models/src/query/dynamic_routing_stats.rs b/crates/diesel_models/src/query/dynamic_routing_stats.rs
index f6771cd103d..bf4cd706a69 100644
--- a/crates/diesel_models/src/query/dynamic_routing_stats.rs
+++ b/crates/diesel_models/src/query/dynamic_routing_stats.rs
@@ -1,6 +1,13 @@
+use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
+use error_stack::report;
+
use super::generics;
use crate::{
- dynamic_routing_stats::{DynamicRoutingStats, DynamicRoutingStatsNew},
+ dynamic_routing_stats::{
+ DynamicRoutingStats, DynamicRoutingStatsNew, DynamicRoutingStatsUpdate,
+ },
+ errors,
+ schema::dynamic_routing_stats::dsl,
PgPooledConn, StorageResult,
};
@@ -9,3 +16,46 @@ impl DynamicRoutingStatsNew {
generics::generic_insert(conn, self).await
}
}
+
+impl DynamicRoutingStats {
+ pub async fn find_optional_by_attempt_id_merchant_id(
+ conn: &PgPooledConn,
+ attempt_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> StorageResult<Option<Self>> {
+ generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::attempt_id.eq(attempt_id.to_owned())),
+ )
+ .await
+ }
+
+ pub async fn update(
+ conn: &PgPooledConn,
+ attempt_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
+ dynamic_routing_stat: DynamicRoutingStatsUpdate,
+ ) -> StorageResult<Self> {
+ generics::generic_update_with_results::<
+ <Self as HasTable>::Table,
+ DynamicRoutingStatsUpdate,
+ _,
+ _,
+ >(
+ conn,
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::attempt_id.eq(attempt_id.to_owned())),
+ dynamic_routing_stat,
+ )
+ .await?
+ .first()
+ .cloned()
+ .ok_or_else(|| {
+ report!(errors::DatabaseError::NotFound)
+ .attach_printable("Error while updating dynamic_routing_stats entry")
+ })
+ }
+}
diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rs
index 1d40039e2a3..e80ddbead4c 100644
--- a/crates/router/src/core/routing/helpers.rs
+++ b/crates/router/src/core/routing/helpers.rs
@@ -14,7 +14,7 @@ use common_utils::ext_traits::ValueExt;
use common_utils::{ext_traits::Encode, id_type, types::keymanager::KeyManagerState};
use diesel_models::configs;
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
-use diesel_models::dynamic_routing_stats::DynamicRoutingStatsNew;
+use diesel_models::dynamic_routing_stats::{DynamicRoutingStatsNew, DynamicRoutingStatsUpdate};
#[cfg(all(feature = "dynamic_routing", feature = "v1"))]
use diesel_models::routing_algorithm;
use error_stack::ResultExt;
@@ -821,28 +821,6 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
first_merchant_success_based_connector_label.to_string(),
);
- let dynamic_routing_stats = DynamicRoutingStatsNew {
- payment_id: payment_attempt.payment_id.to_owned(),
- attempt_id: payment_attempt.attempt_id.clone(),
- merchant_id: payment_attempt.merchant_id.to_owned(),
- profile_id: payment_attempt.profile_id.to_owned(),
- amount: payment_attempt.get_total_amount(),
- success_based_routing_connector: first_merchant_success_based_connector_label
- .to_string(),
- payment_connector: payment_connector.to_string(),
- payment_method_type: payment_attempt.payment_method_type,
- currency: payment_attempt.currency,
- payment_method: payment_attempt.payment_method,
- capture_method: payment_attempt.capture_method,
- authentication_type: payment_attempt.authentication_type,
- payment_status: payment_attempt.status,
- conclusive_classification: outcome,
- created_at: common_utils::date_time::now(),
- global_success_based_connector: Some(
- first_global_success_based_connector.label.to_string(),
- ),
- };
-
core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(
1,
router_env::metric_attributes!(
@@ -915,12 +893,74 @@ pub async fn push_metrics_with_update_window_for_success_based_routing(
);
logger::debug!("successfully pushed success_based_routing metrics");
- state
+ let duplicate_stats = state
.store
- .insert_dynamic_routing_stat_entry(dynamic_routing_stats)
+ .find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
+ payment_attempt.attempt_id.clone(),
+ &payment_attempt.merchant_id.to_owned(),
+ )
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Unable to push dynamic routing stats to db")?;
+ .attach_printable("Failed to fetch dynamic_routing_stats entry")?;
+
+ if duplicate_stats.is_some() {
+ let dynamic_routing_update = DynamicRoutingStatsUpdate {
+ amount: payment_attempt.get_total_amount(),
+ success_based_routing_connector: first_merchant_success_based_connector_label
+ .to_string(),
+ payment_connector: payment_connector.to_string(),
+ payment_method_type: payment_attempt.payment_method_type,
+ currency: payment_attempt.currency,
+ payment_method: payment_attempt.payment_method,
+ capture_method: payment_attempt.capture_method,
+ authentication_type: payment_attempt.authentication_type,
+ payment_status: payment_attempt.status,
+ conclusive_classification: outcome,
+ global_success_based_connector: Some(
+ first_global_success_based_connector.label.to_string(),
+ ),
+ };
+
+ state
+ .store
+ .update_dynamic_routing_stats(
+ payment_attempt.attempt_id.clone(),
+ &payment_attempt.merchant_id.to_owned(),
+ dynamic_routing_update,
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to update dynamic routing stats to db")?;
+ } else {
+ let dynamic_routing_stats = DynamicRoutingStatsNew {
+ payment_id: payment_attempt.payment_id.to_owned(),
+ attempt_id: payment_attempt.attempt_id.clone(),
+ merchant_id: payment_attempt.merchant_id.to_owned(),
+ profile_id: payment_attempt.profile_id.to_owned(),
+ amount: payment_attempt.get_total_amount(),
+ success_based_routing_connector: first_merchant_success_based_connector_label
+ .to_string(),
+ payment_connector: payment_connector.to_string(),
+ payment_method_type: payment_attempt.payment_method_type,
+ currency: payment_attempt.currency,
+ payment_method: payment_attempt.payment_method,
+ capture_method: payment_attempt.capture_method,
+ authentication_type: payment_attempt.authentication_type,
+ payment_status: payment_attempt.status,
+ conclusive_classification: outcome,
+ created_at: common_utils::date_time::now(),
+ global_success_based_connector: Some(
+ first_global_success_based_connector.label.to_string(),
+ ),
+ };
+
+ state
+ .store
+ .insert_dynamic_routing_stat_entry(dynamic_routing_stats)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Unable to push dynamic routing stats to db")?;
+ };
client
.update_success_rate(
diff --git a/crates/router/src/db/dynamic_routing_stats.rs b/crates/router/src/db/dynamic_routing_stats.rs
index d22f4fdd40b..f78655db0b3 100644
--- a/crates/router/src/db/dynamic_routing_stats.rs
+++ b/crates/router/src/db/dynamic_routing_stats.rs
@@ -16,6 +16,19 @@ pub trait DynamicRoutingStatsInterface {
&self,
dynamic_routing_stat_new: storage::DynamicRoutingStatsNew,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>;
+
+ async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
+ &self,
+ attempt_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError>;
+
+ async fn update_dynamic_routing_stats(
+ &self,
+ attempt_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
+ data: storage::DynamicRoutingStatsUpdate,
+ ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -31,6 +44,33 @@ impl DynamicRoutingStatsInterface for Store {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
+
+ async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
+ &self,
+ attempt_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::DynamicRoutingStats::find_optional_by_attempt_id_merchant_id(
+ &conn,
+ attempt_id,
+ merchant_id,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
+ async fn update_dynamic_routing_stats(
+ &self,
+ attempt_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
+ data: storage::DynamicRoutingStatsUpdate,
+ ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::DynamicRoutingStats::update(&conn, attempt_id, merchant_id, data)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
}
#[async_trait::async_trait]
@@ -42,6 +82,23 @@ impl DynamicRoutingStatsInterface for MockDb {
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
+
+ async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
+ &self,
+ _attempt_id: String,
+ _merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> {
+ Err(errors::StorageError::MockDbError)?
+ }
+
+ async fn update_dynamic_routing_stats(
+ &self,
+ _attempt_id: String,
+ _merchant_id: &common_utils::id_type::MerchantId,
+ _data: storage::DynamicRoutingStatsUpdate,
+ ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
+ Err(errors::StorageError::MockDbError)?
+ }
}
#[async_trait::async_trait]
@@ -55,4 +112,25 @@ impl DynamicRoutingStatsInterface for KafkaStore {
.insert_dynamic_routing_stat_entry(dynamic_routing_stat)
.await
}
+
+ async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
+ &self,
+ attempt_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
+ ) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> {
+ self.diesel_store
+ .find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(attempt_id, merchant_id)
+ .await
+ }
+
+ async fn update_dynamic_routing_stats(
+ &self,
+ attempt_id: String,
+ merchant_id: &common_utils::id_type::MerchantId,
+ data: storage::DynamicRoutingStatsUpdate,
+ ) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
+ self.diesel_store
+ .update_dynamic_routing_stats(attempt_id, merchant_id, data)
+ .await
+ }
}
diff --git a/crates/router/src/types/storage/dynamic_routing_stats.rs b/crates/router/src/types/storage/dynamic_routing_stats.rs
index ba692a25255..2b1bc3f4a45 100644
--- a/crates/router/src/types/storage/dynamic_routing_stats.rs
+++ b/crates/router/src/types/storage/dynamic_routing_stats.rs
@@ -1 +1,3 @@
-pub use diesel_models::dynamic_routing_stats::{DynamicRoutingStats, DynamicRoutingStatsNew};
+pub use diesel_models::dynamic_routing_stats::{
+ DynamicRoutingStats, DynamicRoutingStatsNew, DynamicRoutingStatsUpdate,
+};
|
refactor
|
change insert operation to upsert for dynamic_routing_stats (#7398)
|
71b52024c296548156cd80950010a2f1266906fb
|
2024-09-10 19:52:19
|
Sai Harsha Vardhan
|
feat(router): mask keys in `connector_account_details` for merchant_connector_response in mca retrieve flow (#5848)
| false
|
diff --git a/crates/hyperswitch_domain_models/src/router_data.rs b/crates/hyperswitch_domain_models/src/router_data.rs
index 122acbb0adc..df0b63833d9 100644
--- a/crates/hyperswitch_domain_models/src/router_data.rs
+++ b/crates/hyperswitch_domain_models/src/router_data.rs
@@ -7,7 +7,7 @@ use common_utils::{
types::MinorUnit,
};
use error_stack::ResultExt;
-use masking::Secret;
+use masking::{ExposeInterface, Secret};
use crate::{payment_address::PaymentAddress, payment_method_data};
@@ -136,6 +136,74 @@ impl ConnectorAuthType {
"ConnectorAuthType",
))
}
+
+ // show only first and last two digits of the key and mask others with *
+ // mask the entire key if it's length is less than or equal to 4
+ fn mask_key(&self, key: String) -> Secret<String> {
+ let key_len = key.len();
+ let masked_key = if key_len <= 4 {
+ "*".repeat(key_len)
+ } else {
+ // Show the first two and last two characters, mask the rest with '*'
+ let mut masked_key = String::new();
+ let key_len = key.len();
+ // Iterate through characters by their index
+ for (index, character) in key.chars().enumerate() {
+ if index < 2 || index >= key_len - 2 {
+ masked_key.push(character); // Keep the first two and last two characters
+ } else {
+ masked_key.push('*'); // Mask the middle characters
+ }
+ }
+ masked_key
+ };
+ Secret::new(masked_key)
+ }
+
+ // Mask the keys in the auth_type
+ pub fn get_masked_keys(&self) -> Self {
+ match self {
+ Self::TemporaryAuth => Self::TemporaryAuth,
+ Self::NoKey => Self::NoKey,
+ Self::HeaderKey { api_key } => Self::HeaderKey {
+ api_key: self.mask_key(api_key.clone().expose()),
+ },
+ Self::BodyKey { api_key, key1 } => Self::BodyKey {
+ api_key: self.mask_key(api_key.clone().expose()),
+ key1: self.mask_key(key1.clone().expose()),
+ },
+ Self::SignatureKey {
+ api_key,
+ key1,
+ api_secret,
+ } => Self::SignatureKey {
+ api_key: self.mask_key(api_key.clone().expose()),
+ key1: self.mask_key(key1.clone().expose()),
+ api_secret: self.mask_key(api_secret.clone().expose()),
+ },
+ Self::MultiAuthKey {
+ api_key,
+ key1,
+ api_secret,
+ key2,
+ } => Self::MultiAuthKey {
+ api_key: self.mask_key(api_key.clone().expose()),
+ key1: self.mask_key(key1.clone().expose()),
+ api_secret: self.mask_key(api_secret.clone().expose()),
+ key2: self.mask_key(key2.clone().expose()),
+ },
+ Self::CurrencyAuthKey { auth_key_map } => Self::CurrencyAuthKey {
+ auth_key_map: auth_key_map.clone(),
+ },
+ Self::CertificateAuth {
+ certificate,
+ private_key,
+ } => Self::CertificateAuth {
+ certificate: self.mask_key(certificate.clone().expose()),
+ private_key: self.mask_key(private_key.clone().expose()),
+ },
+ }
+ }
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone)]
diff --git a/crates/router/src/types/transformers.rs b/crates/router/src/types/transformers.rs
index a12c3593f38..5d8c8a87bd2 100644
--- a/crates/router/src/types/transformers.rs
+++ b/crates/router/src/types/transformers.rs
@@ -7,7 +7,7 @@ use api_models::{
use common_utils::{
consts::X_HS_LATENCY,
crypto::Encryptable,
- ext_traits::{StringExt, ValueExt},
+ ext_traits::{Encode, StringExt, ValueExt},
fp_utils::when,
pii,
types::MinorUnit,
@@ -15,7 +15,7 @@ use common_utils::{
use diesel_models::enums as storage_enums;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::payments::payment_intent::CustomerData;
-use masking::{ExposeInterface, PeekInterface};
+use masking::{ExposeInterface, PeekInterface, Secret};
use super::domain;
use crate::{
@@ -1103,13 +1103,29 @@ impl ForeignTryFrom<domain::MerchantConnectorAccount>
}
None => None,
};
+ // parse the connector_account_details into ConnectorAuthType
+ let connector_account_details: hyperswitch_domain_models::router_data::ConnectorAuthType =
+ item.connector_account_details
+ .clone()
+ .into_inner()
+ .parse_value("ConnectorAuthType")
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed while parsing value for ConnectorAuthType")?;
+ // get the masked keys from the ConnectorAuthType and encode it to secret value
+ let masked_connector_account_details = Secret::new(
+ connector_account_details
+ .get_masked_keys()
+ .encode_to_value()
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to encode ConnectorAuthType")?,
+ );
#[cfg(feature = "v2")]
let response = Self {
id: item.get_id(),
connector_type: item.connector_type,
connector_name: item.connector_name,
connector_label: item.connector_label,
- connector_account_details: item.connector_account_details.into_inner(),
+ connector_account_details: masked_connector_account_details,
disabled: item.disabled,
payment_methods_enabled,
metadata: item.metadata,
@@ -1149,7 +1165,7 @@ impl ForeignTryFrom<domain::MerchantConnectorAccount>
connector_name: item.connector_name,
connector_label: item.connector_label,
merchant_connector_id: item.merchant_connector_id,
- connector_account_details: item.connector_account_details.into_inner(),
+ connector_account_details: masked_connector_account_details,
test_mode: item.test_mode,
disabled: item.disabled,
payment_methods_enabled,
|
feat
|
mask keys in `connector_account_details` for merchant_connector_response in mca retrieve flow (#5848)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.